Example #1
0
class AppWindow(QtGui.QMainWindow, hackYourOwn.Ui_MainWindow,utilitiesClass):
	def __init__(self, parent=None,**kwargs):
		super(AppWindow, self).__init__(parent)
		self.setupUi(self)
		self.I=kwargs.get('I',None)
		self.setWindowTitle('pyqtgraph example: FlowchartCustomNode')

		## Create an empty flowchart with a single input and output
		self.fc = Flowchart(terminals={
			'dataIn': {'io': 'in'},
			
		})
		self.w = self.fc.widget()
		self.WidgetLayout.addWidget(self.fc.widget())

		self.plot1 = self.add2DPlot(self.ExperimentLayout)
		self.plot2 = self.add2DPlot(self.ExperimentLayout)
		self.curve1 = self.addCurve(self.plot1)
		self.curve2 = self.addCurve(self.plot2)
		self.curve1.setData([1,2,3],[5,6,7])

		self.library = fclib.LIBRARY.copy() # start with the default node set
		self.library.addNodeType(PlotViewNode, [('Display',)])
		self.library.addNodeType(CaptureNode, [('Acquire',)])
		self.fc.setLibrary(self.library)


		## Now we will programmatically add nodes to define the function of the flowchart.
		## Normally, the user will do this manually or by loading a pre-generated
		## flowchart file.

		self.cap = self.fc.createNode('Capture', pos=(0, 0))
		self.cap.setI(self.I)

		self.v1Node = self.fc.createNode('PlotView', pos=(0, -150))
		self.v1Node.setView(self.curve1)

		self.v2Node = self.fc.createNode('PlotView', pos=(150, -150))
		self.v2Node.setView(self.curve2)

		self.fc.connectTerminals(self.fc['dataIn'], self.cap['dataIn'])
		self.fc.connectTerminals(self.cap['dataOut'], self.v1Node['data'])
		#self.fc.connectTerminals(self.fc['dataIn'], self.v2Node['data'])

		self.fc.setInput(dataIn=True)


	def run(self):
		self.fc.setInput(dataIn=True)

	def __del__(self):
		#self.looptimer.stop()
		print ('bye')

	def closeEvent(self, event):
		self.finished=True
Example #2
0
class AppWindow(QtGui.QMainWindow, hackYourOwn.Ui_MainWindow, utilitiesClass):
    def __init__(self, parent=None, **kwargs):
        super(AppWindow, self).__init__(parent)
        self.setupUi(self)
        self.I = kwargs.get('I', None)
        self.setWindowTitle('pyqtgraph example: FlowchartCustomNode')

        ## Create an empty flowchart with a single input and output
        self.fc = Flowchart(terminals={
            'dataIn': {
                'io': 'in'
            },
        })
        self.w = self.fc.widget()
        self.WidgetLayout.addWidget(self.fc.widget())

        self.plot1 = self.add2DPlot(self.ExperimentLayout)
        self.plot2 = self.add2DPlot(self.ExperimentLayout)
        self.curve1 = self.addCurve(self.plot1)
        self.curve2 = self.addCurve(self.plot2)
        self.curve1.setData([1, 2, 3], [5, 6, 7])

        self.library = fclib.LIBRARY.copy()  # start with the default node set
        self.library.addNodeType(PlotViewNode, [('Display', )])
        self.library.addNodeType(CaptureNode, [('Acquire', )])
        self.fc.setLibrary(self.library)

        ## Now we will programmatically add nodes to define the function of the flowchart.
        ## Normally, the user will do this manually or by loading a pre-generated
        ## flowchart file.

        self.cap = self.fc.createNode('Capture', pos=(0, 0))
        self.cap.setI(self.I)

        self.v1Node = self.fc.createNode('PlotView', pos=(0, -150))
        self.v1Node.setView(self.curve1)

        self.v2Node = self.fc.createNode('PlotView', pos=(150, -150))
        self.v2Node.setView(self.curve2)

        self.fc.connectTerminals(self.fc['dataIn'], self.cap['dataIn'])
        self.fc.connectTerminals(self.cap['dataOut'], self.v1Node['data'])
        #self.fc.connectTerminals(self.fc['dataIn'], self.v2Node['data'])

        self.fc.setInput(dataIn=True)

    def run(self):
        self.fc.setInput(dataIn=True)

    def __del__(self):
        #self.looptimer.stop()
        print('bye')

    def closeEvent(self, event):
        self.finished = True
Example #3
0
    def initialize(self):
        pvhistory = []
        lvhistory = []
        n = 0
        fc = Flowchart(terminals={'in': {'io': 'out'}, 'op': {'io': 'in'}})

        nodeList = fc.nodes()
        fc.removeNode(nodeList['Input'])
        fc.removeNode(nodeList['Output'])

        for i in self.mappings["vgs"]:

            vgNode = Node(i, allowRemove=False, allowAddOutput=False)
            fc.addNode(vgNode, i, [0, n])
            Node.addTerminal(vgNode, 'O', io='out', multi=True)
            Node.addTerminal(vgNode, 'I', io='in', multi=True)

            for j in self.mappings["mappings"]:
                if i == j[1]:
                    if j[2] not in lvhistory:
                        lvNode = Node(j[2],
                                      allowRemove=False,
                                      allowAddOutput=False)
                        fc.addNode(lvNode, j[2], [200, n])
                        Node.addTerminal(lvNode, 'I', io='in')
                        try:
                            fc.connectTerminals(vgNode['O'], lvNode['I'])
                        except:
                            pass
                            #cvar2 = Node.addOutput(vgNode)
                            #fc.connectTerminals(vgNode['Out'],cvar2)

                        lvhistory.append(j[2])
                    else:
                        pass

                    if j[0] not in pvhistory:
                        pvNode = Node(j[0],
                                      allowRemove=False,
                                      allowAddOutput=False)
                        fc.addNode(pvNode, j[0], [-400, n])
                        Node.addTerminal(pvNode, 'O', io='out')
                        try:
                            fc.connectTerminals(pvNode['O'], vgNode['I'])
                        except:
                            pass
                            #cvar1 = Node.addInput(vgNode)
                            #fc.connectTerminals(pvNode['Out'], cvar1)

                        pvhistory.append(j[0])
                    else:
                        pass
                    n = n + 200
        #vgNode.ctrls['doubleSpin'].setValue(5)
        #lvNode = fc.createNode('PlotWidget', 'lv')

        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.layout.addWidget(fc.widget())
Example #4
0
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Fourier Transformation")
        self.showFullScreen()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        fc = Flowchart(terminals={
            'dataIn': {
                'io': 'in'
            },
            'dataOut': {
                'io': 'out'
            }
        })

        self.layout.addWidget(fc.widget(), 0, 0, 2, 1)

        pw1 = pg.PlotWidget()
        pw2 = pg.PlotWidget()
        pw1.getPlotItem().setLabel('left', text='Amplitude')
        pw1.getPlotItem().setLabel('bottom', text='Time')
        pw2.getPlotItem().setLabel('left', text='Y(freq)')
        pw2.getPlotItem().setLabel('bottom', text='F(Hz)')
        self.layout.addWidget(pw1, 0, 1)
        self.layout.addWidget(pw2, 1, 1)

        sampling_rate = 150.0
        sampling_interval = 1.0 / sampling_rate
        # Abtastfrequenz f = (1/t)
        time_vector = np.arange(0, 1, sampling_interval)

        signal_frequency = 10
        data = np.sin(2 * np.pi * signal_frequency * time_vector)

        print data

        fc.setInput(dataIn=data)

        pw1Node = fc.createNode('PlotWidget', pos=(0, -150))
        pw1Node.setPlot(pw1)

        pw2Node = fc.createNode('PlotWidget', pos=(150, -150))
        pw2Node.setPlot(pw2)

        fNode = fc.createNode('AnalyzeNode', pos=(0, 0))

        fc.connectTerminals(fc['dataIn'], fNode['dataIn'])
        fc.connectTerminals(fc['dataIn'], pw1Node['In'])
        fc.connectTerminals(fNode['dataOut'], pw2Node['In'])
        fc.connectTerminals(fNode['dataOut'], fc['dataOut'])
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Fourier Transformation")
        self.showFullScreen()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        fc = Flowchart(terminals={
            'dataIn': {'io': 'in'},
            'dataOut': {'io': 'out'}
        })

        self.layout.addWidget(fc.widget(), 0, 0, 2, 1)

        pw1 = pg.PlotWidget()
        pw2 = pg.PlotWidget()
        pw1.getPlotItem().setLabel('left', text='Amplitude')
        pw1.getPlotItem().setLabel('bottom', text='Time')
        pw2.getPlotItem().setLabel('left', text='Y(freq)')
        pw2.getPlotItem().setLabel('bottom', text='F(Hz)')
        self.layout.addWidget(pw1, 0, 1)
        self.layout.addWidget(pw2, 1, 1)

        sampling_rate = 150.0
        sampling_interval = 1.0 / sampling_rate; # Abtastfrequenz f = (1/t)
        time_vector = np.arange(0, 1, sampling_interval)

        signal_frequency = 10
        data = np.sin(2 * np.pi * signal_frequency * time_vector)

        print data

        fc.setInput(dataIn=data)

        pw1Node = fc.createNode('PlotWidget', pos=(0, -150))
        pw1Node.setPlot(pw1)

        pw2Node = fc.createNode('PlotWidget', pos=(150, -150))
        pw2Node.setPlot(pw2)

        fNode = fc.createNode('AnalyzeNode', pos=(0, 0))

        fc.connectTerminals(fc['dataIn'], fNode['dataIn'])
        fc.connectTerminals(fc['dataIn'], pw1Node['In'])
        fc.connectTerminals(fNode['dataOut'], pw2Node['In'])
        fc.connectTerminals(fNode['dataOut'], fc['dataOut'])
    def init_filters(self):
        ## Create flowchart, define input/output terminals
        fc = Flowchart(terminals={
            'dataIn': {
                'io': 'in'
            },
            'dataOut': {
                'io': 'out'
            }
        })
        ## Add flowchart control panel to the main window
        self.filter_d.layout.addWidget(fc.widget(), 0, 0, 2, 1)
        ## Add two plot widgets
        pw1 = pg.PlotWidget()
        pw2 = pg.PlotWidget()
        self.filter_d.layout.addWidget(pw1, 0, 1)
        self.filter_d.layout.addWidget(pw2, 1, 1)
        ## generate signal data to pass through the flowchart
        data = np.random.normal(size=1000)
        data[200:300] += 1
        data += np.sin(np.linspace(0, 100, 1000))
        data = metaarray.MetaArray(data,
                                   info=[{
                                       'name':
                                       'Time',
                                       'values':
                                       np.linspace(0, 1.0, len(data))
                                   }, {}])
        ## Feed data into the input terminal of the flowchart
        fc.setInput(dataIn=data)
        ## populate the flowchart with a basic set of processing nodes.
        ## (usually we let the user do this)
        plotList = {'Top Plot': pw1, 'Bottom Plot': pw2}

        pw1Node = fc.createNode('PlotWidget', pos=(0, -150))
        pw1Node.setPlotList(plotList)
        pw1Node.setPlot(pw1)

        pw2Node = fc.createNode('PlotWidget', pos=(150, -150))
        pw2Node.setPlot(pw2)
        pw2Node.setPlotList(plotList)

        fNode = fc.createNode('GaussianFilter', pos=(0, 0))
        fNode.ctrls['sigma'].setValue(5)
        fc.connectTerminals(fc['dataIn'], fNode['In'])
        fc.connectTerminals(fc['dataIn'], pw1Node['In'])
        fc.connectTerminals(fNode['Out'], pw2Node['In'])
        fc.connectTerminals(fNode['Out'], fc['dataOut'])
    def __init__(self, imagepath='images/'):
        super(FlowChartWidget, self).__init__()
        
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        self.imagepath = imagepath

        layout = QVBoxLayout()
        
        ## Create flowchart, define input/output terminals
        fc = Flowchart(terminals={
            'dataIn': {'io': 'in'},
            'dataOut': {'io': 'out'}    
            })
        w = fc.widget()
        layout.addWidget(w)
        self.setLayout(layout)
    def __init__(self, imagepath='images/'):
        super(FlowChartWidget, self).__init__()

        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        self.imagepath = imagepath

        layout = QVBoxLayout()

        ## Create flowchart, define input/output terminals
        fc = Flowchart(terminals={
            'dataIn': {
                'io': 'in'
            },
            'dataOut': {
                'io': 'out'
            }
        })
        w = fc.widget()
        layout.addWidget(w)
        self.setLayout(layout)
Example #9
0
def setup_displaying_of_plots():
    """
    setup of all PyQt and PyQtGraph related objects for further use

    :return: newly constructed window object, central_widget object,
             layout object and flowchart object
    """
    win = QtGui.QMainWindow()
    win.setWindowTitle("Analyze")

    central_widget = QtGui.QWidget()

    win.setCentralWidget(central_widget)

    layout = QtGui.QGridLayout()
    central_widget.setLayout(layout)

    fc = Flowchart(terminals={})

    layout.addWidget(fc.widget(), 0, 0, 2, 1)

    return win, central_widget, layout, fc
class Demo(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Pointing Device")
        self.show()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.buffer_amount = 20

        self.fc = Flowchart(terminals={
            'dataIn': {'io': 'in'},
            'dataOut': {'io': 'out'}
        })
        self.layout.addWidget(self.fc.widget(), 0, 0, 2, 1)

        self.configNodes()
        self.configScatterPlot()

        self.getWiimote()

    def getWiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    # create and connect nodes
    def configNodes(self):
        self.pointVisNode = self.fc.createNode('Vis3D', pos=(-150, 150))
        self.wiimoteNode = self.fc.createNode('Wiimote', pos=(0, 0), )
        self.bufferNode = self.fc.createNode('Buffer', pos=(0, -150))

        self.buffer_amount = self.bufferNode.getBufferSize()

        self.fc.connectTerminals(
            self.wiimoteNode['irVals'],
            self.bufferNode['dataIn'])
        self.fc.connectTerminals(
            self.bufferNode['dataOut'],
            self.pointVisNode['irVals'])

    # create and config scatter plot item
    def configScatterPlot(self):
        gview = pg.GraphicsLayoutWidget()
        self.layout.addWidget(gview, 0, 1, 2, 1)

        plot = gview.addPlot()
        self.scatter = pg.ScatterPlotItem(
            size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 120))
        plot.addItem(self.scatter)
        plot.setXRange(-1000, 200)
        plot.setYRange(-1000, 200)

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()

    # do actions in loop
    def update(self):
        outputValues = self.pointVisNode.outputValues()

        isX1Valid = outputValues['irX1'] is not None
        isY1Valid = outputValues['irY1'] is not None
        isX2Valid = outputValues['irX2'] is not None
        isY2Valid = outputValues['irY2'] is not None

        if isX1Valid and isX2Valid and isY1Valid and isY2Valid:
            distance = self.calcDistance(outputValues)
            if distance > 0:
                size = 3000 * (1 / distance * 2)

                self.scatter.setData(
                    pos=[[
                        -outputValues['irX1'],
                        -outputValues['irY1']],
                        [-outputValues['irX2'], -outputValues['irY2']]],
                    size=size, pxMode=True)

        # raise or lower buffer amount with +/- keys
        if self.wiimoteNode.wiimote is not None:
            if self.wiimoteNode.wiimote.buttons['Plus']:
                self.buffer_amount += 1
                self.bufferNode.setBufferSize(self.buffer_amount)
            elif self.wiimoteNode.wiimote.buttons['Minus']:
                if self.buffer_amount > 1:
                    self.buffer_amount -= 1
                    self.bufferNode.setBufferSize(self.buffer_amount)

        pyqtgraph.QtGui.QApplication.processEvents()

    # calc distance from wiimote to the two lights
    # reference: http://wiiphysics.site88.net/physics.html
    def calcDistance(self, outputValues):
        x1 = outputValues['irX1']
        y1 = outputValues['irY1']
        x2 = outputValues['irX2']
        y2 = outputValues['irY2']

        # init wiimote's camera angles
        hfov = 41
        vfov = 31

        # set constant distance between the two lights
        lightDistance = 30

        fov = ((hfov / 1024.0) + (vfov / 768.0)) / 2.0

        r = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))

        alpha = (fov * r) / 4.0

        tan = math.tan(math.radians(alpha))

        try:
            camDistance = lightDistance / (2 * tan)
        except:
            camDistance = 0
        return camDistance
