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 __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
def setup_nodes(self): # Create an empty flowchart with a single input and output self.fc = Flowchart(terminals={}) self.wiimote_node = self.fc.createNode('Wiimote') self.buffer_node_x = self.fc.createNode('Buffer') self.buffer_node_y = self.fc.createNode('Buffer') self.buffer_node_z = self.fc.createNode('Buffer') self.fft_node = self.fc.createNode('Fft') self.fc.connectTerminals(self.wiimote_node['accelX'], self.buffer_node_x['dataIn']) self.fc.connectTerminals(self.wiimote_node['accelY'], self.buffer_node_y['dataIn']) self.fc.connectTerminals(self.wiimote_node['accelZ'], self.buffer_node_z['dataIn']) self.fc.connectTerminals(self.buffer_node_x['dataOut'], self.fft_node['inX']) self.fc.connectTerminals(self.buffer_node_y['dataOut'], self.fft_node['inY']) self.fc.connectTerminals(self.buffer_node_z['dataOut'], self.fft_node['inZ']) spectrogram_node = self.fc.createNode('PlotWidget') spectrogram_node.setPlot(self.spectrogram_widget) self.fc.connectTerminals(self.fft_node['fft'], spectrogram_node['In']) self.svm_node = self.fc.createNode('Svm') self.fc.connectTerminals(self.fft_node['fft'], self.svm_node['fft'])
def setup_nodes(self): # Create an empty flowchart with a single input and output self.fc = Flowchart(terminals={}) self.wiimote_node = self.fc.createNode('Wiimote') self.fft_node = self.fc.createNode('Fft') self.svm_node = self.fc.createNode('Svm') self.fc.connectTerminals(self.wiimote_node['accelX'], self.svm_node['inX']) self.fc.connectTerminals(self.wiimote_node['accelY'], self.svm_node['inY']) self.fc.connectTerminals(self.wiimote_node['accelZ'], self.svm_node['inZ'])
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)
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 __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()
class DaskFlow(FlowchartCtrlWidget): def __init__(self): self.flowchart = Flowchart() super(DaskFlow, self).__init__(self.flowchart) def fromDask(self, workflow: Workflow): for process in workflow.processes: node = Node(process.name, terminals={ "inputTerminalName": { "io": "in" }, "outputTerminalName": { "io": "out" } }) self.flowchart.addNode(node, process.name)
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)
class DaskFlow(FlowchartCtrlWidget): def __init__(self): self.flowchart = Flowchart() super(DaskFlow, self).__init__(self.flowchart) def fromDask(self, workflow: Workflow): for process in workflow.processes: node = Node(process.name, terminals={ 'inputTerminalName': { 'io': 'in' }, 'outputTerminalName': { 'io': 'out' } }) self.flowchart.addNode(node, process.name)
def __init__(self, fc: Flowchart, parent: Union[QtGui.QWidget, None] = None, pathAndId: Union[Tuple[str, int], None] = None, monitorInterval: Union[int, None] = None): super().__init__(parent) self.fc = fc self.loaderNode = fc.nodes()['QCodesDSLoader.0'] self.monitor = QtCore.QTimer() # a flag we use to set reasonable defaults when the first data # is processed self._initialized = False windowTitle = "Plottr | QCoDeS autoplot" if pathAndId is not None: path = os.path.abspath(pathAndId[0]) windowTitle += f" | {os.path.split(path)[1]} [{pathAndId[1]}]" pathAndId = path, pathAndId[1] self.setWindowTitle(windowTitle) # toolbar self.toolbar = self.addToolBar('Data monitoring') # toolbar item: monitor interval self.monitorInput = MonitorIntervalInput() self.monitorInput.setToolTip('Set to 0 for disabling monitoring') self.monitorInput.intervalChanged.connect(self.setMonitorInterval) self.toolbar.addWidget(self.monitorInput) # status bar self.status = QtGui.QStatusBar() self.setStatusBar(self.status) # menu bar menu = self.menuBar() fileMenu = menu.addMenu('&Data') # action: updates from the db file refreshAction = QtGui.QAction('&Refresh', self) refreshAction.setShortcut('R') refreshAction.triggered.connect(self.refreshData) fileMenu.addAction(refreshAction) # more signals/slots self.monitor.timeout.connect(self.monitorTriggered) if pathAndId is not None: self.loaderNode.pathAndId = pathAndId if monitorInterval is not None: self.setMonitorInterval(monitorInterval) if self.loaderNode.nLoadedRecords > 0: self.setDefaults() self._initialized = True
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 __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()
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)
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 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
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()
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()
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 __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()
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
def cli(dataset, flowchart): app = QtGui.QApplication.instance( ) # retrieves the ipython qt application if any if app is None: app = QtGui.QApplication([]) # create one if standalone execution fc = Flowchart(library=LIBRARY, terminals={'dataIn': {'io': 'in'}}) win = pyviViewerWindow(fc) fc.setInput(dataIn=dataset) if flowchart: fc_state = configfile.readConfigFile(flowchart) fc.restoreState(fc_state, clear=False) fc.viewBox.autoRange() import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): app.exec_() app.deleteLater() sys.exit()
import wiimote import wiimote_node if __name__ == '__main__': import sys app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.setWindowTitle('NormalVector Demo') 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={}) w = fc.widget() layout.addWidget(fc.widget(), 0, 0, 2, 1) wiimoteNode = fc.createNode('Wiimote', pos=(-150, 150)) normalNode = fc.createNode('NormalVector', pos=(0, 150)) plotCurve = fc.createNode('PlotCurve', pos=(150, 150)) pw1 = pg.PlotWidget() pw1.setYRange(-1, 1) pw1.setXRange(-1, 1) layout.addWidget(pw1, 0, 1) pw1Node = fc.createNode('PlotWidget', pos=(300, 150)) pw1Node.setPlot(pw1)
import wiimote import wiimote_node if __name__ == '__main__': import sys app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.setWindowTitle('NormalVector Demo') 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={ }) w = fc.widget() layout.addWidget(fc.widget(), 0, 0, 2, 1) wiimoteNode = fc.createNode('Wiimote', pos=(-150, 150)) normalNode = fc.createNode('NormalVector', pos=( 0, 150)) plotCurve = fc.createNode('PlotCurve', pos=(150, 150)) pw1 = pg.PlotWidget() pw1.setYRange(-1, 1) pw1.setXRange(-1, 1) layout.addWidget(pw1, 0, 1) pw1Node = fc.createNode('PlotWidget', pos=(300, 150)) pw1Node.setPlot(pw1)
fclib.registerNodeType(WiimoteNode, [('Sensor',)]) fclib.registerNodeType(IrPlotNode, [('Display',)]) if __name__ == '__main__': import sys app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.setWindowTitle('Wiipoint 2D') cw = QtGui.QWidget() win.setCentralWidget(cw) layout = QtGui.QGridLayout() cw.setLayout(layout) fc = Flowchart(terminals={ 'dataIn': {'io': 'in'}, 'dataOut': {'io': 'out'} }) w = fc.widget() layout.addWidget(fc.widget(), 0, 0, 2, 1) view = pg.GraphicsLayoutWidget() layout.addWidget(view, 0, 1, 2, 1) wiimoteNode = fc.createNode('Wiimote', pos=(0, 0), ) bufferNodeIr = fc.createNode('Buffer', pos=(150, 150)) irPlotNode = fc.createNode('IrPlotNode', pos=(300, 150)) # connect 'Plus' and 'Minus' buttons wiimoteNode.set_buffer_node(bufferNodeIr)
fclib.registerNodeType(WiimoteNode, [('Sensor',)]) if __name__ == '__main__': import sys app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.setWindowTitle('WiimoteNode demo') 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) pw1 = pg.PlotWidget() layout.addWidget(pw1, 0, 1) pw1.setYRange(0, 1024) pw1Node = fc.createNode('PlotWidget', pos=(0, -150)) pw1Node.setPlot(pw1) wiimoteNode = fc.createNode('Wiimote', pos=(0, 0), ) bufferNode = fc.createNode('Buffer', pos=(150, 0))
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()
def __init__(self): self.flowchart = Flowchart() super(DaskFlow, self).__init__(self.flowchart)
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
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("")
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()
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()
# -*- coding: utf-8 -*- """ Created on Sat Feb 27 09:12:30 2016 @author: christoph """ from pyqtgraph.flowchart import Flowchart fc = Flowchart(terminals={ 'nameOfInputTerminal': {'io': 'in'}, 'nameOfOutputTerminal': {'io': 'out'} }) ctrl = fc.ctrlWidget() myLayout.addWidget(ctrl) ## read Qt docs on QWidget and layouts for more information
return {'numberOut': output} fclib.registerNodeType(NumberDisplayNode, [('Data',)]) if __name__ == '__main__': import sys app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.setWindowTitle('Noisalyzer') 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={ }) w = fc.widget() layout.addWidget(fc.widget(), 0, 0, 2, 1) # WiimoteNode: wiimoteNode = fc.createNode('Wiimote', pos=(0, 0), ) wiimoteNode.text.setText(addr) # X Axis: pw_accelX = pg.PlotWidget() layout.addWidget(pw_accelX, 0, 1) pw_accelX.setYRange(0, 1024) # plot node for x axis pw_x_Node = fc.createNode('PlotWidget', pos=(600, 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())
import numpy as np import pyqtgraph.metaarray as metaarray 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
fclib.registerNodeType(SpectrumNode, [('Display',)]) ############################################################################################################### if __name__ == '__main__': import sys app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.setWindowTitle('WiimoteNode demo') 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) pw1 = pg.PlotWidget() pw1.plot(pen='y') layout.addWidget(pw1, 1, 1) pw1.setYRange(0, 1024) pw1Node = fc.createNode('PlotWidget', pos=(300, 150)) pw1Node.setPlot(pw1) pw2 = pg.PlotWidget() pw2.plot(pen='g')
class ActivityRecognition(): RED = QtGui.QColor(255, 0, 0) GREEN = QtGui.QColor(0, 255, 0) YELLOW = QtGui.QColor(255, 255, 0) GRAY = QtGui.QColor(100, 100, 100) def __init__(self, app): self.app = app self.training_mode = False self.recognition_mode = False # self.gestures = {} self.init_ui() self.setup_nodes() self.connect_buttons() self.win.show() if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() def init_ui(self): width, height = self.app.desktop().width(), self.app.desktop().height() self.win = QtGui.QWidget() self.win.setWindowTitle('Activity Recognition') self.win.setGeometry(width / 4, height / 4, width / 2, height / 2) self.main_layout = QtGui.QGridLayout() self.win.setLayout(self.main_layout) self.setup_left_group() self.setup_middle_group() self.setup_right_group() def setup_left_group(self): left_group = QtGui.QGroupBox() left_layout = QtGui.QGridLayout() wm_label = QtGui.QLabel("Enter your mac address") self.wm_addr = QtGui.QLineEdit() self.wm_addr.setPlaceholderText("Enter your mac address here") self.wm_addr.setText("B8:AE:6E:1B:5B:03") self.wm_connect_btn = QtGui.QPushButton("Connect") # wm_connect_btn.clicked.connect(self.connect_wm) left_layout.addWidget(wm_label, 1, 1, 1, 2) left_layout.addWidget(self.wm_addr, 2, 1, 1, 2) left_layout.addWidget(self.wm_connect_btn, 3, 1, 1, 2) self.training_hint = QtGui.QLabel( "You can toggle Training Mode by pressing 'A' on your WiiMote!") self.training_label = QtGui.QLabel("NO WIIMOTE CONNECTED") self.training_label.setAlignment(QtCore.Qt.AlignCenter) self.training_label.setAutoFillBackground(True) self.training_btn = QtGui.QPushButton("Activate Training Mode") left_layout.addWidget(self.training_hint, 4, 1, 1, 2) left_layout.addWidget(self.training_label, 5, 1, 1, 2) left_layout.addWidget(self.training_btn, 6, 1, 1, 2) self.save_label = QtGui.QLabel("Enter a name for your gesture:") self.save_label.setAlignment(QtCore.Qt.AlignCenter) self.save_text = QtGui.QLineEdit() self.save_text.setPlaceholderText("Enter Gesture Name") self.save_btn = QtGui.QPushButton("Save Gesture") left_layout.addWidget(self.save_label, 7, 1, 1, 2) left_layout.addWidget(self.save_text, 8, 1, 1, 2) left_layout.addWidget(self.save_btn, 9, 1, 1, 2) left_group.setLayout(left_layout) self.main_layout.addWidget(left_group, 1, 1, 1, 1) def setup_middle_group(self): middle_group = QtGui.QGroupBox() middle_layout = QtGui.QGridLayout() l1 = QtGui.QLabel() l1.setText("MIDDLE GROUP") middle_layout.addWidget(l1, 1, 1) self.spectrogram_widget = pg.PlotWidget() self.spectrogram_widget.setYRange(0, 128) middle_layout.addWidget(self.spectrogram_widget, 2, 1) middle_group.setLayout(middle_layout) self.main_layout.addWidget(middle_group, 1, 2, 1, 5) def setup_right_group(self): right_group = QtGui.QGroupBox() right_layout = QtGui.QGridLayout() self.connected_status_label = QtGui.QLabel() self.connected_status_label.setAlignment(QtCore.Qt.AlignCenter) self.connected_status_label.setAutoFillBackground(True) connected_status_palette = self.connected_status_label.palette() connected_status_palette.setColor( self.connected_status_label.backgroundRole(), self.RED) self.connected_status_label.setPalette(connected_status_palette) self.connected_status_label.setText("NOT CONNECTED") right_layout.addWidget(self.connected_status_label, 1, 1) self.recording_status_label = QtGui.QLabel() self.recording_status_label.setAlignment(QtCore.Qt.AlignCenter) self.recording_status_label.setAutoFillBackground(True) recording_status_palette = self.recording_status_label.palette() recording_status_palette.setColor( self.recording_status_label.backgroundRole(), self.RED) self.recording_status_label.setPalette(recording_status_palette) self.recording_status_label.setText("Not Recording") right_layout.addWidget(self.recording_status_label, 2, 1) self.recognized_gesture_heading = QtGui.QLabel("Recognized Gesture:") self.recognized_gesture = QtGui.QLabel("UNKNOWN GESTURE") right_layout.addWidget(self.recognized_gesture_heading, 3, 1, 1, 1) right_layout.addWidget(self.recognized_gesture, 4, 1, 1, 1) self.known_gestures = QtGui.QLabel() self.known_gestures.setText("HERE WILL BE ALL KNOWN GESTURES") right_layout.addWidget(self.known_gestures, 5, 1, 3, 1) right_group.setLayout(right_layout) self.main_layout.addWidget(right_group, 1, 7, 1, 1) def setup_nodes(self): # Create an empty flowchart with a single input and output self.fc = Flowchart(terminals={}) self.wiimote_node = self.fc.createNode('Wiimote') self.buffer_node_x = self.fc.createNode('Buffer') self.buffer_node_y = self.fc.createNode('Buffer') self.buffer_node_z = self.fc.createNode('Buffer') self.fft_node = self.fc.createNode('Fft') self.fc.connectTerminals(self.wiimote_node['accelX'], self.buffer_node_x['dataIn']) self.fc.connectTerminals(self.wiimote_node['accelY'], self.buffer_node_y['dataIn']) self.fc.connectTerminals(self.wiimote_node['accelZ'], self.buffer_node_z['dataIn']) self.fc.connectTerminals(self.buffer_node_x['dataOut'], self.fft_node['inX']) self.fc.connectTerminals(self.buffer_node_y['dataOut'], self.fft_node['inY']) self.fc.connectTerminals(self.buffer_node_z['dataOut'], self.fft_node['inZ']) spectrogram_node = self.fc.createNode('PlotWidget') spectrogram_node.setPlot(self.spectrogram_widget) self.fc.connectTerminals(self.fft_node['fft'], spectrogram_node['In']) self.svm_node = self.fc.createNode('Svm') self.fc.connectTerminals(self.fft_node['fft'], self.svm_node['fft']) def connect_buttons(self): self.training_btn.clicked.connect(self.toggle_training_mode) self.wm_connect_btn.clicked.connect(self.connect_wm) self.save_btn.clicked.connect(self.save_gesture) def save_gesture(self): # evtl in list statt dict speichern um mehrere mit gleichne namen zu haben name = self.save_text.text().strip() print(len(name)) if len(name) == 0: name = "Unknown Name" # self.gestures[name] = self.svm_node.get_current_recording() self.svm_node.add_gesture(name) self.save_text.setText("") def connect_wm(self): btaddr = self.wm_addr.text().strip() print(btaddr) self.wiimote_node.connect_wiimote(btaddr, model='Nintendo RVL-CNT-01-TR') self.training_label.setText("Training Mode OFF") self.connected_status_label.setText("CONNECTED") connected_status_palette = self.connected_status_label.palette() connected_status_palette.setColor( self.connected_status_label.backgroundRole(), self.GREEN) self.connected_status_label.setPalette(connected_status_palette) self.wiimote_node.wiimote.buttons.register_callback( self.handle_wm_button) def handle_wm_button(self, buttons): if len(buttons) > 0: for button in buttons: if button[0] == 'A': if button[1]: self.toggle_training_mode() if button[0] == 'B': if button[1]: self.start_recognition_mode() else: self.stop_recognition_mode() def toggle_training_mode(self): self.training_mode = not self.training_mode print('New State (Training Mode): ', self.training_mode) if self.training_mode: self.svm_node.set_training_mode(True) self.training_btn.setText("Deactivate Training Mode") self.training_label.setText("Training Mode ON") training_status_palette = self.training_label.palette() training_status_palette.setColor( self.training_label.backgroundRole(), self.YELLOW) self.training_label.setPalette(training_status_palette) self.recording_status_label.setText("Recording Training Data") p = self.recording_status_label.palette() p.setColor(self.recording_status_label.backgroundRole(), self.YELLOW) self.recording_status_label.setPalette(p) else: self.svm_node.set_training_mode(False) self.training_btn.setText("Activate Training Mode") self.training_label.setText("Training Mode OFF") training_status_palette = self.training_label.palette() training_status_palette.setColor( self.training_label.backgroundRole(), self.GRAY) self.training_label.setPalette(training_status_palette) self.recording_status_label.setText("Not Recording") p = self.recording_status_label.palette() p.setColor(self.recording_status_label.backgroundRole(), self.RED) self.recording_status_label.setPalette(p) def start_recognition_mode(self): print("Start recognition Mode") self.svm_node.set_recognition_mode(True) self.recording_status_label.setText("Recording Recognition Data") p = self.recording_status_label.palette() p.setColor(self.recording_status_label.backgroundRole(), self.YELLOW) self.recording_status_label.setPalette(p) def stop_recognition_mode(self): print("Stop recognition Mode") self.svm_node.set_recognition_mode(False) self.recording_status_label.setText("Not Recording") p = self.recording_status_label.palette() p.setColor(self.recording_status_label.backgroundRole(), self.RED) self.recording_status_label.setPalette(p)
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'])
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()
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)
# Save the default state of view of main window save() # Create and Add a ControllerWidget (for visual and serial communication) controller_w = ControllerWidget() controller.addWidget(controller_w) ##################################### # 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',)])
# Save the default state of view of main window save() # Create and Add a ControllerWidget (for visual and serial communication) controller_w = ControllerWidget() controller.addWidget(controller_w) ##################################### # 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', )])
if __name__ == '__main__': import sys app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.setWindowTitle('WiimoteNode demo') 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) pw1 = pg.PlotWidget() layout.addWidget(pw1, 0, 1) pw1.setYRange(0, 1024) pw1Node = fc.createNode('PlotWidget', pos=(0, -150)) pw1Node.setPlot(pw1) wiimoteNode = fc.createNode(
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()
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)
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_())
import pyqtgraph as pg import numpy as np app = QtGui.QApplication([]) ## Create main window with a grid layout inside win = QtGui.QMainWindow() win.setWindowTitle('pyqtgraph example: FlowchartCustomNode') 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) ## Create two ImageView widgets to display the raw and processed data with contrast ## and color control. v1 = pg.ImageView() v2 = pg.ImageView() layout.addWidget(v1, 0, 1) layout.addWidget(v2, 1, 1) win.show() ## generate random input data
from pyqtgraph.flowchart.library.common import CtrlNode, metaArrayWrapper from pyqtgraph.Qt import QtGui, QtCore app = QtGui.QApplication([]) ## Create main window with a grid layout inside win = QtGui.QMainWindow() win.setWindowTitle('pyqtgraph example: FlowchartCustomNode') 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) ## Create two ImageView widgets to display the raw and processed data with contrast ## and color control. v1 = pg.ImageView() v2 = pg.ImageView() layout.addWidget(v1, 0, 1) layout.addWidget(v2, 1, 1) win.show() import cv2 def loadcv(pth,mode=-1,shape=None):
if __name__ == "__main__": # creating main window app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.setWindowTitle('Wiimote Accelerometer Analyze') cw = QtGui.QWidget() win.setCentralWidget(cw) layout = QtGui.QGridLayout() cw.setLayout(layout) #creating flowchart fc = Flowchart(terminals={ 'dataIn': {'io': 'in'}, 'dataOut': {'io': 'out'} }) w = fc.widget() layout.addWidget(fc.widget(), 0, 0, 2, 1) # three widgets for x-, y- & z-Axis x = pg.PlotWidget() y = pg.PlotWidget() z = pg.PlotWidget() # add widgets to grid layout layout.addWidget(x, 0, 1) layout.addWidget(y, 0, 2) layout.addWidget(z, 0, 3) raw_input("Press the 'sync' button on the back of your Wiimote Plus " + "or buttons (1) and (2) on your classic Wiimote.\n" +
from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg import numpy as np app = QtGui.QApplication([]) ## Create main window with a grid layout inside win = QtGui.QMainWindow() win.setWindowTitle('pyqtgraph example: FlowchartCustomNode') 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) ## Create two ImageView widgets to display the raw and processed data with contrast ## and color control. v1 = pg.ImageView() v2 = pg.ImageView() layout.addWidget(v1, 0, 1) layout.addWidget(v2, 1, 1) win.show() ## generate random input data data = np.random.normal(size=(100, 100))
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'])
fclib.registerNodeType(FFTNode, [('Data',)]) if __name__ == '__main__': import sys app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.setWindowTitle('Frequalyzer') 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={ }) w = fc.widget() layout.addWidget(fc.widget(), 0, 0, 2, 1) # WiimoteNode: wiimoteNode = fc.createNode('Wiimote', pos=(0, 0), ) wiimoteNode.text.setText(addr) # X accelerator axis: # Plots Widget: pw_accelX = pg.PlotWidget(name="X accelerator") layout.addWidget(pw_accelX, 0, 1) pw_accelX.setYRange(-15, 55) pw_accelX.setXRange(0, 40) pw_x_Node = fc.createNode('PlotWidget', pos=(370, -140))
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)
fclib.registerNodeType(PlotNode, [('Display',)]) ############################################################################### 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()
p = os.path.dirname(os.path.abspath(__file__)) p = os.path.join(p, '..', '..') sys.path.insert(0, p) 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)
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()
fclib.registerNodeType(CategoryVisualizerNode, [('Data',)]) if __name__ == '__main__': import sys app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.setWindowTitle('WiimoteNode demo') 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) pw1 = pg.PlotWidget() label = QtGui.QLabel("You're not moving") layout.addWidget(label, 0, 1) layout.addWidget(pw1, 0, 2) pw1.setYRange(0, 1024) pw1Node = fc.createNode('PlotWidget', pos=(0, -150)) pw1Node.setPlot(pw1)