def addColorTransform(f,name): node = numpyInNumpyOutNode( nodeName=name, uiTemplate=[], f=f, ) fclib.registerNodeType(node,[('Image-ColorSpace',)])
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 _normalizeQuantiles(data,newMin,newMax,quantileLow,quantileHigh): ql,qh = mquantiles(np.array(data), prob=[quantileLow,quantileHigh], alphap=0.4, betap=0.4, axis=None, limit=()) d = np.clip(np.array(data),ql,qh) d-=data.min() d/=data.max() d*=(newMax-newMin) d+=newMin return d node = numpyInNumpyOutNode( nodeName="Normalize", uiTemplate=[ ('newMin','spin', {'value': 0, 'step': 1, 'range': [None, None]}), ('newMax','spin', {'value': 255, 'step': 1, 'range': [None, None]}) ], f=_normalize ) fclib.registerNodeType(node,[('Image-Normalize',)]) node = numpyInNumpyOutNode( nodeName="NormalizeQuantiles", uiTemplate=[ ('newMin','spin', {'value': 0, 'step': 1, 'range': [None, None]}), ('newMax','spin', {'value': 255, 'step': 1, 'range': [None, None]}), ('quantileLow','spin', {'value': 0.1, 'step': 0.05, 'range': [0.0,1.0]} ), ('quantileHigh','spin', {'value': 0.9, 'step': 0.05, 'range': [0.0,1.0]} ) ], f=_normalizeQuantiles ) fclib.registerNodeType(node,[('Image-Normalize',)])
def ctrlWidget(self): if self.ui is None: self.ui = ComboBox() self.ui.currentIndexChanged.connect(self.plotSelected) self.updateUi() return self.ui def plotSelected(self, index): self.setPlot(self.ui.value()) def setPlotList(self, plots): """ Specify the set of plots (ImageView) that the user may select from. *plots* must be a dictionary of {name: plot} pairs. """ self.plots = plots self.updateUi() def updateUi(self): # sets list and automatically preserves previous selection self.ui.setItems(self.plots) try: self.ui.setValue(self.plots) except ValueError: pass fclib.registerNodeType(ImagePlotNode, [('Display',)])
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)
try: sample_file = open(which, 'r') for line in sample_file: values = line.strip().split(',') if len(values) is 3: x = int(values[0]) y = int(values[1]) z = int(values[2]) avg.append((x + y + z) / 3) sample_file.close() except IOError: print 'Failed to open file ' + which return avg fclib.registerNodeType(FileReaderNode, [('Data', )]) class LiveFFTNode(Node): ''' ''' nodeName = "FFTLiveNode" def __init__(self, name): terminals = { 'samples': dict(io='in'), 'accelX': dict(io='in'), 'accelY': dict(io='in'), 'accelZ': dict(io='in'), 'samplesFrequencies': dict(io='out'),
'dataOutX': dict(io='out') } self._dataInX = np.array([]) Node.__init__(self, name, terminals=terminals) # calculates standard deviation def calcStd(self, a): standardDeviation = np.std(a) return standardDeviation def process(self, **kwds): self._dataInX = kwds['dataInX'] output = float(self.calcStd(self._dataInX)) return {'dataOutX': output} fclib.registerNodeType(StdDevNode, [('Data',)]) class NumberDisplayNode(Node): nodeName = "NumberDisplayNode" def __init__(self, name): terminals = { 'numberIn': dict(io='in'), 'numberOut': dict(io='out') } Node.__init__(self, name, terminals=terminals) def process(self, **kwds): output = kwds['numberIn'] # shows STD in DisplayWidget
def set_update_rate(self, rate): if rate == 0: # use callbacks for max. update rate self.wiimote.accelerometer.register_callback(self.update_accel) self.update_timer.stop() else: self.wiimote.accelerometer.unregister_callback(self.update_accel) self.update_timer.start(1000.0/rate) def process(self, **kwdargs): x, y, z = self._acc_vals return {'accelX': np.array([x]), 'accelY': np.array([y]), 'accelZ': np.array([z])} fclib.registerNodeType(WiimoteNode, [('Sensor',)]) ############################################################################### class BufferNode(CtrlNode): """ Buffers the last n samples provided on input and provides them as a list of length n on output. A spinbox widget allows for setting the size of the buffer. Default size is 32 samples. """ nodeName = "Buffer" uiTemplate = [ ('size', 'spin', {'value': bufferSize, 'step': 2, 'range': [0, 128]}), ]
fc = Flowchart(terminals={ #'sigOut': {'io': 'in'}, #'sigOut2': {'io': 'in'}#, #'sigIn': {'io': 'out'} #We don't currently need any outputs from FC }, name='Connections') # Remove the unnecessary input and output nodes fc.removeNode(fc.inputNode) fc.removeNode(fc.outputNode) flowchart = fc.widget() d3.addWidget(flowchart) flowchart_dock.addWidget(fc.widget().chartWidget) #Register own node types fclib.registerNodeType(OscilloscopeNode, [('SciEdu',)]) fclib.registerNodeType(FilterNode, [('SciEdu',)]) fclib.registerNodeType(CharToBinaryNode, [('SciEdu',)]) # fclib.registerNodeType(BinaryToCharNode, [('SciEdu',)]) # TODO fclib.registerNodeType(ParityNode, [('SciEdu',)]) fclib.registerNodeType(CheckParityNode, [('SciEdu',)]) fclib.registerNodeType(FFTNode, [('SciEdu',)]) fclib.registerNodeType(SigGenNode, [('SciEdu',)]) fclib.registerNodeType(AmplifierNode, [('SciEdu',)]) fclib.registerNodeType(LineEncoderNode, [('SciEdu',)]) fclib.registerNodeType(RectifierNode, [('SciEdu',)]) fclib.registerNodeType(DCBlockNode, [('SciEdu',)]) fclib.registerNodeType(DigiAdderNode, [('SciEdu',)]) fclib.registerNodeType(NoiseNode, [('SciEdu',)]) # Test thread generation (Not in use now)
print("Acceleration Values:") terminals = { 'accelXIn': dict(io='in'), 'accelYIn': dict(io='in'), 'accelZIn': dict(io='in'), } self._acc_vals = [] Node.__init__(self, name, terminals=terminals) def process(self, **kwds): x = str(kwds['accelXIn'][0]) y = str(kwds['accelYIn'][0]) z = str(kwds['accelZIn'][0]) print("X: " + x + " Y: " + y + " Z: " + z) fclib.registerNodeType(LogNode, [('AccValues',)]) class NormalVectorNode(Node): """ Creates tuples for x-acceleration and z-acceleration values with the average sensor values subtracted """ nodeName = "NormalVector" SIGNAL_AVERAGE = 515 def __init__(self, name): terminals = { 'accelXIn': dict(io='in'), 'accelZIn': dict(io='in'), 'normalVectorX': dict(io='out'),
class Selector(MyCtrlNode): """ Since the windows to show are limited one might need a selector""" nodeName = "Selector2" uiTemplate=[('selection', 'combo', {'values': ['A', 'B'], 'index': 0})] def __init__(self, name): terminals = { 'A': dict(io='in'), 'B': dict(io='in'), 'dataOut': dict(io='out'), # to specify whether it is input or output } # other more advanced options are available # as well.. MyCtrlNode.__init__(self, name, terminals=terminals) def execute(self, A,B, display=True): selection=self.ctrls['selection'].currentIndex() if selection==0: return {'dataOut': A} else: return {'dataOut': B} """ node = numpyInNumpyOutNode( nodeName="selctor2", uiTemplate=[ ('radius','intSpin', {'value': 1, 'min': 1, 'max': 1e9 }) ], f=_normalize ) """ fclib.registerNodeType(Selector,[('Data-Selector',)])
# Y = fft(y) / n # fft computing and normalization # Y = Y[0:int(n/2)] # use only first half as the function is mirrored # print(Y) x = fft(self._bufferX) xfft = abs(x) y = fft(self._bufferY) yfft = abs(y) z = fft(self._bufferZ) zfft = abs(z) return {'XdataOut': xfft, 'YdataOut': yfft, 'ZdataOut': zfft} fclib.registerNodeType(FftNode, [('Data', )]) if __name__ == '__main__': 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={}) w = fc.widget() layout.addWidget(fc.widget(), 0, 0, 2, 1)
outputDataDict = dict(trainLoss=trainLoss, testLoss=testLoss, testAcc=testAcc) self.sigOutputDataChanged.emit(outputDataDict) def plotTestData(self, it, testLossesDict, testAccuraciesDict): trainLoss = {outputName: lossArr[:it] for outputName, lossArr in self.trainLoss.items()} testLoss = {outputName: lossArr[:it // self.testInterval] for outputName, lossArr in self.testLoss.items()} testAcc = {outputName: lossArr[:it // self.testInterval] for outputName, lossArr in self.testAcc.items()} # emit a signal to the plotting gods outputDataDict = dict(trainLoss=trainLoss, testLoss=testLoss, testAcc=testAcc) self.sigOutputDataChanged.emit(outputDataDict) fclib.registerNodeType(SolverNode, [('Layers',)]) class RemoteSolver(QtCore.QObject): sigTrainDataUpdated = QtCore.Signal(object, object) # iteration, trainLoss Dictionary sigTestDataUpdated = QtCore.Signal(object, object, object) # iteration, testLoss Dictionary, testAcc dictionary def __init__(self, filename, niter, testInterval, testIter, weights=None, mode=0): import pyqtgraph.multiprocess as mp # create a remote process proc = mp.QtProcess() # import this module in remote process rcaffe = proc._import('caffe') # this solver lives in the remote process
import vigra import math from node_base import numpyInNumpyOutNode import pyqtgraph.flowchart.library as fclib ####################################################### # # FILTERS # ######################################################## # ERROR!!! """ node = numpyInNumpyOutNode( nodeName="HourGlassFilter", uiTemplate=[ ('scale','spin', {'value': 1.50, 'step': 0.25, 'range': [0.01, None]}) , ('rho', 'spin', {'value': 1.50, 'step': 0.25, 'range': [0.01, None]}) ], f=vigra.filters.hourGlassFilter2D ) fclib.registerNodeType(node,[('Image-Tensors',)]) """ def _powerdGaussianSmoothing(img,sigma,power): img=img**power result = vigra.filters.gaussianSmoothing(img,sigma=sigma)
def decrease_buffer_size(self): size = self.ctrls['size'].value() self.ctrls['size'].setValue(size - 1.0) def process(self, **kwds): size = int(self.ctrls['size'].value()) self._buffer = np.append(self._buffer, kwds['dataIn']) self._buffer = self._buffer[-size:] if self.buttons is None: self.register_buttons(kwds['buttons']) output = self._buffer return {'dataOut': output} fclib.registerNodeType(BufferNode, [('Data',)]) class WiimoteNode(Node): """ Outputs sensor data from a Wiimote. Supported sensors: accelerometer (3 axis) Text input box allows for setting a Bluetooth MAC address. Pressing the "connect" button tries connecting to the Wiimote. Update rate can be changed via a spinbox widget. Setting it to "0" activates callbacks everytime a new sensor value arrives (which is quite often -> performance hit) """ nodeName = "Wiimote"
activity = self.activities['running'] return activity if mean <= standingFrequency or dev < 5.0: activity = self.activities['standing'] return activity if mean > walkingFrequency - (walkingFrequency - standingFrequency) \ and mean < runningFrequency: activity = self.activities['walking'] return activity return activity fclib.registerNodeType(ActivityNode, [('Data', )]) 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'
self.view = view def process(self, data, display=True): ## if process is called with display=False, then the flowchart is being operated ## in batch processing mode, so we should skip displaying to improve performance. if display and self.view is not None: ## the 'data' argument is the value given to the 'data' terminal if data is None: self.view.setImage(np.zeros((1,1))) # give a blank array to clear the view else: self.view.setImage(data) ## register the class so it will appear in the menu of node types. ## It will appear in the 'display' sub-menu. fclib.registerNodeType(ImageViewNode, [('Display',)]) ## We will define an unsharp masking filter node as a subclass of CtrlNode. ## CtrlNode is just a convenience class that automatically creates its ## control widget based on a simple data structure. class UnsharpMaskNode(CtrlNode): """Return the input data passed through scipy.ndimage.gaussian_filter.""" nodeName = "UnsharpMask" uiTemplate = [ ('sigma', 'spin', {'value': 1.0, 'step': 1.0, 'range': [0.0, None]}), ('strength', 'spin', {'value': 1.0, 'dec': True, 'step': 0.5, 'minStep': 0.01, 'range': [0.0, None]}), ] def __init__(self, name): ## Define the input / output terminals available on this node terminals = { 'dataIn': dict(io='in'), # each terminal needs at least a name and
raw_input("Press the 'sync' button on the back of your Wiimote Plus " + "or buttons (1) and (2) on your classic Wiimote.\n" + "Press <return> once the Wiimote's LEDs start blinking.") if len(sys.argv) == 1: addr, name = 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)) wm = connect(addr, name) # fclib.registerNodeType(WiiMoteNode, [('Display',)]) wiiMoteNode = fc.createNode('WiiMote', pos=(0, 0)) fc.connectTerminals(fc['dataIn'], wiiMoteNode['dataIn']) data = wm.accelerometer # three widgets for x-, y- & z-Axis xPlot = pg.PlotWidget() yPlot = pg.PlotWidget() zPlot = pg.PlotWidget() # add widgets to grid layout layout.addWidget(xPlot, 0, 1) layout.addWidget(yPlot, 0, 2) layout.addWidget(zPlot, 0, 3) xGaussianNode = fc.createNode('GaussianFilter', pos=(150, -150)) yGaussianNode = fc.createNode('GaussianFilter', pos=(300, -150))
self.update_timer.stop() self.wiimote.accelerometer.register_callback(self.update_accel) else: self.wiimote.accelerometer.unregister_callback(self.update_accel) self.update_timer.start(1000.0 / rate) def process(self, **kwdargs): x, y, z = self._acc_vals return { 'accelX': np.array([x]), 'accelY': np.array([y]), 'accelZ': np.array([z]) } fclib.registerNodeType(WiimoteNode, [('Sensor', )]) class SvmNode(Node): """ Support Vector Machine that can be switched between training mode and recognition mode via buttons in the UI and on the WiiMote. In training mode it continually reads in a date from the accelerometer. When starting recognition mode the SVM is getting trained with all saved data. While in recognition Mode the data is getting saved and then handed to the SVM for a prediction. """ nodeName = 'Svm' def __init__(self, name): terminals = {
######################################################## def _brightness(image,factor): return vigra.colors.brightness(image,factor=float(factor),range='auto') def _contrast(image,factor): return vigra.colors.contrast(image,factor=float(factor),range='auto') def _gammaCorrection(image,gamma): return vigra.colors.gammaCorrection(image,gamma=float(gamma),range='auto') node = vigraNode( nodeName="Brightness", uiTemplate=[ ('factor', 'spin', {'value': 1.00, 'step': 0.20, 'range': [0.10, None]}) ], f=_brightness, ) fclib.registerNodeType(node,[('Image-Color/Intensity',)]) node = vigraNode( nodeName="Contrast", uiTemplate=[ ('factor', 'spin', {'value': 1.00, 'step': 0.20, 'range': [0.10, None]}) ], f=_contrast, ) fclib.registerNodeType(node,[('Image-Color/Intensity',)]) node = vigraNode( nodeName="GammaCorrection", uiTemplate=[ ('gamma', 'spin', {'value': 1.00, 'step': 0.20, 'range': [0.10, None]}) ], f=_gammaCorrection, ) fclib.registerNodeType(node,[('Image-Color/Intensity',)])
def execute(self, *args,**kwargs): inputList = [] # iterate over all terminals in ordere they where added for termName in self.terminals.keys(): term = self.terminals[termName] if termName in self._inputs: inputData = kwargs[termName] if inputData is not None: inputList.append(inputData) return {'dataOut':inputList} fclib.registerNodeType(MakeList, [('Container',)]) class MakeTuple(MyNode): """ make a tuple from input(s) """ nodeName = "MakeTuple" uiTemplate=[ ] def __init__(self, name): terminals = OrderedDict() terminals['Input']=dict(io='in') terminals['dataOut']=dict(io='out') MyNode.__init__(self, name, terminals=terminals,nodeSize=(100,150),allowAddInput=True)
ew = vigra.filters.tensorEigenvalues(tensor) if sortEigenValues : ew = np.sort(ew,axis=2) if eigenvalue<=1: return ew[:,:,eigenvalue] else : return ew node = numpyInNumpyOutNode( nodeName="BoundaryTensor", uiTemplate=[('scale', 'spin', {'value': 1.50, 'step': 0.25, 'range': [0.01, None]})], f=vigra.filters.boundaryTensor2D, doChannelWise=True, tensor=True ) fclib.registerNodeType(node,[('Image-Tensors',)]) node = numpyInNumpyOutNode( nodeName="StructureTensor", uiTemplate=[ ('innerScale', 'spin', {'value': 1.50, 'step': 0.25, 'range': [0.01, None]}), ('outerScale', 'spin', {'value': 2.50, 'step': 0.25, 'range': [0.01, None]}), ], f=vigra.filters.structureTensor, doChannelWise=True, tensor=True ) fclib.registerNodeType(node,[('Image-Tensors',)]) node = numpyInNumpyOutNode(
return self.ui def hideRow(self, name): w = self.ctrls[name] l = self.ui.layout().labelForField(w) w.hide() l.hide() def showRow(self, name): w = self.ctrls[name] l = self.ui.layout().labelForField(w) w.show() l.show() def execute(self, FeatureImage, LabelImage, display=True): if FeatureImage is None or LabelImage is None: return None FeatureImage = np.require(FeatureImage, dtype=np.float32) LabelImage = np.require(LabelImage, dtype=np.uint32) self.used_features = _get_checked_features(self.ctrls) region_features = vigra.analysis.extractRegionFeatures(FeatureImage, LabelImage, self.used_features) return { 'RegionFeatures': region_features, 'UsedFeatures': self.used_features } fclib.registerNodeType(RegionFeaturesNode, [('Image-Analysis',)])
'VectorX': dict(io='out'), 'VectorY': dict(io='out'), } self._stuff = np.array([]) Node.__init__(self, name, terminals=terminals) def process(self, **kwds): #reduce sensor default values to 0 and calculate angle angle = np.arctan2(kwds['Znormal'] - 512, kwds['Xnormal'] - 512) return { 'VectorX': np.array([0, np.cos(angle)]), 'VectorY': np.array([0, np.sin(angle)]) } fclib.registerNodeType(NormalVectorNode, [('NormalVector', )]) def setupFlowChart(layout, fc, wiimoteNode): pw1 = pg.PlotWidget() layout.addWidget(pw1, 0, 1) pw1.setYRange(0, 1024) pw1Node = fc.createNode('PlotWidget', pos=(-150, 300)) pw1Node.setPlot(pw1) pw2 = pg.PlotWidget() layout.addWidget(pw2, 1, 1) pw2.setYRange(0, 1024) pw2Node = fc.createNode('PlotWidget', pos=(0, 300)) pw2Node.setPlot(pw2)
self.connect_button.setText("disconnect") self.set_update_rate(self.update_rate_input.value()) def set_update_rate(self, rate): if rate == 0: # use callbacks for max. update rate self.wiimote.accelerometer.register_callback(self.update_accel) self.update_timer.stop() else: self.wiimote.accelerometer.unregister_callback(self.update_accel) self.update_timer.start(1000.0/rate) def process(self, **kwdargs): x,y,z = self._acc_vals return {'accelX': np.array([x]), 'accelY': np.array([y]), 'accelZ': np.array([z])} fclib.registerNodeType(WiimoteNode, [('Sensor',)]) ############################################################################################################### class BufferNode(CtrlNode): """ Buffers the last n samples provided on input and provides them as a list of length n on output. A spinbox widget allows for setting the size of the buffer. Default size is 32 samples. """ nodeName = "Buffer" uiTemplate = [ ('size', 'spin', {'value': 100.0, 'step': 1.0, 'range': [0.0, 128.0]}), ] def __init__(self, name):
def __init__(self, name): terminals = { 'Znormal': dict(io='in'), 'Xnormal': dict(io='in'), 'VectorX': dict(io='out'), 'VectorY': dict(io='out'), } self._stuff = np.array([]) Node.__init__(self, name, terminals=terminals) def process(self, **kwds): #reduce sensor default values to 0 and calculate angle angle = np.arctan2(kwds['Znormal'] - 512, kwds['Xnormal'] - 512) return {'VectorX': np.array([0, np.cos(angle)]), 'VectorY': np.array([0, np.sin(angle)])} fclib.registerNodeType(NormalVectorNode, [('NormalVector',)]) def setupFlowChart(layout, fc, wiimoteNode): pw1 = pg.PlotWidget() layout.addWidget(pw1, 0, 1) pw1.setYRange(0, 1024) pw1Node = fc.createNode('PlotWidget', pos=(-150, 300)) pw1Node.setPlot(pw1) pw2 = pg.PlotWidget() layout.addWidget(pw2, 1, 1) pw2.setYRange(0, 1024) pw2Node = fc.createNode('PlotWidget', pos=(0, 300)) pw2Node.setPlot(pw2)
svc.fit(train, cats) cat = svc.predict(classdata) print cat return categories[cat] def process(self, **kwds): cdata = [[kwds['classifyData'][:len(kwds['trainigData'][0])]]] print cdata output = self.classify(kwds['categories'], kwds['trainigData'], cdata) return { 'classification': output } fclib.registerNodeType(SvmClassifierNode, [('Data',)]) class FFTNode(Node): nodeName = "FFTNode" def __init__(self, name): terminals = { 'dataIn': dict(io='in'), 'dataOut': dict(io='out'), } Node.__init__(self, name, terminals=terminals) def calculation(self, data): if(isinstance(data[0], types.ListType)):
'normalX': dict(io='out'), 'normalY': dict(io='out') } Node.__init__(self, name, terminals=terminals) def process(self, **kwds): x = kwds['accelX'] z = kwds['accelZ'] diffx = (612 - x)/200 diffz = (z - 508)/200 return {'normalX': [0, float(np.cos(diffx*np.pi))], 'normalY': [0, float(np.sin(diffz*np.pi))]} fclib.registerNodeType(NormalVectorNode, [('Data',)]) class LogNode(Node): # a LogNode that reads values (e.g., accelerometer data) from its input terminal and writes them to stdout . nodeName = 'Log' def __init__(self, name): terminals = { 'accelX': dict(io='in'), 'accelY': dict(io='in'), 'accelZ': dict(io='in') } Node.__init__(self, name, terminals=terminals)
#'sigOut': {'io': 'in'}, #'sigOut2': {'io': 'in'}#, #'sigIn': {'io': 'out'} #We don't currently need any outputs from FC }, name='Connections') # Remove the unnecessary input and output nodes fc.removeNode(fc.inputNode) fc.removeNode(fc.outputNode) flowchart = fc.widget() d3.addWidget(flowchart) flowchart_dock.addWidget(fc.widget().chartWidget) #Register own node types fclib.registerNodeType(OscilloscopeNode, [('SciEdu', )]) fclib.registerNodeType(FilterNode, [('SciEdu', )]) fclib.registerNodeType(CharToBinaryNode, [('SciEdu', )]) # fclib.registerNodeType(BinaryToCharNode, [('SciEdu',)]) # TODO fclib.registerNodeType(ParityNode, [('SciEdu', )]) fclib.registerNodeType(CheckParityNode, [('SciEdu', )]) fclib.registerNodeType(FFTNode, [('SciEdu', )]) fclib.registerNodeType(SigGenNode, [('SciEdu', )]) fclib.registerNodeType(AmplifierNode, [('SciEdu', )]) fclib.registerNodeType(LineEncoderNode, [('SciEdu', )]) fclib.registerNodeType(RectifierNode, [('SciEdu', )]) fclib.registerNodeType(DCBlockNode, [('SciEdu', )]) fclib.registerNodeType(VCONode, [('SciEdu', )]) fclib.registerNodeType(BinDataSourceNode, [('SciEdu', )]) fclib.registerNodeType(PRBSNode, [('SciEdu', )])
Node.__init__(self, name, terminals=terminals) def process(self, dataIn): data_length = len(dataIn) frequency_spectrum = np.fft.fft( dataIn) / data_length # fft computing and normalization frequency_spectrum = frequency_spectrum[range(data_length / 2)] output = np.abs(frequency_spectrum) print output return {'dataOut': output} fclib.registerNodeType(AnalyzeNode, [('Data', )]) class NoiseNode(CtrlNode): nodeName = "NoiseNode" uiTemplate = [ ('noise', 'spin', { 'value': 5, 'step': 1.0, 'range': [0.0, 128.0] }), ] def __init__(self, name): terminals = { 'dataIn': dict(io='in'),
terminals = { 'dataIn': dict(io='in'), 'dataOut': dict(io='out'), } self._buffer = np.array([]) CtrlNode.__init__(self, name, terminals=terminals) def process(self, **kwds): size = int(self.ctrls['size'].value()) self._buffer = np.append(self._buffer, kwds['dataIn']) self._buffer = self._buffer[-size:] output = self._buffer return {'dataOut': output} fclib.registerNodeType(BufferNode, [('Data', )]) class WiimoteNode(Node): """ Outputs sensor data from a Wiimote. Supported sensors: accelerometer (3 axis) Text input box allows for setting a Bluetooth MAC address. Pressing the "connect" button tries connecting to the Wiimote. Update rate can be changed via a spinbox widget. Setting it to "0" activates callbacks everytime a new sensor value arrives (which is quite often -> performance hit) """ nodeName = "Wiimote"
Node.__init__(self, name, terminals=terminals) def process(self, dataIn): data_length = len(dataIn) frequency_spectrum = np.fft.fft(dataIn) / data_length # fft computing and normalization frequency_spectrum = frequency_spectrum[range(data_length / 2)] output = np.abs(frequency_spectrum) print output return {'dataOut': output} fclib.registerNodeType(AnalyzeNode, [('Data',)]) class NoiseNode(CtrlNode): nodeName = "NoiseNode" uiTemplate = [ ('noise', 'spin', {'value': 5, 'step': 1.0, 'range': [0.0, 128.0]}), ] def __init__(self, name): terminals = { 'dataIn': dict(io='in'), 'dataOut': dict(io='out'), } CtrlNode.__init__(self, name, terminals=terminals)
def process(self, dataIn, display=True): self.addValues(dataIn) return {'X': np.array(self.frequency_array[0]), 'Y': np.array(self._dataIn[0])} def FFT(self, x): n = len(x) k = np.arange(n) T = n/frequency frq = k/T norm = fft.fft(x)/n ret = [frq, abs(norm)] return ret 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={ })
######################################################## def _brightness(image,factor): return vigra.colors.brightness(image,factor=float(factor),range='auto') def _contrast(image,factor): return vigra.colors.contrast(image,factor=float(factor),range='auto') def _gammaCorrection(image,gamma): return vigra.colors.gammaCorrection(image,gamma=float(gamma),range='auto') node = numpyInNumpyOutNode( nodeName="Brightness", uiTemplate=[ ('factor', 'spin', {'value': 1.00, 'step': 0.20, 'range': [0.10, None]}) ], f=_brightness, ) fclib.registerNodeType(node,[('Image-Color/Intensity',)]) node = numpyInNumpyOutNode( nodeName="Contrast", uiTemplate=[ ('factor', 'spin', {'value': 1.00, 'step': 0.20, 'range': [0.10, None]}) ], f=_contrast, ) fclib.registerNodeType(node,[('Image-Color/Intensity',)]) node = numpyInNumpyOutNode( nodeName="GammaCorrection", uiTemplate=[ ('gamma', 'spin', {'value': 1.00, 'step': 0.20, 'range': [0.10, None]}) ], f=_gammaCorrection, ) fclib.registerNodeType(node,[('Image-Color/Intensity',)])
try: sample_file = open(which, "r") for line in sample_file: values = line.strip().split(",") if len(values) is 3: x = int(values[0]) y = int(values[1]) z = int(values[2]) avg.append((x + y + z) / 3) sample_file.close() except IOError: print "Failed to open file " + which return avg fclib.registerNodeType(FileReaderNode, [("Data",)]) class LiveFFTNode(Node): """ """ nodeName = "FFTLiveNode" def __init__(self, name): terminals = { "samples": dict(io="in"), "accelX": dict(io="in"), "accelY": dict(io="in"), "accelZ": dict(io="in"), "samplesFrequencies": dict(io="out"),
# check channels if nC !=3 : raise RuntimeError("wrong number of channels for lab image") self.view.setImage(vigra.colors.transform_Lab2RGB(data)) elif displayType=='MultiChannel': print "display MultiChannel" # check SELECTED channels if channel >= nC : raise RuntimeError("channel index is out of bounds") self.view.setImage(data[:,:,channel]) else: assert False return {'view': self.view} ## register the class so it will appear in the menu of node types. ## It will appear in the 'display' sub-menu. fclib.registerNodeType(ImageViewNode, [('Display',)]) """ print "name ",pName ,"pType",pType if(pType=='spin' or pType == 'intSpin'): kwargs[pName]=self.ctrls[pName].value() elif(pType=='check'): kwargs[pName]=self.ctrls[pName].isChecked() elif(pType=='combo'): kwargs[pName]=self.ctrls[pName].currentIndex() """
def getAverage(self, x, y, z): return (x + y + z)/3 def process(self, **kwds): size = int(self.ctrls['size'].value()) x = kwds['dataInX'] y = kwds['dataInY'] z = kwds['dataInZ'] avg = self.getAverage(x, y, z) data = np.array([avg]) self._buffer = np.append(self._buffer, data) self._buffer = self._buffer[-size:] output = self._buffer return {'dataOut': output} fclib.registerNodeType(BufferNode, [('Data',)]) class WiimoteNode(Node): """ Outputs sensor data from a Wiimote. Supported sensors: accelerometer (3 axis) Text input box allows for setting a Bluetooth MAC address. Pressing the "connect" button tries connecting to the Wiimote. Update rate can be changed via a spinbox widget. Setting it to "0" activates callbacks everytime a new sensor value arrives (which is quite often -> performance hit) """ nodeName = "Wiimote"
def __init__(self, name): terminals = { 'dataIn': dict(io='in'), } self.label = None Node.__init__(self, name, terminals=terminals) def setLabel(self, label): self.label = label def process(self, **kwds): #print kwds['dataIn'] if self.label is not None: self.label.setText(kwds['dataIn']) 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'},
'z_rotation_out': dict(io='out') } CtrlNode.__init__(self, node_name, terminals=terminals) def process(self, **kwds): out = [kwds['x_axis_in'] - 512, kwds['z_axis_in'] - 512] return { 'x_rotation_out': np.array([0, out[0]]), 'z_rotation_out': np.array([0, out[1]]) } fclib.registerNodeType(CustomNormalVectorNode, [('NVN',)]) def input_from_cmd(): """ checks if cmd args are exactly 2 in number :return: void """ if len(sys.argv) != 2: raise Exception("Insufficient number of CMD Args! Mac Address Required") def add_plot_widget_to_layout(layout, offset, columns): """
#self.uiTree.collapseTree(param.param('NodeOptions').makeTreeItem(1)) #param.param('NodeOptions').hide() self.uiTree.update() def execute(self, dataIn, display=True): #print "1",self.getParamValue(['P2']) #print "2",self.getParamValue(['Group1','NamedList_']) #print "3",self.getParamValue(['Group1','Subgroup','Sub-param2']) #print "4",self.getParamValue(['Group1','Subgroup','Action Parameter']) return {'dataOut':None} def onActionButtonPress(self,actionPath): print "onActionButtonPress",actionPath fclib.registerNodeType(TestNode, [('Tests',)]) ################################################### # # numpy # ################################################### _stringedBooleanOperators = { '==' : '__eq__' , '!=' : '__ne__' , '<' : '__lt__' , '>' : '__gt__' ,
self.counter = 0 self._buffer = np.array([]) CtrlNode.__init__(self, name, terminals=terminals) def process(self, **kwds): self.counter += 1 # print(self.counter) size = int(self.ctrls['size'].value()) self._buffer = np.append(self._buffer, kwds['dataIn']) self._buffer = self._buffer[-size:] output = self._buffer print(output) return {'dataOut': output} fclib.registerNodeType(BufferNode, [('Data', )]) class WiimoteNode(Node): """ Outputs sensor data from a Wiimote. Supported sensors: accelerometer (3 axis) Text input box allows for setting a Bluetooth MAC address. Pressing the "connect" button tries connecting to the Wiimote. Update rate can be changed via a spinbox widget. Setting it to "0" activates callbacks every time a new sensor value arrives (which is quite often -> performance hit) """ nodeName = "Wiimote"
if termName in self._inputs: inputData = kwargs[termName] if inputData is not None: cmapPath = self.termNameToCmPath[termName] cmap = self.getParamValue(*cmapPath) print "inputDataShape",termName,cmap return { 'dataOut': res } fclib.registerNodeType(NewBlender, [('Image-Channels',)]) class ChannelStacker(MyNode): """ stack channels of all input(s) """ nodeName = "ChannelStacker" uiTemplate=[ ] def __init__(self, name): """ terminals = { 'Data0': dict(io='in'), 'Data1': dict(io='in'), 'dataOut': dict(io='out'), }p