class Demo(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Pointing Device")
        self.show()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.fc = Flowchart(terminals={
            'dataIn': {
                'io': 'in'
            },
            'dataOut': {
                'io': 'out'
            }
        })
        self.layout.addWidget(self.fc.widget(), 0, 0, 2, 1)

        self.configNodes()
        self.configScatterPlot()

        self.getWiimote()

    # connect to wiimote and config wiimote node
    def getWiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    # create and connect nodes
    def configNodes(self):
        self.pointVisNode = self.fc.createNode('Vis2D', pos=(-150, 150))
        self.wiimoteNode = self.fc.createNode(
            'Wiimote',
            pos=(0, 0),
        )
        self.bufferNode = self.fc.createNode('Buffer', pos=(0, -150))

        self.buffer_amount = self.bufferNode.getBufferSize()

        self.fc.connectTerminals(self.wiimoteNode['irVals'],
                                 self.bufferNode['dataIn'])
        self.fc.connectTerminals(self.bufferNode['dataOut'],
                                 self.pointVisNode['irVals'])

    # create and config scatter plot item
    def configScatterPlot(self):
        gview = pg.GraphicsLayoutWidget()
        self.layout.addWidget(gview, 0, 1, 2, 1)
        plot = gview.addPlot()
        self.scatter = pg.ScatterPlotItem(size=10,
                                          pen=pg.mkPen(None),
                                          brush=pg.mkBrush(255, 255, 255, 120))
        plot.addItem(self.scatter)
        plot.setXRange(-1000, 200)
        plot.setYRange(-1000, 200)

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()

    # do actions in loop
    def update(self):
        outputValues = self.pointVisNode.outputValues()

        if outputValues['irX'] is not None and outputValues['irY'] is not None:
            self.scatter.setData(
                pos=[[-outputValues['irX'], -outputValues['irY']]])

        # raise or lower buffer amount with +/- keys
        if self.wiimoteNode.wiimote is not None:
            if self.wiimoteNode.wiimote.buttons['Plus']:
                self.buffer_amount += 1
                self.bufferNode.setBufferSize(self.buffer_amount)
            elif self.wiimoteNode.wiimote.buttons['Minus']:
                if self.buffer_amount > 1:
                    self.buffer_amount -= 1
                    self.bufferNode.setBufferSize(self.buffer_amount)

        pyqtgraph.QtGui.QApplication.processEvents()
class Demo(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Gesture Recognizer")
        self.showFullScreen()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.fc = Flowchart(terminals={
            'dataIn': {
                'io': 'in'
            },
            'dataOut': {
                'io': 'out'
            }
        })
        self.layout.addWidget(self.fc.widget(), 0, 0, 2, 1)

        self.path = {'x': [], 'y': []}
        self.threshold = 50
        self.sample_size = 64
        self.default_msg = 'No template matched...'
        self.error_ir_msg = 'No ir-values received'
        self.error_wiimote_msg = 'No wiimote connected'
        self.error_template_msg = 'No template could be created'

        self.pressed_key = None

        self.dollar = Recognizer()

        self.config_nodes()
        self.config_layout()
        self.setup_templates()

        self.get_wiimote()

    '''
    The command-line argument is parsed and used to establish
    a connection to the wiimote
    '''

    def get_wiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    '''
    A wiimote node and a buffer node are created as well as a
    custom node which returns the position of the most intense
    light source detected by the wiimote
    '''

    def config_nodes(self):
        self.wiimoteNode = self.fc.createNode(
            'Wiimote',
            pos=(0, 0),
        )
        self.bufferNode = self.fc.createNode('Buffer', pos=(0, -150))
        self.pointVisNode = self.fc.createNode('Vis2D', pos=(-150, 150))

        self.bufferNode.setBufferSize(4)

        self.fc.connectTerminals(self.wiimoteNode['irVals'],
                                 self.bufferNode['dataIn'])
        self.fc.connectTerminals(self.bufferNode['dataOut'],
                                 self.pointVisNode['irVals'])

    '''
    A scatterplot is used to display the infrafred data and a text label
    should indicate if the user input matches a predefined template
    '''

    def config_layout(self):
        gview = pg.GraphicsLayoutWidget()
        self.layout.addWidget(gview, 0, 1, 2, 1)
        self.templatePlot = gview.addPlot()
        self.templateScatter = pg.ScatterPlotItem(size=10,
                                                  pen=pg.mkPen(None),
                                                  brush=pg.mkBrush(
                                                      0, 255, 0, 120))
        self.templatePlot.addItem(self.templateScatter)
        self.templatePlot.setTitle("Template")
        self.setRange(self.templatePlot, False)

        # self.layout.addWidget(gview, 0, 1, 2, 1)
        self.pathPlot = gview.addPlot()
        self.pathScatter = pg.ScatterPlotItem(size=10,
                                              pen=pg.mkPen(None),
                                              brush=pg.mkBrush(
                                                  255, 255, 255, 120))
        self.pathPlot.addItem(self.pathScatter)
        self.pathPlot.setTitle("Path")
        self.setRange(self.pathPlot, False)

        self.label = QtGui.QLabel()
        self.label.setText(self.default_msg)
        font = QtGui.QFont("Arial")
        font.setPointSize(32)
        self.label.setFont(font)
        self.layout.addWidget(self.label, 2, 1, 1, 1)

    '''
    Three default templates are added to the recognizer
    '''

    def setup_templates(self):
        circlePoints = [(269, 84), (263, 86), (257, 92), (253, 98), (249, 104),
                        (245, 114), (243, 122), (239, 132), (237, 142),
                        (235, 152), (235, 162), (235, 172), (235, 180),
                        (239, 190), (245, 198), (251, 206), (259, 212),
                        (267, 216), (275, 218), (281, 222), (287, 224),
                        (295, 224), (301, 226), (311, 226), (319, 226),
                        (329, 226), (339, 226), (349, 226), (352, 226),
                        (360, 226), (362, 225), (366, 219), (367, 217),
                        (367, 209), (367, 206), (367, 198), (367, 190),
                        (367, 182), (367, 174), (365, 166), (363, 158),
                        (359, 152), (355, 146), (353, 138), (349, 134),
                        (345, 130), (341, 124), (340, 122), (338, 121),
                        (337, 119), (336, 117), (334, 116), (332, 115),
                        (331, 114), (327, 110), (325, 109), (323, 109),
                        (321, 108), (320, 108), (318, 107), (316, 107),
                        (315, 107), (314, 107), (313, 107), (312, 107),
                        (311, 107), (310, 107), (309, 106), (308, 106),
                        (307, 105), (306, 105), (305, 105), (304, 105),
                        (303, 104), (302, 104), (301, 104), (300, 104),
                        (299, 103), (298, 103), (296, 102), (295, 101),
                        (293, 101), (292, 100), (291, 100), (290, 100),
                        (289, 100), (288, 100), (288, 99), (287, 99),
                        (287, 99)]
        squarePoints = [(193, 123), (193, 131), (193, 139), (195, 151),
                        (197, 161), (199, 175), (201, 187), (205, 201),
                        (207, 213), (209, 225), (213, 235), (213, 243),
                        (215, 251), (215, 254), (217, 262), (217, 264),
                        (217, 266), (217, 267), (218, 267), (219, 267),
                        (221, 267), (224, 267), (227, 267), (237, 267),
                        (247, 265), (259, 263), (273, 261), (287, 261),
                        (303, 259), (317, 257), (331, 255), (347, 255),
                        (361, 253), (375, 253), (385, 253), (395, 251),
                        (403, 249), (406, 249), (408, 249), (408, 248),
                        (409, 248), (409, 246), (409, 245), (409, 242),
                        (409, 234), (409, 226), (409, 216), (407, 204),
                        (407, 194), (405, 182), (403, 172), (403, 160),
                        (401, 150), (399, 140), (399, 130), (397, 122),
                        (397, 119), (397, 116), (396, 114), (396, 112),
                        (396, 111), (396, 110), (396, 109), (396, 108),
                        (396, 107), (396, 106), (396, 105), (394, 105),
                        (392, 105), (384, 105), (376, 105), (364, 105),
                        (350, 107), (334, 109), (318, 111), (306, 113),
                        (294, 115), (286, 117), (278, 117), (272, 119),
                        (269, 119), (263, 121), (260, 121), (254, 123),
                        (251, 123), (245, 125), (243, 125), (242, 125),
                        (241, 126), (240, 126), (238, 127), (236, 127),
                        (232, 128), (231, 128), (231, 129), (230, 129),
                        (228, 129), (227, 129), (226, 129), (225, 129),
                        (224, 129), (223, 129), (222, 129), (221, 130),
                        (221, 130)]
        trianglePoints = \
            [(282, 83), (281, 85), (277, 91), (273, 97),
             (267, 105), (261, 113), (253, 123), (243, 133),
             (235, 141), (229, 149), (221, 153), (217, 159),
             (216, 160), (215, 161), (214, 162), (216, 162),
             (218, 162), (221, 162), (227, 164), (233, 166),
             (241, 166), (249, 166), (259, 166), (271, 166),
             (283, 166), (297, 166), (309, 164), (323, 164),
             (335, 162), (345, 162), (353, 162), (361, 160),
             (363, 159), (365, 159), (366, 158), (367, 158),
             (368, 157), (369, 157), (370, 156), (371, 156),
             (371, 155), (372, 155), (372, 153), (372, 152),
             (372, 151), (372, 149), (372, 147), (371, 145),
             (367, 141), (363, 137), (359, 133), (353, 129),
             (349, 125), (343, 121), (337, 119), (333, 115),
             (327, 111), (325, 110), (324, 109), (320, 105),
             (318, 104), (314, 100), (312, 99), (310, 98),
             (306, 94), (305, 93), (303, 92), (301, 91),
             (300, 90), (298, 89), (297, 88), (296, 88),
             (295, 87), (294, 87), (293, 87), (293, 87)]

        self.dollar.addTemplate('circle', circlePoints)
        self.dollar.addTemplate('square', squarePoints)
        self.dollar.addTemplate('triangle', trianglePoints)

    def update(self):
        # get biggest light's x/y values
        outputValues = self.pointVisNode.outputValues()
        if outputValues['irX'] is not None and outputValues['irY'] is not None:
            if self.wiimoteNode.wiimote is not None:
                if self.wiimoteNode.wiimote.buttons['A']:
                    # collect values and set state
                    self.construct_path(outputValues)
                    self.pressed_key = 'A'
                elif self.wiimoteNode.wiimote.buttons['B']:
                    # collect values and set state
                    self.construct_path(outputValues)
                    self.pressed_key = 'B'
                elif self.path['x'] is not None and len(self.path['x']) > 0:
                    # draw path when A or B is released after collecting path
                    self.draw_path()
            else:
                self.templateScatter.clear()
                self.pathScatter.clear()
                self.display_message(self.error_wiimote_msg)
        else:
            self.templateScatter.clear()
            self.pathScatter.clear()
            self.display_message(self.error_ir_msg)

        # update range to remove old graphics
        self.setRange(self.templatePlot, False)
        self.setRange(self.pathPlot, False)

        pyqtgraph.QtGui.QApplication.processEvents()

    '''
    The user input is added as a new template
    '''

    def create_template(self):
        points = []
        # combine x/y path arrays to one point array
        for i in range(0, len(self.path['x'])):
            points.append([self.path['x'][i], self.path['y'][i]])

        # avoid devision by zero
        if len(points) > 3:
            # name and add template
            name = 'tpl_' + str((len(self.dollar.templates) + 1))
            self.label.setText("Created template " + name)
            self.dollar.addTemplate(name, points)
        else:
            self.display_message(self.error_template_msg)

    '''
    The user input is compared to all available templates and depending
    on the accordance a text message is displayed
    '''

    def compare_template(self):
        points = self.combineXYPoints()

        # try recognizing points. get name of template that matches most
        # and its amount of matching
        if len(points) < 3:
            self.display_message(self.default_msg)
            self.templateScatter.clear()
            return

        name, score = self.dollar.recognize(points)

        score = score * 100
        if score > self.threshold:
            # template matches good enough
            self.display_message(name)

            # get template by name
            template = [t for t in self.dollar.templates if t.name == name][0]

            tpl_points = []

            if template.points is None:
                # template doesn't match good enough
                self.display_message(self.default_msg)
                self.templateScatter.clear()
            else:
                # collect and display template points
                for i in range(0, len(template.points)):
                    tpl_points.append(
                        [template.points[i].x, template.points[i].y])
                # display points
                self.templateScatter.addPoints(pos=np.array(tpl_points),
                                               brush=pg.mkBrush(
                                                   0, 255, 0, 120))
        else:
            # template doesn't match good enough
            self.display_message(self.default_msg)
            self.templateScatter.clear()

    '''
    The infrafred values are stored in a dictionary
    '''

    def construct_path(self, irValues):
        self.templateScatter.clear()
        self.pathScatter.clear()
        self.path['x'].append(irValues['irX'])
        self.path['y'].append(irValues['irY'])

    '''
    The stored infrafred values are passed to a scatterplot
    '''

    def draw_path(self):
        path = self.combineXYPoints()
        points = []
        for i in range(0, len(path)):
            points.append(Point(path[i][0], path[i][1]))

        # display points
        if len(points) >= 3:
            points = resample(points, self.sample_size)
            if points is not None:
                path = []
                for i in range(0, len(points)):
                    path.append([points[i].x, points[i].y])

                self.pathScatter.addPoints(pos=np.array(path),
                                           brush=pg.mkBrush(
                                               255, 255, 255, 120))

                # handle pressed keys
                if self.pressed_key is 'A':
                    self.compare_template()
                elif self.pressed_key is 'B':
                    self.create_template()

        self.path['x'] = []
        self.path['y'] = []
        self.pressed_key = None

    '''
    Combine separate x and y point arrays to one nested array
    '''

    def combineXYPoints(self):
        points = []
        for i in range(0, len(self.path['x'])):
            points.append([self.path['x'][i], self.path['y'][i]])
        return points

    '''
    A text message is passed to a ui label widget
    '''

    def display_message(self, msg):
        self.label.setText(msg)

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()

    def setRange(self, plot, static):
        if static is False:
            plot.enableAutoRange(enable=False)
            plot.enableAutoRange(enable=True)
        else:
            plot.setXRange(300, 750)
            plot.setYRange(300, 750)
class Demo(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Wiimote Activity")
        self.showFullScreen()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.fc = Flowchart(terminals={"dataIn": {"io": "in"}, "dataOut": {"io": "out"}})

        self.layout.addWidget(self.fc.widget(), 0, 0, 4, 1)

        self.createNodes()
        # self.getWiimote()

    # connect to wiimote with an address given as argument
    def getWiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print ("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    def update(self):
        outputValues = self.activityNode.outputValues()
        if outputValues["activity"] is not None:
            self.label.setText(outputValues["activity"])
        pg.QtGui.QApplication.processEvents()

    # create and config the nodes needed to recognize activities
    def createNodes(self):
        pwX = pg.PlotWidget()
        pwY = pg.PlotWidget()
        pwZ = pg.PlotWidget()
        pwX.getPlotItem().hideAxis("bottom")
        pwX.setYRange(300, 700)
        pwY.getPlotItem().hideAxis("bottom")
        pwY.setYRange(300, 700)
        pwZ.getPlotItem().hideAxis("bottom")
        pwZ.setYRange(300, 700)

        self.label = QtGui.QLabel()
        self.label.setText("No activity yet...")
        font = QtGui.QFont("Arial")
        font.setPointSize(32)
        self.label.setFont(font)

        self.layout.addWidget(pwX, 0, 1)
        self.layout.addWidget(pwY, 1, 1)
        self.layout.addWidget(pwZ, 2, 1)
        self.layout.addWidget(self.label, 3, 1)

        pwXNode = self.fc.createNode("PlotWidget", pos=(-150, -150))
        pwXNode.setPlot(pwX)

        pwYNode = self.fc.createNode("PlotWidget", pos=(0, -150))
        pwYNode.setPlot(pwY)

        pwZNode = self.fc.createNode("PlotWidget", pos=(150, -150))
        pwZNode.setPlot(pwZ)

        self.activityNode = self.fc.createNode("ClassifierNode", pos=(0, 150))

        """
        self.wiimoteNode = self.fc.createNode('Wiimote', pos=(-300, 0))
        self.bufferXNode = self.fc.createNode('Buffer', pos=(-150, -300))
        self.bufferYNode = self.fc.createNode('Buffer', pos=(0, -300))
        self.bufferZNode = self.fc.createNode('Buffer', pos=(150, -300))

        self.fc.connectTerminals(
            self.wiimoteNode['accelX'], self.bufferXNode['dataIn'])
        self.fc.connectTerminals(
            self.wiimoteNode['accelY'], self.bufferYNode['dataIn'])
        self.fc.connectTerminals(
            self.wiimoteNode['accelZ'], self.bufferZNode['dataIn'])
        self.fc.connectTerminals(self.bufferXNode['dataOut'], pwXNode['In'])
        self.fc.connectTerminals(self.bufferYNode['dataOut'], pwYNode['In'])
        self.fc.connectTerminals(self.bufferZNode['dataOut'], pwZNode['In'])
        self.fc.connectTerminals(
            self.bufferXNode['dataOut'], self.activityNode['accelX'])
        self.fc.connectTerminals(
            self.bufferYNode['dataOut'], self.activityNode['accelY'])
        self.fc.connectTerminals(
            self.bufferZNode['dataOut'], self.activityNode['accelZ'])
        """

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()
class Demo(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Plotting the Wiimote")
        self.showFullScreen()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.flowchart = Flowchart(terminals={
            'xDataIn': {'io': 'in'},
            'yDataIn': {'io': 'in'},
            'zDataIn': {'io': 'in'},
            'xDataOut': {'io': 'out'},
            'yDataOut': {'io': 'out'},
            'zDataOut': {'io': 'out'}
        })

        self.layout.addWidget(self.flowchart.widget(), 0, 0, 3, 1)

        fclib.registerNodeType(WiimoteNode, [('Display',)])
        self.wii_node = self.flowchart.createNode('Wiimote', pos=(0, 0))

        self.axes = ['x', 'y', 'z']

        # positions for all nodes; order:
        # raw_node xpos, raw_node ypos, filtered_node xpos, filtered_node ypos,
        # filter_node xpos, filter_node ypos
        self.positions = {
            'x': [-450, -350, -300, -350, -375, -150],
            'y': [-150, -350, 0, -350, -75, -150],
            'z': [150, -350, 300, -350, 225, -150],
        }

        # create, style, config and connect the elements for every axis
        for axis in self.axes:
            index = self.axes.index(axis)

            plot_raw = pyqtgraph.PlotWidget()
            plot_filtered = pyqtgraph.PlotWidget()

            # add widget for this axis in next row
            self.layout.addWidget(plot_filtered, index, 2, 1, 2)

            self.configPlotItems(axis, plot_raw, plot_filtered)

            self.createNodes(axis, plot_raw, plot_filtered)

            self.connectNodes(axis)

        pyqtgraph.setConfigOptions(antialias=True)

        self.flowchart.setInput(xDataIn=0)
        self.flowchart.setInput(yDataIn=0)
        self.flowchart.setInput(zDataIn=0)

    # create raw, filter and filtered node
    def createNodes(self, axis, plot_raw, plot_filtered):

        # create filtered node
        self.plot_filtered_node = self.flowchart.createNode(
            'PlotWidget', pos=(
                self.positions[axis][2],
                self.positions[axis][3]))
        self.plot_filtered_node.setPlot(plot_filtered)

        # create gaussian filter
        self.filter_node = self.flowchart.createNode(
            'GaussianFilter', pos=(
                self.positions[axis][4],
                self.positions[axis][5]))
        self.filter_node.ctrls['sigma'].setValue(5)

    # connect nodes: flowchart -> wiinode -> plot_raw +  filter_node
    # -> filtered_node
    def connectNodes(self, axis):
        self.flowchart.connectTerminals(
            self.flowchart[axis + 'DataIn'], self.wii_node[axis + 'DataIn'])

        self.flowchart.connectTerminals(
            self.wii_node[axis + 'DataOut'], self.filter_node['In'])

        self.flowchart.connectTerminals(
            self.filter_node['Out'], self.plot_filtered_node['In'])

        #self.flowchart.connectTerminals(
        #    self.filter_node['Out'], self.flowchart[axis + 'DataOut'])

    # config plot items
    def configPlotItems(self, axis, plot_raw, plot_filtered):
        plot_raw.getPlotItem().setTitle("The " + axis + " Accelerometer")
        plot_raw.getPlotItem().setMenuEnabled(False)
        plot_raw.getPlotItem().setClipToView(False)
        plot_raw.getPlotItem().hideAxis('bottom')
        plot_raw.getPlotItem().showGrid(x=True, y=True, alpha=0.5)

        plot_filtered.getPlotItem().setTitle(
            "The " + axis + " Accelerometer - Filtered")
        plot_filtered.getPlotItem().setMenuEnabled(False)
        plot_filtered.getPlotItem().setClipToView(False)
        plot_filtered.getPlotItem().hideAxis('bottom')
        plot_filtered.getPlotItem().showGrid(x=True, y=True, alpha=0.5)

    def updateValues(self, x, y, z):
        self.flowchart.setInput(xDataIn=x)
        self.flowchart.setInput(yDataIn=y)
        self.flowchart.setInput(zDataIn=z)
        pyqtgraph.QtGui.QApplication.processEvents()

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()
Example #15
0
class ModelWindow(QtWidgets.QMainWindow, Ui_ModelWindow):  #模型界面对应的类
    def __init__(self):
        super(ModelWindow, self).__init__()
        self.setupUi(self)
        self.global_id = 0  #每个层对应的唯一ID,用于基于DAG图的校验和代码生成
        self.nodes = dict()  #所有层的信息
        self.id_name = dict()  #ID-名字映射
        self.name_id = dict()  #名字-ID映射
        self.net = nx.DiGraph()  #图,节点为层的ID
        self.library = fclib.LIBRARY.copy()
        self.library.addNodeType(CovNode, [('CovNode', )])
        self.library.addNodeType(PoolNode, [('PoolNode', )])
        self.library.addNodeType(LinearNode, [('LinearNode', )])
        self.library.addNodeType(ConcatNode, [('ConcatNode', )])
        self.library.addNodeType(Concat1dNode, [('Concat1dNode', )])
        self.library.addNodeType(SoftmaxNode, [('SoftmaxNode', )])
        self.library.addNodeType(LogSoftmaxNode, [('LogSoftmaxNode', )])
        self.library.addNodeType(BachNorm1dNode, [('BachNorm1dNode', )])
        self.library.addNodeType(BachNorm2dNode, [('BachNorm2dNode', )])
        self.library.addNodeType(AddNode, [('ResAddNode', )])
        self.library.addNodeType(IdentityNode, [('IdentityNode', )])
        self.type_name = {
            2: 'Cov2d',
            3: 'Pool2d',
            4: 'Linear',
            5: 'Softmax',
            6: 'LogSoftmax',
            7: 'BachNorm1d',
            8: 'BachNorm2d',
            9: 'Res_Add',
            10: 'Concat2d',
            11: 'Concat1d',
            12: 'Identity'
        }
        self.fc = Flowchart()  #模型可视化的流程图,对应FlowChart按钮
        self.fc.setLibrary(self.library)  #引入FCNodes.py中定义的Node
        self.outputs = list()  #模型所有输出
        w = self.fc.widget()
        self.fc_inputs = dict()  #self.fc流程图的输入
        main_widget = QWidget()
        main_layout = QGridLayout()
        main_widget.setLayout(main_layout)
        self.detail = QTreeWidget()
        self.detail.setColumnCount(2)
        self.detail.setHeaderLabels(["属性", "值"])
        self.root = QTreeWidgetItem(self.detail)
        self.root.setText(0, "所有属性")
        main_layout.addWidget(self.fc.widget(), 0, 0, 1, 2)
        main_layout.addWidget(self.detail, 0, 2)
        self.setCentralWidget(main_widget)

    def add_layer(self):  #用于弹出“层-新建”动作对应的层操作界面
        self.addlayer_window = AddLayerWindow()
        self.addlayer_window.datasignal.connect(self.accept_layer)
        self.addlayer_window.show()

    def modifiey_layer(self):  #用于弹出“层-更改”动作对应的层操作界面
        self.addlayer_window = AddLayerWindow()
        self.addlayer_window.datasignal.connect(self.accept_layer)
        self.addlayer_window.layertype.addItem("恒等层(Identity)")
        self.addlayer_window.show()

    def clear(self):  #对应“层-清除”,清除当前模型
        self.fc.clear()
        self.id_name = dict()
        self.name_id = dict()
        self.nodes = dict()
        self.net = nx.DiGraph()
        self.fc.clear()
        self.fc_inputs = dict()
        self.global_id = 0
        self.outputs = list()
        self.detail.clear()
        self.detail.setColumnCount(2)
        self.detail.setHeaderLabels(["属性", "值"])
        self.root = QTreeWidgetItem(self.detail)
        self.root.setText(0, "所有属性")

    def to_train(self):  #对应“功能-训练”动作,跳转到训练界面
        self.train_window = TrainWindow()
        self.train_window.show()

    def to_test(self):  #对应“功能-测试”动作,跳转到测试界面
        self.test_window = TestWindow()
        self.test_window.show()

    def accept_layer(self, data):  #接收层操作界面中信号的槽函数,接收层操作界面传来的数据并显示在该界面上
        reset_flag = False
        if not data['type'] in [1, 12]:  #对输入层和恒等层不检查输入
            inputs = data['input'].split(";")
            data['input'] = list()
            for i in range(len(inputs)):  #判断连接是否合法
                try:
                    name = inputs[i]
                    layer = self.name_id[name]
                    if data['type'] == 3 and (self.nodes[inputs[i]]['type']
                                              not in [2, 8, 9, 10]):
                        QMessageBox.warning(self, "错误",
                                            "输入:{}层类型不合法".format(inputs[i]))
                        return 0
                    elif (data['type'] in [
                            5, 6, 7, 11
                    ]) and (self.nodes[inputs[i]]['type'] not in [4, 7, 11]):
                        QMessageBox.warning(self, "错误",
                                            "输入:{}层类型不合法".format(inputs[i]))
                        return 0
                    elif (data['type']
                          in [2, 8, 10]) and (self.nodes[inputs[i]]['type']
                                              not in [1, 2, 3, 8, 9, 10]):
                        QMessageBox.warning(self, "错误",
                                            "输入:{}层类型不合法".format(inputs[i]))
                        return 0
                    data['input'].append(layer)  #将input中的层名替换为对应的ID
                except:
                    QMessageBox.warning(self, "错误",
                                        "输入来自未生成的层:{}".format(inputs[i]))
                    return 0
        else:
            data['input'] = list()
        if data['type'] == 9:  #残差连接层判断两个输入size是否相同
            layer_id = data['input'][0]
            cur_size = self.nodes[self.id_name[layer_id]]['para']['out_size']
            for layer_id in data['input']:
                layer = self.nodes[self.id_name[layer_id]]
                if layer['para']['out_size'] != cur_size:
                    QMessageBox.warning(self, "错误", "输入尺寸不匹配")
                    return 0
        if data['name'] in self.name_id.keys():  #替换同名层的情形
            id = self.name_id[data['name']]
            for input_id in data['input']:
                if input_id >= id:
                    QMessageBox.warning(self, "错误", "输入来自后继层")
                    return 0
            if data['type'] == 12:
                data['para']['former_type'] = self.nodes[data['name']]['type']
                if len(data['input']) == 0:
                    data['input'].append(self.nodes[data['name']]['input'][0])
            self.net.remove_node(id)
            self.net.add_node(id)
            for i in data['input']:
                self.net.add_edge(i, id)
            self.fc.removeNode(self.fc.nodes()[data['name']])
            data['ID'] = id
            reset_flag = True
        else:  #新建层
            data['ID'] = self.global_id
            self.name_id[data['name']] = self.global_id
            self.id_name[self.global_id] = data['name']
            self.net.add_node(self.global_id)
            for i in data['input']:
                self.net.add_edge(i, self.global_id)
            self.global_id += 1
        self.nodes[data['name']] = data
        if data['type'] == 1:  #输入层对应的流程图操作
            self.fc.addInput(data['name'])
            self.fc_inputs[data['name']] = data['para']['out_size']
            self.fc.setInput(**self.fc_inputs)
        elif data['type'] in [9, 10, 11]:  #concat2D、concat1D和残差连接层的流程图操作
            node = self.fc.createNode(
                self.type_name[data['type']],
                name=data['name'],
                pos=(data['input'][0] * 120,
                     (data['ID'] - data['input'][0]) * 150 - 500))
            node.setPara(data['para'])
            node.setView(self.root)
            for i in data['input']:
                in_name = self.id_name[i]
                in_size = self.nodes[in_name]['para']['out_size']
                node.addInput(in_name)
                if self.nodes[in_name]['type'] == 1:
                    self.fc.connectTerminals(self.fc[in_name], node[in_name])
                else:
                    self.fc.connectTerminals(
                        self.fc.nodes()[in_name]['dataOut'], node[in_name])
            if data['isoutput']:
                self.fc.addOutput(data['name'])
                self.fc.connectTerminals(node['dataOut'],
                                         self.fc[data['name']])
        else:  #其他层的流程图操作
            node = self.fc.createNode(
                self.type_name[data['type']],
                name=data['name'],
                pos=(data['input'][0] * 120,
                     (data['ID'] - data['input'][0]) * 150 - 500))
            node.setPara(data['para'])
            node.setView(self.root)
            if self.nodes[self.id_name[data['input'][0]]]['type'] == 1:
                self.fc.connectTerminals(
                    self.fc[self.id_name[data['input'][0]]], node['dataIn'])
            else:
                self.fc.connectTerminals(
                    self.fc.nodes()[self.id_name[data['input'][0]]]['dataOut'],
                    node['dataIn'])
            if data['isoutput']:
                self.fc.addOutput(data['name'])
                self.fc.connectTerminals(node['dataOut'],
                                         self.fc[data['name']])
        if data['isoutput']:  #添加流程图输出
            self.outputs.append(data['ID'])
        if reset_flag:  #对替换的层恢复后向的连接
            for everynode in self.nodes.values():
                if data['ID'] in everynode['input']:
                    out_terminal = node.outputs()['dataOut']
                    if everynode['type'] in [9, 10, 11]:
                        in_terminal = self.fc.nodes()[
                            everynode['name']].inputs()[data['name']]
                    else:
                        in_terminal = self.fc.nodes()[
                            everynode['name']].inputs()['dataIn']
                    self.fc.connectTerminals(in_terminal, out_terminal)
                    self.net.add_edge(data['ID'], everynode['ID'])

    def export_file(self):  #导出pytorch脚本
        filename, _ = QFileDialog.getSaveFileName(self, '导出模型', 'C:\\',
                                                  'Python Files (*.py)')
        if filename is None or filename == "":
            return 0
        filedir, filename_text = os.path.split(filename)
        filename_text = filename_text.split(".")[0]
        if self.check() == 0:
            QMessageBox.warning(self, "错误", "出现size<=0或模型没有输出")
            return 0
        sort = list(nx.topological_sort(self.net))
        content = list()
        for id in sort:
            content.append(self.nodes[self.id_name[id]])
        with open(filedir + '/' + filename_text + ".json", 'w') as f1:
            json.dump(content, f1)
        with open(filename, 'w') as f:
            space = "    "
            f.write(
                'import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n'
            )
            f.write("class Net(nn.Module):\n")
            f.write(space + "def __init__(self):\n")
            f.write(space * 2 +
                    "super(Net, self).__init__()\n")  #一下为__init__函数
            for id in sort:
                name = self.id_name[id]
                layer = self.nodes[name]
                if layer['type'] == 2:
                    f.write(space * 2 + "self." + layer['name'] +
                            " = nn.Conv2d(")
                    f.write(str(layer['para']['in_size'][0])+","+str(layer['para']['outchannels'])+","\
                            +str(layer['para']['kernel']))
                    for k, v in layer['para'].items():
                        if k in [
                                'stride', 'padding', 'dilation', 'bias',
                                'padding_mode'
                        ] and v is not None:
                            f.write("," + k + "=" + str(v))
                    f.write(")\n")
                elif layer['type'] == 12:
                    f.write(space * 2 +
                            "self.{} = nn.Identity()\n".format(name))
                elif layer['type'] == 3:
                    if layer['para']['type'] == "max":
                        f.write(space * 2 + "self." + layer['name'] +
                                " = nn.MaxPool2d(")
                        f.write(str(layer['para']['kernel']))
                        for k, v in layer['para'].items():
                            if k in ['stride', 'padding'] and v is not None:
                                f.write("," + k + "=" + str(v))
                    elif layer['para']['type'] == "average":
                        f.write(space * 2 + "self." + layer['name'] +
                                " = nn.AvgPool2d(")
                        f.write(str(layer['para']['kernel']))
                        for k, v in layer['para'].items():
                            if k in ['stride', 'padding'] and v is not None:
                                f.write("," + k + "=" + str(v))
                    else:
                        f.write(space * 2 + "self." + layer['name'] +
                                " = nn.LPPool2d(")
                        f.write(str(layer['para']['power']) + ",")
                        f.write(str(layer['para']['kernel']))
                        for k, v in layer['para'].items():
                            if k == 'stride' and v is not None:
                                f.write("," + k + "=" + str(v))
                    f.write(")\n")
                elif layer['type'] == 4:
                    f.write(space * 2 + "self." + layer['name'] +
                            " = nn.Linear(")
                    f.write(str(layer['para']['in_size']) + ",")
                    f.write(str(layer['para']['out_features']) + ",")
                    f.write("bias=" + str(layer['para']['bias']))
                    f.write(")\n")
                elif layer['type'] == 7:
                    f.write(space * 2 + "self." + layer['name'] +
                            " = nn.BatchNorm1d(")
                    f.write(str(layer['para']['in_size']) + ",")
                    f.write("eps=" + str(layer['para']['eps']) + ",")
                    f.write("momentum=" + str(layer['para']['momentum']) + ",")
                    f.write("affine=" + str(layer['para']['affine']) + ",")
                    f.write("track_running_stats=" +
                            str(layer['para']['track_running_stats']) + ")\n")
                elif layer['type'] == 8:
                    f.write(space * 2 + "self." + layer['name'] +
                            " = nn.BatchNorm2d(")
                    f.write(str(layer['para']['in_size'][0]) + ",")
                    f.write("eps=" + str(layer['para']['eps']) + ",")
                    f.write("momentum=" + str(layer['para']['momentum']) + ",")
                    f.write("affine=" + str(layer['para']['affine']) + ",")
                    f.write("track_running_stats=" +
                            str(layer['para']['track_running_stats']) + ")\n")
            #以下为forward函数
            f.write(space + "def forward(self")
            for input in self.fc_inputs.keys():
                f.write("," + input)
            f.write("):\n")
            return_layers = list()
            for layer_id in sort:
                layer = self.nodes[self.id_name[layer_id]]
                if layer['type'] == 2 or layer['type'] == 4:
                    f.write(space * 2 + layer['name'] + " = ")
                    if layer['type'] == 4:
                        input_name = self.id_name[layer['input'][0]]
                        inner_str = "self.{0}({1}.view({1}.size()[0], -1))".format(
                            layer['name'], input_name)
                    else:
                        inner_str = "self." + layer[
                            'name'] + "(" + self.id_name[layer['input']
                                                         [0]] + ")"
                    if layer['para']['activate'] != "None":
                        if layer['para']['activate'] in ['tanh', 'sigmoid']:
                            tmp = "torch." + layer['para'][
                                'activate'] + "({})".format(inner_str)
                        else:
                            tmp = "F." + layer['para'][
                                'activate'] + "({})".format(inner_str)
                        inner_str = tmp
                    if layer['para']['dropout']:
                        tmp = "F.dropout({}, p=".format(inner_str) + str(
                            layer['para']['dropout_radio']) + ")"
                        inner_str = tmp
                    f.write(inner_str)
                    f.write("\n")
                elif layer['type'] in [3, 7, 8]:
                    f.write(
                        space * 2 + layer['name'] + " = self.{}({})\n".format(
                            layer['name'], self.id_name[layer['input'][0]]))
                elif layer['type'] == 5:
                    f.write(space * 2 + layer['name'] +
                            " = F.softmax({}, dim=1)\n".format(self.id_name[
                                layer['input'][0]]))
                elif layer['type'] == 6:
                    f.write(space * 2 + layer['name'] +
                            " = F.log_softmax({}, dim=1)\n".format(
                                self.id_name[layer['input'][0]]))
                elif layer['type'] == 9:
                    f.write(space * 2 + layer['name'] + " = ")
                    for i in range(len(layer['input']) - 1):
                        f.write(self.id_name[layer['input'][i]] + "+")
                    f.write(self.id_name[layer['input'][len(layer['input']) -
                                                        1]] + "\n")
                elif layer['type'] == 10:
                    layers_to_cat = list()
                    for input_id in layer['input']:
                        input_name = self.id_name[input_id]
                        input_layer = self.nodes[input_name]
                        layers_to_cat.append(input_name)
                        pad_up, pad_down, pad_left, pad_right = 0, 0, 0, 0
                        if input_layer['para']['out_size'][1] != layer['para'][
                                'out_size'][1]:
                            rest = (layer['para']['out_size'][1] -
                                    input_layer['para']['out_size'][1]) / 2
                            if rest != int(rest):
                                pad_up, pad_down = int(rest), int(rest) + 1
                            else:
                                pad_up, pad_down = int(rest), int(rest)
                        if input_layer['para']['out_size'][2] != layer['para'][
                                'out_size'][2]:
                            rest = (layer['para']['out_size'][2] -
                                    input_layer['para']['out_size'][2]) / 2
                            if rest != int(rest):
                                pad_left, pad_right = int(rest), int(rest) + 1
                            else:
                                pad_left, pad_right = int(rest), int(rest)
                            pad = (pad_left, pad_right, pad_up, pad_down)
                        f.write(space*2+input_name+" = F.pad({}, ({}, {}, {}, {}))\n".format(input_name,\
                                                        pad_left, pad_right, pad_up, pad_down))
                    f.write(space * 2 + layer['name'] +
                            " = torch.cat([{}], 1)\n".format(",".join(
                                layers_to_cat)))
                elif layer['type'] == 11:
                    layers_to_cat = list()
                    for input_id in layer['input']:
                        input_name = self.id_name[input_id]
                        layers_to_cat.append(input_name)
                    f.write(space * 2 + layer['name'] +
                            " = torch.cat([{}], 1)\n".format(",".join(
                                layers_to_cat)))
                elif layer['type'] == 12:
                    f.write(
                        space * 2 + layer['name'] + " = self.{}({})\n".format(
                            layer['name'], self.id_name[layer['input'][0]]))
                if layer['isoutput']:
                    return_layers.append(layer['name'])
            if len(return_layers) > 1:
                f.write(space * 2 +
                        "return {}\n".format(",".join(return_layers)))
            else:
                f.write(space * 2 + "return {}".format(return_layers[0]))

    def check(self):  #基于DAG的校验
        if len(self.outputs) == 0:
            QMessageBox.warning(self, "错误", "模型没有输出")
            return 0
        for item in self.nodes.values():
            if type(item['para']['out_size']) is int:
                if item['para']['out_size'] <= 0:
                    QMessageBox.warning(self, "错误",
                                        "{}层输出尺寸为负数或0".format(item['name']))
                    return 0
            else:
                for size in item['para']['out_size']:
                    if size <= 0:
                        QMessageBox.warning(
                            self, "错误", "{}层输出尺寸为负数或0".format(item['name']))
                        return 0

    def import_file(self):  #导入json文件重建模型
        filename, _ = QFileDialog.getOpenFileName(self, '导入模型', 'C:\\',
                                                  'JSON Files (*.json)')
        if filename is None or filename == "":
            return 0
        d_json = json.load(open(filename, 'r'))
        self.id_name = dict()
        self.name_id = dict()
        self.nodes = dict()
        self.net = nx.DiGraph()
        self.fc.clear()
        self.fc_inputs = dict()
        self.global_id = 0
        self.outputs = list()
        self.detail.clear()
        self.detail.setColumnCount(2)
        self.detail.setHeaderLabels(["属性", "值"])
        self.root = QTreeWidgetItem(self.detail)
        self.root.setText(0, "所有属性")
        for data in d_json:
            self.id_name[data['ID']] = data['name']
            self.name_id[data['name']] = data['ID']
            self.nodes[data['name']] = data
            self.net.add_node(data['ID'])
            for i in data['input']:
                self.net.add_edge(i, data['ID'])
            if data['type'] == 1:
                if not data['name'] in self.fc.inputs().keys():
                    self.fc.addInput(data['name'])
                self.fc_inputs[data['name']] = data['para']['out_size']
                self.fc.setInput(**self.fc_inputs)
            elif data['type'] in [9, 10, 11]:
                node = self.fc.createNode(
                    self.type_name[data['type']],
                    name=data['name'],
                    pos=(data['input'][0] * 120,
                         (data['ID'] - data['input'][0]) * 150 - 500))
                node.setPara(data['para'])
                node.setView(self.root)
                for i in data['input']:
                    in_name = self.id_name[i]
                    in_size = self.nodes[in_name]['para']['out_size']
                    node.addInput(in_name)
                    if self.nodes[in_name]['type'] == 1:
                        self.fc.connectTerminals(self.fc[in_name],
                                                 node[in_name])
                    else:
                        self.fc.connectTerminals(
                            self.fc.nodes()[in_name]['dataOut'], node[in_name])
                if data['isoutput']:
                    if not data['name'] in self.fc.outputs().keys():
                        self.fc.addOutput(data['name'])
                    self.fc.connectTerminals(node['dataOut'],
                                             self.fc[data['name']])
            else:
                node = self.fc.createNode(
                    self.type_name[data['type']],
                    name=data['name'],
                    pos=(data['input'][0] * 120,
                         (data['ID'] - data['input'][0]) * 150 - 500))
                node.setPara(data['para'])
                node.setView(self.root)
                if self.nodes[self.id_name[data['input'][0]]]['type'] == 1:
                    self.fc.connectTerminals(
                        self.fc[self.id_name[data['input'][0]]],
                        node['dataIn'])
                else:
                    self.fc.connectTerminals(
                        self.fc.nodes()[self.id_name[data['input'][0]]]
                        ['dataOut'], node['dataIn'])
                if data['isoutput']:
                    if not data['name'] in self.fc.outputs().keys():
                        self.fc.addOutput(data['name'])
                    self.fc.connectTerminals(node['dataOut'],
                                             self.fc[data['name']])
            if data['isoutput']:
                self.outputs.append(data['ID'])
Example #16
0
def main():
    addr_hard = 'B8:AE:6E:1B:5B:03'
    name_hard = 'Nintendo RVL-CNT-01-TR'

    input("Press the 'sync' button on the back of your Wiimote Plus " +
          "or buttons (1) and (2) on your classic Wiimote.\n" +
          "Press <return> once the Wiimote's LEDs start blinking.")

    # use hardcoded addr if no parameters were given
    # for easier testing
    if len(sys.argv) == 1:
        addr = addr_hard
        name = name_hard

    elif len(sys.argv) == 2:
        addr = sys.argv[1]
        name = None

    print(("Connecting to %s (%s)" % (name, addr)))

    # Initializing UI
    app = QtGui.QApplication([])
    win = QtGui.QMainWindow()
    win.setWindowTitle('Analyze.py')
    cw = QtGui.QWidget()
    win.setCentralWidget(cw)
    layout = QtGui.QGridLayout()
    layout.setRowStretch(0, 2)
    cw.setLayout(layout)

    # Create an empty flowchart with a single input and output
    fc = Flowchart(terminals={
    })
    w = fc.widget()

    layout.addWidget(w, 0, 0, 2, 1)

    # Init WiimoteNode and connect Wiimote via bluetooth
    wiimoteNode = fc.createNode('Wiimote', pos=(-300, 0))
    wiimoteNode.text.setText(addr)

    wiimoteNode.connect_wiimote()

    # X-Axis Plot
    bufferNode1 = fc.createNode('Buffer', pos=(0, -200))

    pw1 = pg.PlotWidget()
    layout.addWidget(pw1, 0, 1)
    pw1.setYRange(0, 1024)

    pw1Node = fc.createNode('PlotWidget', pos=(150, -200))
    pw1Node.setPlot(pw1)

    fc.connectTerminals(wiimoteNode['accelX'], bufferNode1['dataIn'])
    fc.connectTerminals(bufferNode1['dataOut'], pw1Node['In'])

    # Y-Axis Plot
    bufferNode2 = fc.createNode('Buffer', pos=(0, -50))

    pw2 = pg.PlotWidget()
    layout.addWidget(pw2, 0, 2)
    pw2.setYRange(0, 1024)

    pw2Node = fc.createNode('PlotWidget', pos=(150, -50))
    pw2Node.setPlot(pw2)

    fc.connectTerminals(wiimoteNode['accelY'], bufferNode2['dataIn'])
    fc.connectTerminals(bufferNode2['dataOut'], pw2Node['In'])

    # Z-Axis Plot
    bufferNode3 = fc.createNode('Buffer', pos=(0, 100))

    pw3 = pg.PlotWidget()
    layout.addWidget(pw3, 0, 3)
    pw3.setYRange(0, 1024)

    pw3Node = fc.createNode('PlotWidget', pos=(150, 100))
    pw3Node.setPlot(pw3)

    fc.connectTerminals(wiimoteNode['accelZ'], bufferNode3['dataIn'])
    fc.connectTerminals(bufferNode3['dataOut'], pw3Node['In'])

    # Normalvector
    normalNode = fc.createNode('Normalvector', pos=(-150, 250))
    curveNode = fc.createNode('PlotCurve', pos=(0, 250))

    pw4 = pg.PlotWidget()
    pw4.setYRange(-2, 2)
    pw4.setXRange(-2, 2)
    layout.addWidget(pw4, 1, 1, 1, 3)
    pw4Node = fc.createNode('PlotWidget', pos=(150, 250))

    pw4Node.setPlot(pw4)

    fc.connectTerminals(wiimoteNode['accelX'], normalNode['accelX'])
    fc.connectTerminals(wiimoteNode['accelZ'], normalNode['accelZ'])
    fc.connectTerminals(normalNode['normalX'], curveNode['x'])
    fc.connectTerminals(normalNode['normalY'], curveNode['y'])
    fc.connectTerminals(curveNode['plot'], pw4Node['In'])

    # Lognode
    logNode = fc.createNode('Log', pos=(-150, -300))

    fc.connectTerminals(wiimoteNode['accelX'], logNode['accelX'])
    fc.connectTerminals(wiimoteNode['accelY'], logNode['accelY'])
    fc.connectTerminals(wiimoteNode['accelZ'], logNode['accelZ'])

    win.show()
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
Example #17
0
class Pointer(QtGui.QWidget):
    '''
    This class reads WiiMote IR data and provides
    them on output.
    '''
    def __init__(self, useWiiMote, parent=None):
        super(Pointer, self).__init__()

        self.useWiiMote = useWiiMote

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.buffer_amount = 20

        self.fc = Flowchart(terminals={
            'dataIn': {
                'io': 'in'
            },
            'dataOut': {
                'io': 'out'
            }
        })
        self.layout.addWidget(self.fc.widget(), 0, 0, 2, 1)

        self.configNodes()

        if self.useWiiMote:
            self.getWiimote()

        self.outputCounter = 0

    # connect to wiimoet
    def getWiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    # create and connect nodes
    def configNodes(self):
        self.pointVisNode = self.fc.createNode('Vis3D', pos=(-150, 150))
        self.wiimoteNode = self.fc.createNode(
            'Wiimote',
            pos=(0, 0),
        )
        self.bufferNode = self.fc.createNode('Buffer', pos=(0, -150))

        self.buffer_amount = self.bufferNode.getBufferSize()

        self.fc.connectTerminals(self.wiimoteNode['irVals'],
                                 self.bufferNode['dataIn'])
        self.fc.connectTerminals(self.bufferNode['dataOut'],
                                 self.pointVisNode['irVals'])

    # create and config scatter plot item
    def configScatterPlot(self):
        gview = pg.GraphicsLayoutWidget()
        self.layout.addWidget(gview, 0, 1, 2, 1)

        plot = gview.addPlot()
        self.scatter = pg.ScatterPlotItem(size=10,
                                          pen=pg.mkPen(None),
                                          brush=pg.mkBrush(255, 255, 255, 120))
        plot.addItem(self.scatter)
        plot.setXRange(-1000, 200)
        plot.setYRange(-1000, 200)

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()

    # do actions in loop
    def update(self):
        self.outputValues = self.pointVisNode.outputValues()

        if self.useWiiMote is False:
            # use simulated data if WiiMote shall not
            # be used
            self.outputValues = {
                'irX0': 30,
                'irY0': 120,
                'irX1': 40,
                'irY1': 130,
                'irX2': 400,
                'irY2': 400,
                'irX3': 410,
                'irY3': 410
            }

            self.outputCounter = self.outputCounter + 2

            for key in self.outputValues:
                if 'X' in key:
                    self.outputValues[key] = self.outputValues[key] + \
                        self.outputCounter
                else:
                    self.outputValues[key] = self.outputValues[key] + \
                        self.outputCounter

        # raise or lower buffer amount with +/- keys
        if self.wiimoteNode.wiimote is not None:
            if self.wiimoteNode.wiimote.buttons['Plus']:
                self.buffer_amount += 1
                self.bufferNode.setBufferSize(self.buffer_amount)
            elif self.wiimoteNode.wiimote.buttons['Minus']:
                if self.buffer_amount > 1:
                    self.buffer_amount -= 1
                    self.bufferNode.setBufferSize(self.buffer_amount)

        pyqtgraph.QtGui.QApplication.processEvents()
class Pointer(QtGui.QWidget):
    '''
    This class reads WiiMote IR data and provides
    them on output.
    '''
    def __init__(self, useWiiMote, parent=None):
        super(Pointer, self).__init__()

        self.useWiiMote = useWiiMote

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.buffer_amount = 20

        self.fc = Flowchart(terminals={
            'dataIn': {'io': 'in'},
            'dataOut': {'io': 'out'}
        })
        self.layout.addWidget(self.fc.widget(), 0, 0, 2, 1)

        self.configNodes()

        if self.useWiiMote:
            self.getWiimote()

        self.outputCounter = 0

    # connect to wiimoet
    def getWiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    # create and connect nodes
    def configNodes(self):
        self.pointVisNode = self.fc.createNode('Vis3D', pos=(-150, 150))
        self.wiimoteNode = self.fc.createNode('Wiimote', pos=(0, 0), )
        self.bufferNode = self.fc.createNode('Buffer', pos=(0, -150))

        self.buffer_amount = self.bufferNode.getBufferSize()

        self.fc.connectTerminals(
            self.wiimoteNode['irVals'],
            self.bufferNode['dataIn'])
        self.fc.connectTerminals(
            self.bufferNode['dataOut'],
            self.pointVisNode['irVals'])

    # create and config scatter plot item
    def configScatterPlot(self):
        gview = pg.GraphicsLayoutWidget()
        self.layout.addWidget(gview, 0, 1, 2, 1)

        plot = gview.addPlot()
        self.scatter = pg.ScatterPlotItem(
            size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 120))
        plot.addItem(self.scatter)
        plot.setXRange(-1000, 200)
        plot.setYRange(-1000, 200)

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()

    # do actions in loop
    def update(self):
        self.outputValues = self.pointVisNode.outputValues()

        if self.useWiiMote is False:
            # use simulated data if WiiMote shall not
            # be used
            self.outputValues = {
                'irX0': 30, 'irY0': 120,
                'irX1': 40, 'irY1': 130,
                'irX2': 400, 'irY2': 400,
                'irX3': 410, 'irY3': 410
                }

            self.outputCounter = self.outputCounter + 2

            for key in self.outputValues:
                if 'X' in key:
                    self.outputValues[key] = self.outputValues[key] + \
                        self.outputCounter
                else:
                    self.outputValues[key] = self.outputValues[key] + \
                        self.outputCounter

        # raise or lower buffer amount with +/- keys
        if self.wiimoteNode.wiimote is not None:
            if self.wiimoteNode.wiimote.buttons['Plus']:
                self.buffer_amount += 1
                self.bufferNode.setBufferSize(self.buffer_amount)
            elif self.wiimoteNode.wiimote.buttons['Minus']:
                if self.buffer_amount > 1:
                    self.buffer_amount -= 1
                    self.bufferNode.setBufferSize(self.buffer_amount)

        pyqtgraph.QtGui.QApplication.processEvents()
Example #19
0
class MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """
        self.fc = Flowchart()
        QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.fcctrl = self.fc.widget()
        self.fcwidget = self.fcctrl.chartWidget.view
        self.tab1wid.addWidget(self.fcwidget, 0, 0, 2, 1)
        self.tab2wid.addWidget(self.fcctrl, 0, 0, 2, 1)

    @pyqtSignature("")
    def on_actionNew_triggered(self):
        """
        Slot documentation goes here.
        """
        self.fc.clear()

    @pyqtSignature("")
    def on_actionOpen_triggered(self):
        """
        Slot documentation goes here.
        """
        self.fc.loadFile()

    @pyqtSignature("")
    def on_actionSave_triggered(self):
        """
        Slot documentation goes here.
        """
        self.fc.saveFile()

    @pyqtSignature("")
    def on_actionClose_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError

    @pyqtSignature("")
    def on_actionCut_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError

    @pyqtSignature("")
    def on_actionCopy_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError

    @pyqtSignature("")
    def on_actionProcess_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError

    @pyqtSignature("")
    def on_actionSankey_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError

    @pyqtSignature("")
    def on_actionSaveas_triggered(self):
        """
        Slot documentation goes here.
        """
        self.fc.saveFile(fileName=None)

    @pyqtSignature("")
    def on_actionExit_triggered(self):
        """
        Slot documentation goes here.
        """
        sys.exit()

    @pyqtSignature("")
    def on_actionPaste_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError

    @pyqtSignature("")
    def on_actionSensitivities_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError

    @pyqtSignature("")
    def on_actionAbout_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
class Demo(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Pointing Device")
        self.show()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.buffer_amount = 20

        self.fc = Flowchart(terminals={
            'dataIn': {
                'io': 'in'
            },
            'dataOut': {
                'io': 'out'
            }
        })
        self.layout.addWidget(self.fc.widget(), 0, 0, 2, 1)

        self.configNodes()
        self.configScatterPlot()

        self.getWiimote()

    def getWiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    # create and connect nodes
    def configNodes(self):
        self.pointVisNode = self.fc.createNode('Vis3D', pos=(-150, 150))
        self.wiimoteNode = self.fc.createNode(
            'Wiimote',
            pos=(0, 0),
        )
        self.bufferNode = self.fc.createNode('Buffer', pos=(0, -150))

        self.buffer_amount = self.bufferNode.getBufferSize()

        self.fc.connectTerminals(self.wiimoteNode['irVals'],
                                 self.bufferNode['dataIn'])
        self.fc.connectTerminals(self.bufferNode['dataOut'],
                                 self.pointVisNode['irVals'])

    # create and config scatter plot item
    def configScatterPlot(self):
        gview = pg.GraphicsLayoutWidget()
        self.layout.addWidget(gview, 0, 1, 2, 1)

        plot = gview.addPlot()
        self.scatter = pg.ScatterPlotItem(size=10,
                                          pen=pg.mkPen(None),
                                          brush=pg.mkBrush(255, 255, 255, 120))
        plot.addItem(self.scatter)
        plot.setXRange(-1000, 200)
        plot.setYRange(-1000, 200)

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()

    # do actions in loop
    def update(self):
        outputValues = self.pointVisNode.outputValues()

        isX1Valid = outputValues['irX1'] is not None
        isY1Valid = outputValues['irY1'] is not None
        isX2Valid = outputValues['irX2'] is not None
        isY2Valid = outputValues['irY2'] is not None

        if isX1Valid and isX2Valid and isY1Valid and isY2Valid:
            distance = self.calcDistance(outputValues)
            if distance > 0:
                size = 3000 * (1 / distance * 2)

                self.scatter.setData(
                    pos=[[-outputValues['irX1'], -outputValues['irY1']],
                         [-outputValues['irX2'], -outputValues['irY2']]],
                    size=size,
                    pxMode=True)

        # raise or lower buffer amount with +/- keys
        if self.wiimoteNode.wiimote is not None:
            if self.wiimoteNode.wiimote.buttons['Plus']:
                self.buffer_amount += 1
                self.bufferNode.setBufferSize(self.buffer_amount)
            elif self.wiimoteNode.wiimote.buttons['Minus']:
                if self.buffer_amount > 1:
                    self.buffer_amount -= 1
                    self.bufferNode.setBufferSize(self.buffer_amount)

        pyqtgraph.QtGui.QApplication.processEvents()

    # calc distance from wiimote to the two lights
    # reference: http://wiiphysics.site88.net/physics.html
    def calcDistance(self, outputValues):
        x1 = outputValues['irX1']
        y1 = outputValues['irY1']
        x2 = outputValues['irX2']
        y2 = outputValues['irY2']

        # init wiimote's camera angles
        hfov = 41
        vfov = 31

        # set constant distance between the two lights
        lightDistance = 30

        fov = ((hfov / 1024.0) + (vfov / 768.0)) / 2.0

        r = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))

        alpha = (fov * r) / 4.0

        tan = math.tan(math.radians(alpha))

        try:
            camDistance = lightDistance / (2 * tan)
        except:
            camDistance = 0
        return camDistance
Example #21
0
class Demo(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Plotting the Wiimote")
        self.showFullScreen()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.flowchart = Flowchart(
            terminals={
                'xDataIn': {
                    'io': 'in'
                },
                'yDataIn': {
                    'io': 'in'
                },
                'zDataIn': {
                    'io': 'in'
                },
                'xDataOut': {
                    'io': 'out'
                },
                'yDataOut': {
                    'io': 'out'
                },
                'zDataOut': {
                    'io': 'out'
                }
            })

        self.layout.addWidget(self.flowchart.widget(), 0, 0, 3, 1)

        fclib.registerNodeType(WiimoteNode, [('Display', )])
        self.wii_node = self.flowchart.createNode('Wiimote', pos=(0, 0))

        self.axes = ['x', 'y', 'z']

        # positions for all nodes; order:
        # raw_node xpos, raw_node ypos, filtered_node xpos, filtered_node ypos,
        # filter_node xpos, filter_node ypos
        self.positions = {
            'x': [-450, -350, -300, -350, -375, -150],
            'y': [-150, -350, 0, -350, -75, -150],
            'z': [150, -350, 300, -350, 225, -150],
        }

        # create, style, config and connect the elements for every axis
        for axis in self.axes:
            index = self.axes.index(axis)

            plot_raw = pyqtgraph.PlotWidget()
            plot_filtered = pyqtgraph.PlotWidget()

            # add widget for this axis in next row
            self.layout.addWidget(plot_filtered, index, 2, 1, 2)

            self.configPlotItems(axis, plot_raw, plot_filtered)

            self.createNodes(axis, plot_raw, plot_filtered)

            self.connectNodes(axis)

        pyqtgraph.setConfigOptions(antialias=True)

        self.flowchart.setInput(xDataIn=0)
        self.flowchart.setInput(yDataIn=0)
        self.flowchart.setInput(zDataIn=0)

    # create raw, filter and filtered node
    def createNodes(self, axis, plot_raw, plot_filtered):

        # create filtered node
        self.plot_filtered_node = self.flowchart.createNode(
            'PlotWidget',
            pos=(self.positions[axis][2], self.positions[axis][3]))
        self.plot_filtered_node.setPlot(plot_filtered)

        # create gaussian filter
        self.filter_node = self.flowchart.createNode(
            'GaussianFilter',
            pos=(self.positions[axis][4], self.positions[axis][5]))
        self.filter_node.ctrls['sigma'].setValue(5)

    # connect nodes: flowchart -> wiinode -> plot_raw +  filter_node
    # -> filtered_node
    def connectNodes(self, axis):
        self.flowchart.connectTerminals(self.flowchart[axis + 'DataIn'],
                                        self.wii_node[axis + 'DataIn'])

        self.flowchart.connectTerminals(self.wii_node[axis + 'DataOut'],
                                        self.filter_node['In'])

        self.flowchart.connectTerminals(self.filter_node['Out'],
                                        self.plot_filtered_node['In'])

        #self.flowchart.connectTerminals(
        #    self.filter_node['Out'], self.flowchart[axis + 'DataOut'])

    # config plot items
    def configPlotItems(self, axis, plot_raw, plot_filtered):
        plot_raw.getPlotItem().setTitle("The " + axis + " Accelerometer")
        plot_raw.getPlotItem().setMenuEnabled(False)
        plot_raw.getPlotItem().setClipToView(False)
        plot_raw.getPlotItem().hideAxis('bottom')
        plot_raw.getPlotItem().showGrid(x=True, y=True, alpha=0.5)

        plot_filtered.getPlotItem().setTitle("The " + axis +
                                             " Accelerometer - Filtered")
        plot_filtered.getPlotItem().setMenuEnabled(False)
        plot_filtered.getPlotItem().setClipToView(False)
        plot_filtered.getPlotItem().hideAxis('bottom')
        plot_filtered.getPlotItem().showGrid(x=True, y=True, alpha=0.5)

    def updateValues(self, x, y, z):
        self.flowchart.setInput(xDataIn=x)
        self.flowchart.setInput(yDataIn=y)
        self.flowchart.setInput(zDataIn=z)
        pyqtgraph.QtGui.QApplication.processEvents()

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()
Example #22
0
#####################################

# Create flowchart, define input/output terminals
fc = Flowchart(
    terminals={
        #'sigOut': {'io': 'in'},
        #'sigOut2': {'io': 'in'}#,
        #'sigIn': {'io': 'out'}  #We don't currently need any outputs from FC
    },
    name='Connections')

# Remove the unnecessary input and output nodes
fc.removeNode(fc.inputNode)
fc.removeNode(fc.outputNode)

flowchart = fc.widget()
d3.addWidget(flowchart)
flowchart_dock.addWidget(fc.widget().chartWidget)

#Register own node types
fclib.registerNodeType(OscilloscopeNode, [('SciEdu', )])
fclib.registerNodeType(FilterNode, [('SciEdu', )])
fclib.registerNodeType(CharToBinaryNode, [('SciEdu', )])
# fclib.registerNodeType(BinaryToCharNode, [('SciEdu',)]) # TODO
fclib.registerNodeType(ParityNode, [('SciEdu', )])
fclib.registerNodeType(CheckParityNode, [('SciEdu', )])
fclib.registerNodeType(FFTNode, [('SciEdu', )])
fclib.registerNodeType(SigGenNode, [('SciEdu', )])
fclib.registerNodeType(AmplifierNode, [('SciEdu', )])
fclib.registerNodeType(LineEncoderNode, [('SciEdu', )])
fclib.registerNodeType(RectifierNode, [('SciEdu', )])
class Demo(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Pointing Device")
        self.show()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.fc = Flowchart(terminals={
            'dataIn': {'io': 'in'},
            'dataOut': {'io': 'out'}
        })
        self.layout.addWidget(self.fc.widget(), 0, 0, 2, 1)

        self.configNodes()
        self.configScatterPlot()

        self.getWiimote()

    # connect to wiimote and config wiimote node
    def getWiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    # create and connect nodes
    def configNodes(self):
        self.pointVisNode = self.fc.createNode('Vis2D', pos=(-150, 150))
        self.wiimoteNode = self.fc.createNode('Wiimote', pos=(0, 0), )
        self.bufferNode = self.fc.createNode('Buffer', pos=(0, -150))

        self.buffer_amount = self.bufferNode.getBufferSize()

        self.fc.connectTerminals(
            self.wiimoteNode['irVals'],
            self.bufferNode['dataIn'])
        self.fc.connectTerminals(
            self.bufferNode['dataOut'],
            self.pointVisNode['irVals'])

    # create and config scatter plot item
    def configScatterPlot(self):
        gview = pg.GraphicsLayoutWidget()
        self.layout.addWidget(gview, 0, 1, 2, 1)
        plot = gview.addPlot()
        self.scatter = pg.ScatterPlotItem(
            size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 120))
        plot.addItem(self.scatter)
        plot.setXRange(-1000, 200)
        plot.setYRange(-1000, 200)

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()

    # do actions in loop
    def update(self):
        outputValues = self.pointVisNode.outputValues()

        if outputValues['irX'] is not None and outputValues['irY'] is not None:
            self.scatter.setData(pos=[
                [-outputValues['irX'], -outputValues['irY']]])

        # raise or lower buffer amount with +/- keys
        if self.wiimoteNode.wiimote is not None:
            if self.wiimoteNode.wiimote.buttons['Plus']:
                self.buffer_amount += 1
                self.bufferNode.setBufferSize(self.buffer_amount)
            elif self.wiimoteNode.wiimote.buttons['Minus']:
                if self.buffer_amount > 1:
                    self.buffer_amount -= 1
                    self.bufferNode.setBufferSize(self.buffer_amount)

        pyqtgraph.QtGui.QApplication.processEvents()
Example #24
0

from pyqtgraph.flowchart import Flowchart
from pyqtgraph.Qt import QtGui

#import pyqtgraph.flowchart as f

app = QtGui.QApplication([])

#TETRACYCLINE = True

fc = Flowchart(terminals={
    'dataIn': {'io': 'in'},
    'dataOut': {'io': 'out'}    
})
w = fc.widget()
w.resize(400,200)
w.show()

n1 = fc.createNode('Add')
n2 = fc.createNode('Subtract')
n3 = fc.createNode('Abs')
n4 = fc.createNode('Add')

fc.connectTerminals(fc.dataIn, n1.A)
fc.connectTerminals(fc.dataIn, n1.B)
fc.connectTerminals(fc.dataIn, n2.A)
fc.connectTerminals(n1.Out, n4.A)
fc.connectTerminals(n1.Out, n2.B)
fc.connectTerminals(n2.Out, n3.In)
fc.connectTerminals(n3.Out, n4.B)
Example #25
0
from PyQt5.QtWidgets import QApplication
from pyqtgraph.flowchart import Flowchart, sys

if __name__ == "__main__":
    app = QApplication(sys.argv)
    fc = Flowchart()
    w = fc.widget()
    w1 = fc.nodes()

    w.show()

    sys.exit(app.exec_())
Example #26
0
#####################################
# Create Flow Chart and components
#####################################

# Create flowchart, define input/output terminals
fc = Flowchart(terminals={
    #'sigOut': {'io': 'in'},
    #'sigOut2': {'io': 'in'}#,
    #'sigIn': {'io': 'out'}  #We don't currently need any outputs from FC
}, name='Connections')

# Remove the unnecessary input and output nodes
fc.removeNode(fc.inputNode)
fc.removeNode(fc.outputNode)

flowchart = fc.widget()
d3.addWidget(flowchart)
flowchart_dock.addWidget(fc.widget().chartWidget)

#Register own node types
fclib.registerNodeType(OscilloscopeNode, [('SciEdu',)])
fclib.registerNodeType(FilterNode, [('SciEdu',)])
fclib.registerNodeType(CharToBinaryNode, [('SciEdu',)])
# fclib.registerNodeType(BinaryToCharNode, [('SciEdu',)]) # TODO
fclib.registerNodeType(ParityNode, [('SciEdu',)])
fclib.registerNodeType(CheckParityNode, [('SciEdu',)])
fclib.registerNodeType(FFTNode, [('SciEdu',)])
fclib.registerNodeType(SigGenNode, [('SciEdu',)])
fclib.registerNodeType(AmplifierNode, [('SciEdu',)])
fclib.registerNodeType(LineEncoderNode, [('SciEdu',)])
fclib.registerNodeType(RectifierNode, [('SciEdu',)])
class Demo(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Gesture Recognizer")
        self.showFullScreen()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.fc = Flowchart(terminals={
            'dataIn': {'io': 'in'},
            'dataOut': {'io': 'out'}
        })
        self.layout.addWidget(self.fc.widget(), 0, 0, 2, 1)

        self.path = {'x': [], 'y': []}
        self.threshold = 50
        self.sample_size = 64
        self.default_msg = 'No template matched...'
        self.error_ir_msg = 'No ir-values received'
        self.error_wiimote_msg = 'No wiimote connected'
        self.error_template_msg = 'No template could be created'

        self.pressed_key = None

        self.dollar = Recognizer()

        self.config_nodes()
        self.config_layout()
        self.setup_templates()

        self.get_wiimote()

    '''
    The command-line argument is parsed and used to establish
    a connection to the wiimote
    '''
    def get_wiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    '''
    A wiimote node and a buffer node are created as well as a
    custom node which returns the position of the most intense
    light source detected by the wiimote
    '''
    def config_nodes(self):
        self.wiimoteNode = self.fc.createNode('Wiimote', pos=(0, 0), )
        self.bufferNode = self.fc.createNode('Buffer', pos=(0, -150))
        self.pointVisNode = self.fc.createNode('Vis2D', pos=(-150, 150))

        self.bufferNode.setBufferSize(4)

        self.fc.connectTerminals(
            self.wiimoteNode['irVals'],
            self.bufferNode['dataIn'])
        self.fc.connectTerminals(
            self.bufferNode['dataOut'],
            self.pointVisNode['irVals'])

    '''
    A scatterplot is used to display the infrafred data and a text label
    should indicate if the user input matches a predefined template
    '''
    def config_layout(self):
        gview = pg.GraphicsLayoutWidget()
        self.layout.addWidget(gview, 0, 1, 2, 1)
        self.templatePlot = gview.addPlot()
        self.templateScatter = pg.ScatterPlotItem(
            size=10, pen=pg.mkPen(None), brush=pg.mkBrush(0, 255, 0, 120))
        self.templatePlot.addItem(self.templateScatter)
        self.templatePlot.setTitle("Template")
        self.setRange(self.templatePlot, False)

        # self.layout.addWidget(gview, 0, 1, 2, 1)
        self.pathPlot = gview.addPlot()
        self.pathScatter = pg.ScatterPlotItem(
            size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 120))
        self.pathPlot.addItem(self.pathScatter)
        self.pathPlot.setTitle("Path")
        self.setRange(self.pathPlot, False)

        self.label = QtGui.QLabel()
        self.label.setText(self.default_msg)
        font = QtGui.QFont("Arial")
        font.setPointSize(32)
        self.label.setFont(font)
        self.layout.addWidget(self.label, 2, 1, 1, 1)

    '''
    Three default templates are added to the recognizer
    '''
    def setup_templates(self):
        circlePoints = [(269, 84), (263, 86), (257, 92), (253, 98),
                        (249, 104), (245, 114), (243, 122), (239, 132),
                        (237, 142), (235, 152), (235, 162), (235, 172),
                        (235, 180), (239, 190), (245, 198), (251, 206),
                        (259, 212), (267, 216), (275, 218), (281, 222),
                        (287, 224), (295, 224), (301, 226), (311, 226),
                        (319, 226), (329, 226), (339, 226), (349, 226),
                        (352, 226), (360, 226), (362, 225), (366, 219),
                        (367, 217), (367, 209), (367, 206), (367, 198),
                        (367, 190), (367, 182), (367, 174), (365, 166),
                        (363, 158), (359, 152), (355, 146), (353, 138),
                        (349, 134), (345, 130), (341, 124), (340, 122),
                        (338, 121), (337, 119), (336, 117), (334, 116),
                        (332, 115), (331, 114), (327, 110), (325, 109),
                        (323, 109), (321, 108), (320, 108), (318, 107),
                        (316, 107), (315, 107), (314, 107), (313, 107),
                        (312, 107), (311, 107), (310, 107), (309, 106),
                        (308, 106), (307, 105), (306, 105), (305, 105),
                        (304, 105), (303, 104), (302, 104), (301, 104),
                        (300, 104), (299, 103), (298, 103), (296, 102),
                        (295, 101), (293, 101), (292, 100), (291, 100),
                        (290, 100), (289, 100), (288, 100), (288, 99),
                        (287, 99), (287, 99)]
        squarePoints = [(193, 123), (193, 131), (193, 139), (195, 151),
                        (197, 161), (199, 175), (201, 187), (205, 201),
                        (207, 213), (209, 225), (213, 235), (213, 243),
                        (215, 251), (215, 254), (217, 262), (217, 264),
                        (217, 266), (217, 267), (218, 267), (219, 267),
                        (221, 267), (224, 267), (227, 267), (237, 267),
                        (247, 265), (259, 263), (273, 261), (287, 261),
                        (303, 259), (317, 257), (331, 255), (347, 255),
                        (361, 253), (375, 253), (385, 253), (395, 251),
                        (403, 249), (406, 249), (408, 249), (408, 248),
                        (409, 248), (409, 246), (409, 245), (409, 242),
                        (409, 234), (409, 226), (409, 216), (407, 204),
                        (407, 194), (405, 182), (403, 172), (403, 160),
                        (401, 150), (399, 140), (399, 130), (397, 122),
                        (397, 119), (397, 116), (396, 114), (396, 112),
                        (396, 111), (396, 110), (396, 109), (396, 108),
                        (396, 107), (396, 106), (396, 105), (394, 105),
                        (392, 105), (384, 105), (376, 105), (364, 105),
                        (350, 107), (334, 109), (318, 111), (306, 113),
                        (294, 115), (286, 117), (278, 117), (272, 119),
                        (269, 119), (263, 121), (260, 121), (254, 123),
                        (251, 123), (245, 125), (243, 125), (242, 125),
                        (241, 126), (240, 126), (238, 127), (236, 127),
                        (232, 128), (231, 128), (231, 129), (230, 129),
                        (228, 129), (227, 129), (226, 129), (225, 129),
                        (224, 129), (223, 129), (222, 129), (221, 130),
                        (221, 130)]
        trianglePoints = \
            [(282, 83), (281, 85), (277, 91), (273, 97),
             (267, 105), (261, 113), (253, 123), (243, 133),
             (235, 141), (229, 149), (221, 153), (217, 159),
             (216, 160), (215, 161), (214, 162), (216, 162),
             (218, 162), (221, 162), (227, 164), (233, 166),
             (241, 166), (249, 166), (259, 166), (271, 166),
             (283, 166), (297, 166), (309, 164), (323, 164),
             (335, 162), (345, 162), (353, 162), (361, 160),
             (363, 159), (365, 159), (366, 158), (367, 158),
             (368, 157), (369, 157), (370, 156), (371, 156),
             (371, 155), (372, 155), (372, 153), (372, 152),
             (372, 151), (372, 149), (372, 147), (371, 145),
             (367, 141), (363, 137), (359, 133), (353, 129),
             (349, 125), (343, 121), (337, 119), (333, 115),
             (327, 111), (325, 110), (324, 109), (320, 105),
             (318, 104), (314, 100), (312, 99), (310, 98),
             (306, 94), (305, 93), (303, 92), (301, 91),
             (300, 90), (298, 89), (297, 88), (296, 88),
             (295, 87), (294, 87), (293, 87), (293, 87)]

        self.dollar.addTemplate('circle', circlePoints)
        self.dollar.addTemplate('square', squarePoints)
        self.dollar.addTemplate('triangle', trianglePoints)

    def update(self):
        # get biggest light's x/y values
        outputValues = self.pointVisNode.outputValues()
        if outputValues['irX'] is not None and outputValues['irY'] is not None:
            if self.wiimoteNode.wiimote is not None:
                if self.wiimoteNode.wiimote.buttons['A']:
                    # collect values and set state
                    self.construct_path(outputValues)
                    self.pressed_key = 'A'
                elif self.wiimoteNode.wiimote.buttons['B']:
                    # collect values and set state
                    self.construct_path(outputValues)
                    self.pressed_key = 'B'
                elif self.path['x'] is not None and len(self.path['x']) > 0:
                    # draw path when A or B is released after collecting path
                    self.draw_path()
            else:
                self.templateScatter.clear()
                self.pathScatter.clear()
                self.display_message(self.error_wiimote_msg)
        else:
            self.templateScatter.clear()
            self.pathScatter.clear()
            self.display_message(self.error_ir_msg)

        # update range to remove old graphics
        self.setRange(self.templatePlot, False)
        self.setRange(self.pathPlot, False)

        pyqtgraph.QtGui.QApplication.processEvents()

    '''
    The user input is added as a new template
    '''
    def create_template(self):
        points = []
        # combine x/y path arrays to one point array
        for i in range(0, len(self.path['x'])):
            points.append([self.path['x'][i], self.path['y'][i]])

        # avoid devision by zero
        if len(points) > 3:
            # name and add template
            name = 'tpl_' + str((len(self.dollar.templates) + 1))
            self.label.setText("Created template " + name)
            self.dollar.addTemplate(name, points)
        else:
            self.display_message(self.error_template_msg)

    '''
    The user input is compared to all available templates and depending
    on the accordance a text message is displayed
    '''
    def compare_template(self):
        points = self.combineXYPoints()

        # try recognizing points. get name of template that matches most
        # and its amount of matching
        if len(points) < 3:
            self.display_message(self.default_msg)
            self.templateScatter.clear()
            return

        name, score = self.dollar.recognize(points)

        score = score * 100
        if score > self.threshold:
            # template matches good enough
            self.display_message(name)

            # get template by name
            template = [t for t in self.dollar.templates if t.name == name][0]

            tpl_points = []

            if template.points is None:
                # template doesn't match good enough
                self.display_message(self.default_msg)
                self.templateScatter.clear()
            else:
                # collect and display template points
                for i in range(0, len(template.points)):
                    tpl_points.append(
                        [template.points[i].x, template.points[i].y])
                # display points
                self.templateScatter.addPoints(
                    pos=np.array(tpl_points), brush=pg.mkBrush(0, 255, 0, 120))
        else:
            # template doesn't match good enough
            self.display_message(self.default_msg)
            self.templateScatter.clear()

    '''
    The infrafred values are stored in a dictionary
    '''
    def construct_path(self, irValues):
        self.templateScatter.clear()
        self.pathScatter.clear()
        self.path['x'].append(irValues['irX'])
        self.path['y'].append(irValues['irY'])

    '''
    The stored infrafred values are passed to a scatterplot
    '''
    def draw_path(self):
        path = self.combineXYPoints()
        points = []
        for i in range(0, len(path)):
            points.append(Point(path[i][0], path[i][1]))

        # display points
        if len(points) >= 3:
            points = resample(points, self.sample_size)
            if points is not None:
                path = []
                for i in range(0, len(points)):
                    path.append([points[i].x, points[i].y])

                self.pathScatter.addPoints(
                    pos=np.array(path), brush=pg.mkBrush(255, 255, 255, 120))

                # handle pressed keys
                if self.pressed_key is 'A':
                    self.compare_template()
                elif self.pressed_key is 'B':
                    self.create_template()

        self.path['x'] = []
        self.path['y'] = []
        self.pressed_key = None

    '''
    Combine separate x and y point arrays to one nested array
    '''
    def combineXYPoints(self):
        points = []
        for i in range(0, len(self.path['x'])):
            points.append([self.path['x'][i], self.path['y'][i]])
        return points

    '''
    A text message is passed to a ui label widget
    '''
    def display_message(self, msg):
        self.label.setText(msg)

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()

    def setRange(self, plot, static):
        if static is False:
            plot.enableAutoRange(enable=False)
            plot.enableAutoRange(enable=True)
        else:
            plot.setXRange(300, 750)
            plot.setYRange(300, 750)
class Demo(QtGui.QWidget):
    '''
    The main class which controls initialization and
    processing.
    '''
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Wiimote Activity")
        self.showFullScreen()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.fc = Flowchart(terminals={
            'dataIn': {'io': 'in'},
            'dataOut': {'io': 'out'}
        })

        self.layout.addWidget(self.fc.widget(), 0, 0, 4, 1)

        self.createNodes()

        self.getWiimote()

    # connect to wiimote with an address given as argument
    def getWiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    def update(self):
        # let the app process events
        pg.QtGui.QApplication.processEvents()

    # create and config the nodes needed to recognize activities
    def createNodes(self):
        pwX = pg.PlotWidget()
        pwY = pg.PlotWidget()
        pwZ = pg.PlotWidget()
        pwX.getPlotItem().hideAxis('bottom')
        pwX.setYRange(300, 700)
        pwY.getPlotItem().hideAxis('bottom')
        pwY.setYRange(300, 700)
        pwZ.getPlotItem().hideAxis('bottom')
        pwZ.setYRange(300, 700)

        self.layout.addWidget(pwX, 0, 1)
        self.layout.addWidget(pwY, 1, 1)
        self.layout.addWidget(pwZ, 2, 1)

        # create nodes
        pwXNode = self.fc.createNode('PlotWidget', pos=(-150, -150))
        pwXNode.setPlot(pwX)

        pwYNode = self.fc.createNode('PlotWidget', pos=(0, -150))
        pwYNode.setPlot(pwY)

        pwZNode = self.fc.createNode('PlotWidget', pos=(150, -150))
        pwZNode.setPlot(pwZ)

        self.fileReaderNode = self.fc.createNode(
            'FileReaderNode', pos=(0, 150))
        self.fftNode = self.fc.createNode(
            'LiveFFTNode', pos=(0, 300))
        self.classifierNode = self.fc.createNode(
            'SvmClassifierNode', pos=(150, 150))
        self.visualizerNode = self.fc.createNode(
            'CategoryVisualizerNode', pos=(300, 150))

        self.wiimoteNode = self.fc.createNode('Wiimote', pos=(-300, 0))
        self.bufferXNode = self.fc.createNode('Buffer', pos=(-150, -300))
        self.bufferYNode = self.fc.createNode('Buffer', pos=(0, -300))
        self.bufferZNode = self.fc.createNode('Buffer', pos=(150, -300))

        self.fc.connectTerminals(
            self.wiimoteNode['accelX'], self.bufferXNode['dataIn'])
        self.fc.connectTerminals(
            self.wiimoteNode['accelY'], self.bufferYNode['dataIn'])
        self.fc.connectTerminals(
            self.wiimoteNode['accelZ'], self.bufferZNode['dataIn'])

        self.fc.connectTerminals(
            self.bufferXNode['dataOut'], pwXNode['In'])
        self.fc.connectTerminals(
            self.bufferYNode['dataOut'], pwYNode['In'])
        self.fc.connectTerminals(
            self.bufferZNode['dataOut'], pwZNode['In'])

        self.fc.connectTerminals(
            self.fileReaderNode['data'], self.fftNode['samples'])
        self.fc.connectTerminals(
            self.fileReaderNode['categories'],
            self.classifierNode['categories'])

        self.fc.connectTerminals(
            self.bufferXNode['dataOut'], self.fftNode['accelX'])
        self.fc.connectTerminals(
            self.bufferYNode['dataOut'], self.fftNode['accelY'])
        self.fc.connectTerminals(
            self.bufferZNode['dataOut'], self.fftNode['accelZ'])

        self.fc.connectTerminals(
            self.fftNode['samplesFrequencies'],
            self.classifierNode['trainingData'])
        self.fc.connectTerminals(
            self.fftNode['testFrequencies'],
            self.classifierNode['testData'])

        self.fc.connectTerminals(
            self.classifierNode['classification'],
            self.visualizerNode['classification'])

        self.fileReaderNode.update()

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()
class Demo(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Wiimote Activity")
        self.showFullScreen()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.fc = Flowchart(terminals={
            'dataIn': {
                'io': 'in'
            },
            'dataOut': {
                'io': 'out'
            }
        })

        self.layout.addWidget(self.fc.widget(), 0, 0, 4, 1)

        self.createNodes()
        #self.getWiimote()

    # connect to wiimote with an address given as argument
    def getWiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    def update(self):
        outputValues = self.activityNode.outputValues()
        if outputValues['activity'] is not None:
            self.label.setText(outputValues['activity'])
        pg.QtGui.QApplication.processEvents()

    # create and config the nodes needed to recognize activities
    def createNodes(self):
        pwX = pg.PlotWidget()
        pwY = pg.PlotWidget()
        pwZ = pg.PlotWidget()
        pwX.getPlotItem().hideAxis('bottom')
        pwX.setYRange(300, 700)
        pwY.getPlotItem().hideAxis('bottom')
        pwY.setYRange(300, 700)
        pwZ.getPlotItem().hideAxis('bottom')
        pwZ.setYRange(300, 700)

        self.label = QtGui.QLabel()
        self.label.setText("No activity yet...")
        font = QtGui.QFont("Arial")
        font.setPointSize(32)
        self.label.setFont(font)

        self.layout.addWidget(pwX, 0, 1)
        self.layout.addWidget(pwY, 1, 1)
        self.layout.addWidget(pwZ, 2, 1)
        self.layout.addWidget(self.label, 3, 1)

        pwXNode = self.fc.createNode('PlotWidget', pos=(-150, -150))
        pwXNode.setPlot(pwX)

        pwYNode = self.fc.createNode('PlotWidget', pos=(0, -150))
        pwYNode.setPlot(pwY)

        pwZNode = self.fc.createNode('PlotWidget', pos=(150, -150))
        pwZNode.setPlot(pwZ)

        self.activityNode = self.fc.createNode('ClassifierNode', pos=(0, 150))
        """
        self.wiimoteNode = self.fc.createNode('Wiimote', pos=(-300, 0))
        self.bufferXNode = self.fc.createNode('Buffer', pos=(-150, -300))
        self.bufferYNode = self.fc.createNode('Buffer', pos=(0, -300))
        self.bufferZNode = self.fc.createNode('Buffer', pos=(150, -300))

        self.fc.connectTerminals(
            self.wiimoteNode['accelX'], self.bufferXNode['dataIn'])
        self.fc.connectTerminals(
            self.wiimoteNode['accelY'], self.bufferYNode['dataIn'])
        self.fc.connectTerminals(
            self.wiimoteNode['accelZ'], self.bufferZNode['dataIn'])
        self.fc.connectTerminals(self.bufferXNode['dataOut'], pwXNode['In'])
        self.fc.connectTerminals(self.bufferYNode['dataOut'], pwYNode['In'])
        self.fc.connectTerminals(self.bufferZNode['dataOut'], pwZNode['In'])
        self.fc.connectTerminals(
            self.bufferXNode['dataOut'], self.activityNode['accelX'])
        self.fc.connectTerminals(
            self.bufferYNode['dataOut'], self.activityNode['accelY'])
        self.fc.connectTerminals(
            self.bufferZNode['dataOut'], self.activityNode['accelZ'])
        """

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()
Example #30
0
    def __init__(self, data_In=None, dataB_In=None, *args, **kwargs):
        super().__init__()

        # data_In will be Adata
        if data_In == None:
            print("Please load data")
            # For testing, create noise data
            data_In = []
            for i in range(50):
                dat = np.random.normal(size=1024)
                dat[200:300] += 1
                dat += np.sin(np.linspace(0, 100, 1024))
                data_In.append(dat)
        data_In = np.array(data_In)

        self.ui = Ui_BackgroundSubtraction()
        self.ui.setupUi(self)

        # Change plot labels, because I was too lazy to create a new widget
        pw1 = self.ui.View_Orig
        pw1.plt.setLabel('bottom', 'Magnetic Field', units='T')  # X-Axis
        pw1.plt.setLabel('left', "Amplitude (Arb. Units)", units='')  # Y-Axis

        pw2 = self.ui.View_Mod
        pw2.plt.setLabel('bottom', 'Magnetic Field', units='T')  # X-Axis
        pw2.plt.setLabel('left', "Amplitude (Arb. Units)", units='')  # Y-Axis

        pw3 = self.ui.View_Colour

        # Create Flowchart with two IO Nodes
        fc = Flowchart(terminals={
            'dataIn': {
                'io': 'in'
            },
            'dataOut': {
                'io': 'out'
            }
        })

        w = fc.widget()
        self.ui.gridLayout.addWidget(w)

        # Create metaarray using data_In and some information
        #data = metaarray.MetaArray(data_In, info=[{'name': 'Amplitude data'}, {}])

        fc.setInput(dataIn=data_In)  #Set data to Input Node

        ## If we want to make our custom node available only to this flowchart,
        ## then instead of registering the node type globally, we can create a new
        ## NodeLibrary:
        library = fclib.LIBRARY.copy()  # start with the default node set
        # Add the node to two locations in the menu to demonstrate
        # that we can create arbitrary menu structures
        library.addNodeType(SavGol_Smooth, [('FMR', 'Filter')])
        library.addNodeType(SavGol_Smooth_2D, [('FMR', 'Filter')])
        library.addNodeType(FMR_Subtract_Average, [('FMR', 'Filter')])
        library.addNodeType(FMR_Subtract_Average_Colour, [('FMR', 'Filter')])
        library.addNodeType(Measurement_Select, [('FMR', 'Data')])
        library.addNodeType(Average_Ang_Dep, [('FMR', 'Data')])
        library.addNodeType(ImageViewNode, [('Display', )])
        fc.setLibrary(library)

        plotList = {'Top Plot': pw1.plt, 'Bottom Plot': pw2.plt}

        pw1Node = fc.createNode('PlotWidget', pos=(0, -150))
        pw1Node.setPlotList(plotList)
        pw1Node.setPlot(pw1.plt)

        pw2Node = fc.createNode('PlotWidget', pos=(150, -150))
        pw2Node.setPlot(pw2.plt)
        pw2Node.setPlotList(plotList)

        pw3Node = fc.createNode('ImageView', pos=(300, -150))
        pw3Node.setView(pw3.img)

        fNode = fc.createNode('Spectrum select', pos=(0, 0))
        fc.connectTerminals(
            fc['dataIn'], fNode['dataIn']
        )  # Use this Slice node to select the measurement that you want to smooth aka axis
        fc.connectTerminals(fNode['dataOut'], pw1Node['In'])
        fc.connectTerminals(fNode['dataOut'], pw2Node['In'])
        fc.connectTerminals(fNode['dataOut'], fc['dataOut'])
Example #31
0
class AppWindow(QtGui.QMainWindow, hackYourOwn.Ui_MainWindow, utilitiesClass):
    def __init__(self, parent=None, **kwargs):
        super(AppWindow, self).__init__(parent)
        self.setupUi(self)
        print(self.utils)
        self.I = kwargs.get('I', None)
        self.I.set_sine1(5000)
        self.I.configure_trigger(0, 'CH1', 0)
        self.setWindowTitle('pyqtgraph example: FlowchartCustomNode')
        ## Create an empty flowchart with a single input and output
        self.fc = Flowchart(terminals={
            'In': {
                'io': 'in'
            },
            'dataOut': {
                'io': 'out'
            },
        })
        self.w = self.fc.widget()

        self.ExperimentLayout.addWidget(self.w.chartWidget.view)
        #self.WidgetLayout.addWidget(self.w.chartWidget.selInfo)

        ###############MODIFY INPUT NODE#############################
        self.inp = addWidget(
            self.fc.inputNode.graphicsItem(),
            'input',
            func=self.fc.setInput,
            nameFunc=self.fc.inputNode.graphicsItem().nameItem.setPlainText)

        ############### CREATE USER LIBRARY #############################
        self.library = fclib.LIBRARY.copy()  # start with the default node set
        #add our custom nodes to the library
        self.library.addNodeType(self.PlotViewNode, [('Display', )])

        for a in [
                self.CaptureNode1, self.CaptureNode2, self.DACNode,
                self.VoltNode, self.GainNode
        ]:
            a.I = self.I

        self.library.addNodeType(self.ArrayNode, [('Data', )])
        self.library.addNodeType(self.ArrayNode2D, [('Data', )])

        self.library.addNodeType(self.CaptureNode1, [('Acquire', )])
        self.library.addNodeType(self.CaptureNode2, [('Acquire', )])
        self.library.addNodeType(self.VoltNode, [('Acquire', )])

        self.library.addNodeType(self.DACNode, [('Outputs', )])
        self.library.addNodeType(self.MyEvalNode, [('Outputs', )])

        self.library.addNodeType(self.GainNode, [('Configure', )])
        self.library.addNodeType(self.ConstantNode, [('Configure', )])

        self.fc.setLibrary(self.library)

        #############    LIBRARY HAS BEEN POPULATED. NOW BUILD THE MENU     ###############

        self.menu = self.buildMenu(self.w.chartWidget)
        self.menu.setMinimumHeight(150)
        self.WidgetLayout.addWidget(self.menu)

        self.WidgetLayout.addWidget(self.w)
        self.w.ui.showChartBtn.setParent(None)
        self.w.ui.reloadBtn.setParent(None)

        #############   NEXT UP : add ui elements    ###############

        self.plot = self.add2DPlot(self.ExperimentLayout)
        self.plot.addLegend()
        self.PlotViewNode.plot = self.plot

        ## Now we will programmatically add nodes to define the function of the flowchart.
        ## Normally, the user will do this manually or by loading a pre-generated
        ## flowchart file.

        self.cap = self.fc.createNode('Capture1', pos=(0, 0))

        self.v1Node = self.fc.createNode('2D Curve', pos=(200, -70))
        self.v2Node = self.fc.createNode('2D Curve', pos=(200, 70))

        self.fc.connectTerminals(self.fc['In'], self.cap['In'])
        self.fc.connectTerminals(self.cap['time'], self.v1Node['X'])
        self.fc.connectTerminals(self.cap['voltage'], self.v1Node['Y'])
        self.setStyleSheet("")

    def setInterconnects(self, val):
        if val: shape = 'cubic'
        else: shape = 'line'
        for a in self.fc.listConnections():
            for x in a[1]._graphicsItem.getViewBox().allChildren():
                if isinstance(x, pg.flowchart.TerminalGraphicsItem):
                    for y in x.term.connections().items():
                        y[1].setStyle(shape=shape)

    def runOnce(self):
        self.fc.setInput(In=True)

    def buildMenu(self, CW):
        def buildSubMenu(node, rootMenu, subMenus):
            for section, node in node.items():
                menu = QtGui.QMenu(section)
                rootMenu.addMenu(menu)
                if isinstance(node, OrderedDict):
                    buildSubMenu(node, menu, subMenus)
                    subMenus.append(menu)
                else:
                    act = rootMenu.addAction(section)
                    act.nodeType = section
                    act.pos = None

        class PermanentMenu(QtGui.QMenu):
            def hideEvent(self, event):
                self.show()

        menu = PermanentMenu()
        self.subMenus = []
        buildSubMenu(CW.chart.library.getNodeTree(), menu, self.subMenus)
        menu.triggered.connect(CW.nodeMenuTriggered)
        CW.menuPos = QtCore.QPoint(100, 150)
        return menu
        #self.v3Node = self.fc.createNode('PlotView', pos=(300, -150))
        #self.v3Node.setView(self.curve1)
        #self.fc.connectTerminals(self.cap['dataOut'], self.v1Node['data'])

    def __del__(self):
        #self.looptimer.stop()
        print('bye')

    def closeEvent(self, event):
        self.finished = True
        self.fc._widget.chartWidget.close()

    ################################################################################################
    #######################--------Display Function calls start here------------####################
    ################################################################################################

    class PlotViewNode(Node, utilitiesClass):
        """Node that displays plot data in an Plotwidget"""
        nodeName = '2D Curve'

        def __init__(self, name):
            self.view = None
            Node.__init__(self,
                          name,
                          terminals=OrderedDict([('X', dict(io='in')),
                                                 ('Y', dict(io='in')),
                                                 ('dY',
                                                  dict(io='in',
                                                       optional=True))]))
            self.txt = addWidget(self.graphicsItem(), 'plotText')
            self.curveName = self._name
            self.curve = self.addCurve(
                self.plot, self.curveName
            )  #self.plot is set by the parent prior to initialization
            self.txt.curve = self.curve
            self.sigRenamed.connect(self.renamed)

        def renamed(self, node, oldName):
            print('renamed from ', oldName, ' to ', self._name)
            self.renameLegendItem(self.plot.plotItem.legend, oldName,
                                  self._name)

        def process(self, X, Y, dY):
            if X is not None and Y is not None:
                if len(X) == len(Y):
                    self.txt.setText('length=%d\nx: %s\ny: [%s]...' %
                                     (len(X), str(X[:20]), " ".join(
                                         format(a, ".1f") for a in Y[:20])))
                    try:
                        if dY is not None and self.plot is not None:
                            self.plot.setYRange(dY[0], dY[1])
                    except Exception as e:
                        print(e)
                    self.curve.setData(X, Y)
                    return
            self.curve.setData([])

    ################################################################################################
    #######################--------Container Function calls start here------------##################
    ################################################################################################

    class ArrayNode(CtrlNode):
        nodeName = '1 Column Array'
        uiTemplate = []

        def __init__(self, name):
            self.A = []
            terminals = {'In': dict(io='in'), 'ArrayOut': dict(io='out')}
            CtrlNode.__init__(self, name, terminals=terminals)
            self.container = addWidget(self.graphicsItem(),
                                       'array',
                                       func=self.clear)

        def clear(self):
            self.A = []
            self.container.label.setText('Empty')

        def process(self, In, display=False):
            try:
                self.A.append(float(In))
                self.container.label.setText('size:%d' % len(self.A))
            except Exception as e:
                print(e)
            return {'ArrayOut': np.array(self.A)}

    class ArrayNode2D(CtrlNode):
        nodeName = '2 Column Array'
        uiTemplate = []

        def __init__(self, name):
            self.A = []
            self.B = []
            terminals = {
                'In1': dict(io='in'),
                'In2': dict(io='in'),
                'ArrayOut1': dict(io='out'),
                'ArrayOut2': dict(io='out')
            }
            CtrlNode.__init__(self, name, terminals=terminals)
            self.container = addWidget(self.graphicsItem(),
                                       'array',
                                       func=self.clear)

        def clear(self):
            self.A = []
            self.B = []
            self.container.label.setText('Empty')

        def process(self, In1, In2, display=False):
            try:
                self.A.append(float(In1))
                self.B.append(float(In2))
                self.container.label.setText('size:%d' % len(self.A))
            except Exception as e:
                print(e)
            return {
                'ArrayOut1': np.array(self.A),
                'ArrayOut2': np.array(self.B)
            }

    ################################################################################################
    #######################--------Input Function calls start here------------######################
    ################################################################################################

    class CaptureNode1(CtrlNode):
        nodeName = 'Capture1'
        uiTemplate = [
            ('samples', 'spin', {
                'value': 1000,
                'dec': False,
                'step': 10,
                'minStep': 1,
                'bounds': [0, 10000]
            }),
            ('timegap', 'spin', {
                'value': 1,
                'dec': False,
                'step': 10,
                'minStep': 1,
                'bounds': [0, 100]
            }),
        ]

        def __init__(self, name):
            terminals = OrderedDict([('In', dict(io='in')),
                                     ('time', dict(io='out')),
                                     ('voltage', dict(io='out')),
                                     ('dV', dict(io='out'))])
            CtrlNode.__init__(self, name, terminals=terminals)
            self.comboBox = addWidget(self.graphicsItem(),
                                      'combo',
                                      items=self.I.allAnalogChannels)

        def process(self, In, display=False):
            try:
                x, y = self.I.capture1(self.comboBox.currentText(),
                                       int(self.ctrls['samples'].value()),
                                       int(self.ctrls['timegap'].value()))
                return {
                    'time': x,
                    'voltage': y,
                    'dV': self.I.achans[0].get_Y_range()
                }
            except Exception as e:
                print(e)
            return {'time': None, 'voltage': None}

    class CaptureNode2(CtrlNode):
        nodeName = 'Capture2'
        uiTemplate = [
            ('samples', 'spin', {
                'value': 1000,
                'dec': False,
                'step': 10,
                'minStep': 1,
                'bounds': [0, 5000]
            }),
            ('timegap', 'spin', {
                'value': 1,
                'dec': False,
                'step': 10,
                'minStep': 1,
                'bounds': [0, 100]
            }),
        ]

        def __init__(self, name):
            terminals = OrderedDict([('In', dict(io='in')),
                                     ('time', dict(io='out')),
                                     ('V_CH1', dict(io='out')),
                                     ('V_CH2', dict(io='out'))])
            CtrlNode.__init__(self, name, terminals=terminals)
            self.comboBox = addWidget(self.graphicsItem(),
                                      'combo',
                                      items=self.I.allAnalogChannels)

        def process(self, In, display=False):
            try:
                x, y1, y2 = self.I.capture2(self.ctrls['samples'].value(),
                                            self.ctrls['timegap'].value(),
                                            self.comboBox.currentText())
                return {'time': x, 'V_CH1': y1, 'V_CH2': y2}
            except Exception as e:
                print(e)
            return {'time': None, 'V_CH1': None, 'V_CH2': None}

    class VoltNode(CtrlNode):
        nodeName = 'AnalogIn'
        uiTemplate = [
            ('channel', 'combo', {
                'values': ['CH1', 'CH2', 'CH3', 'AN8', 'SEN', 'CAP']
            }),
        ]

        def __init__(self, name):
            terminals = {'trig': dict(io='in'), 'V_out': dict(io='out')}
            CtrlNode.__init__(self, name, terminals=terminals)

        def process(self, trig, display=False):
            if trig != None:
                try:
                    val = self.I.get_voltage(
                        self.ctrls['channel'].currentText())
                    return {'V_out': val}
                except Exception as e:
                    print(e)
            return {'V_out': None}

    ################################################################################################
    #######################-----------Options and settings start here------------###################
    ################################################################################################

    class GainNode(CtrlNode, utilitiesClass):
        nodeName = 'AnalogGain'

        def __init__(self, name):
            terminals = {}
            CtrlNode.__init__(self, name, terminals=terminals)
            self.graphicsItem().nameItem.setPlainText('')
            self.wg = self.gainIcon(FUNC=self.I.set_gain)
            self.comboBox = addWidget(self.graphicsItem(), 'generic', self.wg)

        def process(self, display=False):
            pass  #return {'Y_CH1':self.I.achans['CH1'].get_Y_range(),'Y_CH2':self.I.achans['CH2'].get_Y_range()}

    class ConstantNode(CtrlNode):
        nodeName = 'Constant'

        def __init__(self, name):
            terminals = {'value': {'io': 'out', 'multiable': True}}
            CtrlNode.__init__(self, name, terminals=terminals)

        def process(self, display=False):
            return {'value': [-4, 4]}

    ################################################################################################
    #######################----------Output Function calls start here------------###################
    ################################################################################################

    class DACNode(CtrlNode):
        nodeName = 'PVx'
        uiTemplate = [
            ('channel', 'combo', {
                'values': ['PV1', 'PV2', 'PV3']
            }),
        ]

        def __init__(self, name):
            terminals = {'V_in': dict(io='in'), 'V_out': dict(io='out')}
            CtrlNode.__init__(self, name, terminals=terminals)
            self.label = addWidget(self.graphicsItem(), 'label', units='V')

        def process(self, V_in, display=False):
            if V_in:
                try:
                    val = self.I.DAC.setVoltage(
                        self.ctrls['channel'].currentText(), V_in)
                    self.label.setValue(val)
                    return {'V_out': val}
                except Exception as e:
                    print(e)
            return {'V_out': None}

    class MyEvalNode(Node):
        """Return the output of a string evaluated/executed by the python interpreter.
		The string may be either an expression or a python script, and inputs are accessed as the name of the terminal. 
		For expressions, a single value may be evaluated for a single output, or a dict for multiple outputs.
		For a script, the text will be executed as the body of a function."""
        nodeName = 'MyPythonEval'

        def __init__(self, name):
            Node.__init__(self,
                          name,
                          terminals={
                              'input': {
                                  'io': 'in',
                                  'renamable': True,
                                  'multiable': True
                              },
                              'output': {
                                  'io': 'out',
                                  'renamable': True,
                                  'multiable': True
                              },
                          },
                          allowAddInput=True,
                          allowAddOutput=True)

            self.ui = QtGui.QWidget()
            self.layout = QtGui.QGridLayout()
            self.text = QtGui.QTextEdit()
            self.text.setTabStopWidth(30)
            self.text.setPlainText(
                "# Access inputs as args['input_name']\nreturn {'output': None} ## one key per output terminal"
            )
            self.layout.addWidget(self.text, 1, 0, 1, 2)
            self.ui.setLayout(self.layout)

            #QtCore.QObject.connect(self.addInBtn, QtCore.SIGNAL('clicked()'), self.addInput)
            #self.addInBtn.clicked.connect(self.addInput)
            #QtCore.QObject.connect(self.addOutBtn, QtCore.SIGNAL('clicked()'), self.addOutput)
            #self.addOutBtn.clicked.connect(self.addOutput)
            self.text.focusOutEvent = self.focusOutEvent
            self.lastText = None

        def focusOutEvent(self, ev):
            text = str(self.text.toPlainText())
            if text != self.lastText:
                self.lastText = text
                self.update()
            return QtGui.QTextEdit.focusOutEvent(self.text, ev)

        def process(self, display=True, **args):
            l = locals()
            l.update(args)
            ## try eval first, then exec
            try:
                text = str(self.text.toPlainText()).replace('\n', ' ')
                output = eval(text, globals(), l)
            except SyntaxError:
                fn = "def fn(**args):\n"
                run = "\noutput=fn(**args)\n"
                text = fn + "\n".join([
                    "    " + l
                    for l in str(self.text.toPlainText()).split('\n')
                ]) + run
                exec(text)
            except:
                print("Error processing node: %s" % self.name())
                raise
            return output

        def saveState(self):
            state = Node.saveState(self)
            state['text'] = str(self.text.toPlainText())
            return state

        def restoreState(self, state):
            Node.restoreState(self, state)
            self.text.clear()
            self.text.insertPlainText(state['text'])
            self.restoreTerminals(state['terminals'])
            self.update()
Example #32
0
app = QtGui.QApplication([])

## Create main window with grid layout
win = QtGui.QMainWindow()
win.setWindowTitle('pyqtgraph example: Flowchart')
cw = QtGui.QWidget()
win.setCentralWidget(cw)
layout = QtGui.QGridLayout()
cw.setLayout(layout)

## Create flowchart, define input/output terminals
fc = Flowchart(terminals={
    'dataIn': {'io': 'in'},
    'dataOut': {'io': 'out'}
})
w = fc.widget()

## Add flowchart control panel to the main window
layout.addWidget(fc.widget(), 0, 0, 2, 1)

## Add two plot widgets
pw1 = pg.PlotWidget()
pw2 = pg.PlotWidget()
layout.addWidget(pw1, 0, 1)
layout.addWidget(pw2, 1, 1)

win.show()

## generate signal data to pass through the flowchart
data = np.random.normal(size=1000)
data[200:300] += 1
class Demo(QtGui.QWidget):
    """
    The main class which controls initialization and
    processing.
    """

    def __init__(self, parent=None):
        super(Demo, self).__init__()

        self.setWindowTitle("Wiimote Activity")
        self.showFullScreen()

        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

        self.fc = Flowchart(terminals={"dataIn": {"io": "in"}, "dataOut": {"io": "out"}})

        self.layout.addWidget(self.fc.widget(), 0, 0, 4, 1)

        self.createNodes()

        self.getWiimote()

    # connect to wiimote with an address given as argument
    def getWiimote(self):
        if len(sys.argv) == 1:
            addr, name = wiimote.find()[0]
        elif len(sys.argv) == 2:
            addr = sys.argv[1]
            name = None
        elif len(sys.argv) == 3:
            addr, name = sys.argv[1:3]
        print ("Connecting to %s (%s)" % (name, addr))

        self.wiimoteNode.text.setText(addr)
        self.wiimoteNode.connect_wiimote()

    def update(self):
        # let the app process events
        pg.QtGui.QApplication.processEvents()

    # create and config the nodes needed to recognize activities
    def createNodes(self):
        pwX = pg.PlotWidget()
        pwY = pg.PlotWidget()
        pwZ = pg.PlotWidget()
        pwX.getPlotItem().hideAxis("bottom")
        pwX.setYRange(300, 700)
        pwY.getPlotItem().hideAxis("bottom")
        pwY.setYRange(300, 700)
        pwZ.getPlotItem().hideAxis("bottom")
        pwZ.setYRange(300, 700)

        self.layout.addWidget(pwX, 0, 1)
        self.layout.addWidget(pwY, 1, 1)
        self.layout.addWidget(pwZ, 2, 1)

        # create nodes
        pwXNode = self.fc.createNode("PlotWidget", pos=(-150, -150))
        pwXNode.setPlot(pwX)

        pwYNode = self.fc.createNode("PlotWidget", pos=(0, -150))
        pwYNode.setPlot(pwY)

        pwZNode = self.fc.createNode("PlotWidget", pos=(150, -150))
        pwZNode.setPlot(pwZ)

        self.fileReaderNode = self.fc.createNode("FileReaderNode", pos=(0, 150))
        self.fftNode = self.fc.createNode("LiveFFTNode", pos=(0, 300))
        self.classifierNode = self.fc.createNode("SvmClassifierNode", pos=(150, 150))
        self.visualizerNode = self.fc.createNode("CategoryVisualizerNode", pos=(300, 150))

        self.wiimoteNode = self.fc.createNode("Wiimote", pos=(-300, 0))
        self.bufferXNode = self.fc.createNode("Buffer", pos=(-150, -300))
        self.bufferYNode = self.fc.createNode("Buffer", pos=(0, -300))
        self.bufferZNode = self.fc.createNode("Buffer", pos=(150, -300))

        self.fc.connectTerminals(self.wiimoteNode["accelX"], self.bufferXNode["dataIn"])
        self.fc.connectTerminals(self.wiimoteNode["accelY"], self.bufferYNode["dataIn"])
        self.fc.connectTerminals(self.wiimoteNode["accelZ"], self.bufferZNode["dataIn"])

        self.fc.connectTerminals(self.bufferXNode["dataOut"], pwXNode["In"])
        self.fc.connectTerminals(self.bufferYNode["dataOut"], pwYNode["In"])
        self.fc.connectTerminals(self.bufferZNode["dataOut"], pwZNode["In"])

        self.fc.connectTerminals(self.fileReaderNode["data"], self.fftNode["samples"])
        self.fc.connectTerminals(self.fileReaderNode["categories"], self.classifierNode["categories"])

        self.fc.connectTerminals(self.bufferXNode["dataOut"], self.fftNode["accelX"])
        self.fc.connectTerminals(self.bufferYNode["dataOut"], self.fftNode["accelY"])
        self.fc.connectTerminals(self.bufferZNode["dataOut"], self.fftNode["accelZ"])

        self.fc.connectTerminals(self.fftNode["samplesFrequencies"], self.classifierNode["trainingData"])
        self.fc.connectTerminals(self.fftNode["testFrequencies"], self.classifierNode["testData"])

        self.fc.connectTerminals(self.classifierNode["classification"], self.visualizerNode["classification"])

        self.fileReaderNode.update()

    def keyPressEvent(self, ev):
        if ev.key() == QtCore.Qt.Key_Escape:
            self.close()
if __name__ == '__main__':
    import sys
    app = QtGui.QApplication([])
    win = QtGui.QMainWindow()
    win.setWindowTitle('Activity tracker')
    cw = QtGui.QWidget()
    win.setCentralWidget(cw)
    layout = QtGui.QGridLayout()
    cw.setLayout(layout)

    # Create an empty flowchart with a single input and output
    fc = Flowchart(terminals={
        'dataIn': {'io': 'in'},
        'dataOut': {'io': 'out'}
    })
    w = fc.widget()

    layout.addWidget(fc.widget(), 0, 0, 2, 1)

    # wiimote node
    wiimoteNode = fc.createNode('Wiimote', pos=(0, -300), )

    # X
    # buffer for X
    xBufferNode = fc.createNode('CSV', pos=(150, -450))
    # fft for X
    xFftNode = fc.createNode('Fft', pos=(600, -450))
    # plotting fft data of X
    xFftPlotWidget = pg.PlotWidget()
    layout.addWidget(xFftPlotWidget, 0, 2)
    xFftPlotWidget.setYRange(0, 150)
Example #35
0
class FlowchartCalibrateWindow:
    def __init__(self):
        """
        Flowchart inside new window for system calibration
        """
        # Graphics window
        self.win = QtGui.QMainWindow()
        self.win.setWindowTitle('System Calibration Flowchart')
        # Dock Area
        dockArea = DockArea()
        # Central widget
        self.win.setCentralWidget(dockArea)

        # Window Docks
        fcWidgetDock = Dock('Flowchart Widget', size=(1, 1), hideTitle=True)
        displayDock = Dock('Measurement and Calibration', size=(1, 1))
        plotDocks = [Dock('Plot {}'.format(i), size=(1, 1)) for i in range(4)]
        dockArea.addDock(fcWidgetDock, 'left')
        dockArea.addDock(displayDock, 'right', fcWidgetDock)
        dockArea.addDock(plotDocks[0], 'top', displayDock)
        dockArea.addDock(plotDocks[1], 'right', plotDocks[0])
        dockArea.addDock(plotDocks[2], 'top', displayDock)
        dockArea.addDock(plotDocks[3], 'right', plotDocks[2])

        # Window size
        self.win.resize(800, 600)

        # Flowchart
        self.fc = Flowchart(terminals={
            'dipImgIn': {
                'io': 'in'
            },
            'CalibConstOut': {
                'io': 'out'
            },
        })
        # row, column, rowspan, colspan
        fcWidgetDock.addWidget(self.fc.widget())

        # Plot widgets
        self.plt_widg = [FlowchartPlotWidget() for _ in range(len(plotDocks))]
        [
            plotDocks[i].addWidget(self.plt_widg[i])
            for i in range(len(plotDocks))
        ]

        # Graphics layout for displays
        displayLayout = pg.GraphicsLayoutWidget(border='w')
        displayDock.addWidget(displayLayout)

        # Display widgets
        self.disp_widg = []
        self.disp_widg.append(
            displayLayout.addLabel('', colspan=2, justify='left'))
        displayLayout.nextRow()
        self.disp_widg.append(
            displayLayout.addLabel('', colspan=2, justify='left'))

        # Flowchart library copy - custom nodes available to user
        self.fc_library = fclib.LIBRARY.copy()
        [
            self.fc_library.addNodeType(nd, [('dipImage', 'Display')])
            for nd in (FlowchartPlotNode, MeasurementDisplayNode,
                       CalibDisplayNode, ORingMeasurementDisplayNode)
        ]
        # Filter nodes
        [
            self.fc_library.addNodeType(nd, [('dipImage', 'Filters')])
            for nd in (GaussianConvolutionNode, GradientNode,
                       GradientMagnitudeNode, GradientDirectionNode,
                       EdgeObjectsRemoveNode, KuwaharaNode,
                       BilateralFilterNode)
        ]
        # Binary Filter nodes
        [
            self.fc_library.addNodeType(nd, [('dipImage', 'Binary')])
            for nd in (BinaryClosingNode, BinaryOpeningNode, BinaryErosionNode,
                       BinaryDilationNode, BinaryAreaClosingNode,
                       BinaryAreaOpeningNode, BinaryPropagationNode,
                       FillHolesNode)
        ]
        # Segmentation nodes
        [
            self.fc_library.addNodeType(nd, [('dipImage', 'Segmentation')])
            for nd in (ThresholdNode, RangeThresholdNode, MinimaNode,
                       MaximaNode, WatershedNode, SeededWatershedNode,
                       CannyNode, SegmentORingNode)
        ]
        # Morphological nodes
        [
            self.fc_library.addNodeType(nd, [('dipImage', 'Morphological')])
            for nd in (DilationNode, ErosionNode, OpeningNode, ClosingNode)
        ]
        # Image nodes
        [
            self.fc_library.addNodeType(nd, [('dipImage', 'Image')])
            for nd in (ConvertNode, FillNode, LabelNode, SetPixelSizeNode)
        ]
        # Arithmetics nodes
        [
            self.fc_library.addNodeType(nd, [('dipImage', 'Arithmetics')])
            for nd in (InvertNode, ApplyMaskNode, CreateMaskNode,
                       OperatorPlusNode)
        ]
        # Measurement nodes
        [
            self.fc_library.addNodeType(nd, [('dipImage', 'Measurement')])
            for nd in (MeasureNode, WorkingDistanceCorrectionNode,
                       CombineMeasurementNode)
        ]
        self.fc.setLibrary(self.fc_library)

        # Plot nodes and Widget connection
        plt_nodes_x = (-20 + x * 120 for x in range(len(self.plt_widg)))
        plt_nodes = [
            self.fc.createNode('FlowchartPlot', pos=(x, -60))
            for x in plt_nodes_x
        ]
        [
            nd.set_fcPlotWidget(widg)
            for nd, widg in zip(plt_nodes, self.plt_widg)
        ]

        # Connecting plot and display widgets with nodes
        self.fc.sigFileLoaded.connect(self.setFlowchartPlotWidgets)
        self.fc.sigFileLoaded.connect(self.setDisplayWidgets)
        self.fc.sigChartChanged.connect(self.setFlowchartPlotWidgets)
        self.fc.sigChartChanged.connect(self.setDisplayWidgets)

    def setFlowchartPlotWidgets(self):
        """
        Connect Flowchart plot widgets with nodes after loading fc file
        """
        nd_list = []
        for name, node in self.fc.nodes().items():
            if isinstance(node, FlowchartPlotNode):
                nd_list.append(node)
        [nd.set_fcPlotWidget(widg) for nd, widg in zip(nd_list, self.plt_widg)]

    def setDisplayWidgets(self):
        """
        Connect Display widgets with nodes
        """
        for name, node in self.fc.nodes().items():
            if isinstance(node, MeasurementDisplayNode):
                node.setDisplayWidget(self.disp_widg[0])
            if isinstance(node, CalibDisplayNode):
                node.setDisplayWidget(self.disp_widg[1])

    def setInput(self, dip_img):
        """
        Set Flowchart input
        """
        self.fc.setInput(dipImgIn=dip_img)

    def fc_process(self, dip_img):
        """
        Process data with display=False (speed increase)
        """
        return self.fc.process(dipImgIn=dip_img)['CalibConstOut']

    def output(self):
        """
        Process data through flowchart with display=True and return output
        """
        return self.fc.output()['CalibConstOut']

    def show(self):
        self.win.show()

    def close(self):
        self.win.hide()