def clearTerminals(self): for t in self.terminals.values(): t.close() self.terminals = OrderedDict() self._inputs = OrderedDict() self._conditions = OrderedDict() self._outputs = OrderedDict()
def __init__(self, **opts): self.forward = OrderedDict() ## name: value self.reverse = OrderedDict() ## value: name ## Parameter uses 'limits' option to define the set of allowed values if 'values' in opts: opts['limits'] = opts['values'] if opts.get('limits', None) is None: opts['limits'] = [] Parameter.__init__(self, **opts) self.setLimits(opts['limits'])
def parse(self, data): """ Given any python object, return: * type * a short string representation * a dict of sub-objects to be parsed * optional widget to display as sub-node """ # defaults for all objects typeStr = type(data).__name__ if typeStr == 'instance': typeStr += ": " + data.__class__.__name__ widget = None desc = "" childs = {} # type-specific changes if isinstance(data, dict): desc = "length=%d" % len(data) if isinstance(data, OrderedDict): childs = data else: childs = OrderedDict(sorted(data.items())) elif isinstance(data, (list, tuple)): desc = "length=%d" % len(data) childs = OrderedDict(enumerate(data)) elif HAVE_METAARRAY and (hasattr(data, 'implements') and data.implements('MetaArray')): childs = OrderedDict([ ('data', data.view(np.ndarray)), ('meta', data.infoCopy()) ]) elif isinstance(data, np.ndarray): desc = "shape=%s dtype=%s" % (data.shape, data.dtype) table = TableWidget() table.setData(data) table.setMaximumHeight(200) widget = table elif isinstance(data, types.TracebackType): ## convert traceback to a list of strings frames = list(map(str.strip, traceback.format_list(traceback.extract_tb(data)))) #childs = OrderedDict([ #(i, {'file': child[0], 'line': child[1], 'function': child[2], 'code': child[3]}) #for i, child in enumerate(frames)]) #childs = OrderedDict([(i, ch) for i,ch in enumerate(frames)]) widget = QtGui.QPlainTextEdit(asUnicode('\n'.join(frames))) widget.setMaximumHeight(200) widget.setReadOnly(True) else: desc = asUnicode(data) return typeStr, desc, childs, widget
def mapping(limits): ## Return forward and reverse mapping dictionaries given a limit specification forward = OrderedDict() ## name: value reverse = OrderedDict() ## value: name if isinstance(limits, dict): for k, v in limits.items(): forward[k] = v reverse[v] = k else: for v in limits: n = asUnicode(v) forward[n] = v reverse[v] = n return forward, reverse
def __init__(self, name, terminals=None, allowAddInput=False, allowAddOutput=False, allowRemove=True): """ ============== ============================================================ Arguments name The name of this specific node instance. It can be any string, but must be unique within a flowchart. Usually, we simply let the flowchart decide on a name when calling Flowchart.addNode(...) terminals Dict-of-dicts specifying the terminals present on this Node. Terminal specifications look like:: 'inputTerminalName': {'io': 'in'} 'outputTerminalName': {'io': 'out'} There are a number of optional parameters for terminals: multi, pos, renamable, removable, multiable, bypass. See the Terminal class for more information. allowAddInput bool; whether the user is allowed to add inputs by the context menu. allowAddOutput bool; whether the user is allowed to add outputs by the context menu. allowRemove bool; whether the user is allowed to remove this node by the context menu. ============== ============================================================ """ QtCore.QObject.__init__(self) self._name = name self._bypass = False self.bypassButton = None ## this will be set by the flowchart ctrl widget.. self._graphicsItem = None self.terminals = OrderedDict() self._inputs = OrderedDict() self._outputs = OrderedDict() self._allowAddInput = allowAddInput ## flags to allow the user to add/remove terminals self._allowAddOutput = allowAddOutput self._allowRemove = allowRemove self.exception = None if terminals is None: return for name, opts in terminals.items(): self.addTerminal(name, **opts)
def setOpts(self, **opts): """ Set any arbitrary options on this parameter. The exact behavior of this function will depend on the parameter type, but most parameters will accept a common set of options: value, name, limits, default, readonly, removable, renamable, visible, enabled, and expanded. See :func:`Parameter.__init__ <pyqtgraph.parametertree.Parameter.__init__>` for more information on default options. """ changed = OrderedDict() for k in opts: if k == 'value': self.setValue(opts[k]) elif k == 'name': self.setName(opts[k]) elif k == 'limits': self.setLimits(opts[k]) elif k == 'default': self.setDefault(opts[k]) elif k not in self.opts or self.opts[k] != opts[k]: self.opts[k] = opts[k] changed[k] = opts[k] if len(changed) > 0: self.sigOptionsChanged.emit(self, changed)
def setFields(self, fields): """ Set the list of fields to be used by the mapper. The format of *fields* is:: [ (fieldName, {options}), ... ] ============== ============================================================ Field Options: mode Either 'range' or 'enum' (default is range). For 'range', The user may specify a gradient of colors to be applied linearly across a specific range of values. For 'enum', the user specifies a single color for each unique value (see *values* option). units String indicating the units of the data for this field. values List of unique values for which the user may assign a color when mode=='enum'. Optionally may specify a dict instead {value: name}. ============== ============================================================ """ self.fields = OrderedDict(fields) #self.fields = fields #self.fields.sort() names = self.fieldNames() self.setAddList(names)
def registerNodeType(cls, paths, override=False): """ Register a new node type. If the type's name is already in use, an exception will be raised (unless override=True). Arguments: cls - a subclass of Node (must have typ.nodeName) paths - list of tuples specifying the location(s) this type will appear in the library tree. override - if True, overwrite any class having the same name """ if not isNodeClass(cls): raise Exception("Object %s is not a Node subclass" % str(cls)) name = cls.nodeName if not override and name in NODE_LIST: raise Exception("Node type name '%s' is already registered." % name) NODE_LIST[name] = cls for path in paths: root = NODE_TREE for n in path: if n not in root: root[n] = OrderedDict() root = root[n] root[name] = cls
def saveState(self): """ Return a structure representing the entire state of the parameter tree. The tree state may be restored from this structure using restoreState() """ state = self.opts.copy() state['children'] = OrderedDict([(ch.name(), ch.saveState()) for ch in self]) if state['type'] is None: global PARAM_NAMES state['type'] = PARAM_NAMES.get(type(self), None) return state
def setFields(self, fields): """ Set the list of field names/units to be processed. The format of *fields* is the same as used by :func:`ColorMapWidget.setFields <pyqtgraph.widgets.ColorMapWidget.ColorMapParameter.setFields>` """ self.fields = OrderedDict(fields) self.fieldList.clear() for f, opts in fields: item = QtGui.QListWidgetItem(f) item.opts = opts item = self.fieldList.addItem(item) self.filter.setFields(fields) self.colorMap.setFields(fields)
def mapping(limits): ## Return forward and reverse mapping objects given a limit specification forward = OrderedDict() ## {name: value, ...} reverse = ([], []) ## ([value, ...], [name, ...]) if isinstance(limits, dict): for k, v in limits.items(): forward[k] = v reverse[0].append(v) reverse[1].append(k) else: for v in limits: n = asUnicode(v) forward[n] = v reverse[0].append(v) reverse[1].append(n) return forward, reverse
def __init__(self, name, opts): self.fieldName = name vals = opts.get('values', []) childs = [] if isinstance(vals, list): vals = OrderedDict([(v, str(v)) for v in vals]) for val, vname in vals.items(): ch = ptree.Parameter.create(name=vname, type='bool', value=True) ch.maskValue = val childs.append(ch) ch = ptree.Parameter.create(name='(other)', type='bool', value=True) ch.maskValue = '__other__' childs.append(ch) ptree.types.SimpleParameter.__init__(self, name=name, autoIncrementName=True, type='bool', value=True, removable=True, renamable=True, children=childs)
def __init__(self, name, opts): self.fieldName = name vals = opts.get('values', []) if isinstance(vals, list): vals = OrderedDict([(v, str(v)) for v in vals]) childs = [{'name': v, 'type': 'color'} for v in vals] childs = [] for val, vname in vals.items(): ch = ptree.Parameter.create(name=vname, type='color') ch.maskValue = val childs.append(ch) ptree.types.GroupParameter.__init__( self, name=name, autoIncrementName=True, removable=True, renamable=True, children=[ dict(name='Values', type='group', children=childs), dict(name='Operation', type='list', value='Overlay', values=['Overlay', 'Add', 'Multiply', 'Set']), dict(name='Channels..', type='group', expanded=False, children=[ dict(name='Red', type='bool', value=True), dict(name='Green', type='bool', value=True), dict(name='Blue', type='bool', value=True), dict(name='Alpha', type='bool', value=True), ]), dict(name='Enabled', type='bool', value=True), dict(name='Default', type='color'), ])
examples = OrderedDict([ ('Command-line usage', 'CLIexample.py'), ('Basic Plotting', 'Plotting.py'), ('ImageView', 'ImageView.py'), ('ParameterTree', 'parametertree.py'), ('Crosshair / Mouse interaction', 'crosshair.py'), ('Data Slicing', 'DataSlicing.py'), ('Plot Customization', 'customPlot.py'), ('Timestamps on x axis', 'DateAxisItem.py'), ('Image Analysis', 'imageAnalysis.py'), ('ViewBox Features', 'ViewBoxFeatures.py'), ('Dock widgets', 'dockarea.py'), ('Console', 'ConsoleWidget.py'), ('Histograms', 'histogram.py'), ('Beeswarm plot', 'beeswarm.py'), ('Symbols', 'Symbols.py'), ('Auto-range', 'PlotAutoRange.py'), ('Remote Plotting', 'RemoteSpeedTest.py'), ('Scrolling plots', 'scrollingPlots.py'), ('HDF5 big data', 'hdf5.py'), ('Demos', OrderedDict([ ('Optics', 'optics_demos.py'), ('Special relativity', 'relativity_demo.py'), ('Verlet chain', 'verlet_chain_demo.py'), ('Koch Fractal', 'fractal.py'), ])), ('GraphicsItems', OrderedDict([ ('Scatter Plot', 'ScatterPlot.py'), #('PlotItem', 'PlotItem.py'), ('IsocurveItem', 'isocurve.py'), ('GraphItem', 'GraphItem.py'), ('ErrorBarItem', 'ErrorBarItem.py'), ('FillBetweenItem', 'FillBetweenItem.py'), ('ImageItem - video', 'ImageItem.py'), ('ImageItem - draw', 'Draw.py'), ('Region-of-Interest', 'ROIExamples.py'), ('Bar Graph', 'BarGraphItem.py'), ('GraphicsLayout', 'GraphicsLayout.py'), ('LegendItem', 'Legend.py'), ('Text Item', 'text.py'), ('Linked Views', 'linkedViews.py'), ('Arrow', 'Arrow.py'), ('ViewBox', 'ViewBoxFeatures.py'), ('Custom Graphics', 'customGraphicsItem.py'), ('Labeled Graph', 'CustomGraphItem.py'), ])), ('Benchmarks', OrderedDict([ ('Video speed test', 'VideoSpeedTest.py'), ('Line Plot update', 'PlotSpeedTest.py'), ('Scatter Plot update', 'ScatterPlotSpeedTest.py'), ('Multiple plots', 'MultiPlotSpeedTest.py'), ])), ('3D Graphics', OrderedDict([ ('Volumetric', 'GLVolumeItem.py'), ('Isosurface', 'GLIsosurface.py'), ('Surface Plot', 'GLSurfacePlot.py'), ('Scatter Plot', 'GLScatterPlotItem.py'), ('Shaders', 'GLshaders.py'), ('Line Plot', 'GLLinePlotItem.py'), ('Mesh', 'GLMeshItem.py'), ('Image', 'GLImageItem.py'), ])), ('Widgets', OrderedDict([ ('PlotWidget', 'PlotWidget.py'), ('SpinBox', 'SpinBox.py'), ('ConsoleWidget', 'ConsoleWidget.py'), ('Histogram / lookup table', 'HistogramLUT.py'), ('TreeWidget', 'TreeWidget.py'), ('ScatterPlotWidget', 'ScatterPlotWidget.py'), ('DataTreeWidget', 'DataTreeWidget.py'), ('GradientWidget', 'GradientWidget.py'), ('TableWidget', 'TableWidget.py'), ('ColorButton', 'ColorButton.py'), #('CheckTable', '../widgets/CheckTable.py'), #('VerticalLabel', '../widgets/VerticalLabel.py'), ('JoystickButton', 'JoystickButton.py'), ])), ('Flowcharts', 'Flowchart.py'), ('Custom Flowchart Nodes', 'FlowchartCustomNode.py'), ])
examples = OrderedDict([ ('Command-line usage', 'CLIexample.py'), ('Basic Plotting', 'Plotting.py'), ('ImageView', 'ImageView.py'), ('ParameterTree', 'parametertree.py'), ('Crosshair / Mouse interaction', 'crosshair.py'), ('Data Slicing', 'DataSlicing.py'), ('Plot Customization', 'customPlot.py'), ('Dock widgets', 'dockarea.py'), ('Console', 'ConsoleWidget.py'), ('Histograms', 'histogram.py'), ('Auto-range', 'PlotAutoRange.py'), ('Remote Plotting', 'RemoteSpeedTest.py'), ( 'GraphicsItems', OrderedDict([ ('Scatter Plot', 'ScatterPlot.py'), #('PlotItem', 'PlotItem.py'), ('IsocurveItem', 'isocurve.py'), ('GraphItem', 'GraphItem.py'), ('ErrorBarItem', 'ErrorBarItem.py'), ('ImageItem - video', 'ImageItem.py'), ('ImageItem - draw', 'Draw.py'), ('Region-of-Interest', 'ROIExamples.py'), ('GraphicsLayout', 'GraphicsLayout.py'), ('LegendItem', 'Legend.py'), ('Text Item', 'text.py'), ('Linked Views', 'linkedViews.py'), ('Arrow', 'Arrow.py'), ('ViewBox', 'ViewBox.py'), ('Custom Graphics', 'customGraphicsItem.py'), ])), ('Benchmarks', OrderedDict([ ('Video speed test', 'VideoSpeedTest.py'), ('Line Plot update', 'PlotSpeedTest.py'), ('Scatter Plot update', 'ScatterPlotSpeedTest.py'), ])), ('3D Graphics', OrderedDict([ ('Volumetric', 'GLVolumeItem.py'), ('Isosurface', 'GLIsosurface.py'), ('Surface Plot', 'GLSurfacePlot.py'), ('Scatter Plot', 'GLScatterPlotItem.py'), ('Shaders', 'GLshaders.py'), ('Line Plot', 'GLLinePlotItem.py'), ('Mesh', 'GLMeshItem.py'), ('Image', 'GLImageItem.py'), ])), ( 'Widgets', OrderedDict([ ('PlotWidget', 'PlotWidget.py'), ('SpinBox', 'SpinBox.py'), ('ConsoleWidget', 'ConsoleWidget.py'), ('Histogram / lookup table', 'HistogramLUT.py'), ('TreeWidget', 'TreeWidget.py'), ('DataTreeWidget', 'DataTreeWidget.py'), ('GradientWidget', 'GradientWidget.py'), ('TableWidget', 'TableWidget.py'), ('ColorButton', 'ColorButton.py'), #('CheckTable', '../widgets/CheckTable.py'), #('VerticalLabel', '../widgets/VerticalLabel.py'), ('JoystickButton', 'JoystickButton.py'), ])), #('GraphicsScene', 'GraphicsScene.py'), ('Flowcharts', 'Flowchart.py'), ('Custom Flowchart Nodes', 'FlowchartCustomNode.py'), #('Canvas', '../canvas'), #('MultiPlotWidget', 'MultiPlotWidget.py'), ])
import pyqtgraph as pg import numpy as np from pyqtgraph.pgcollections import OrderedDict app = pg.mkQApp() listOfTuples = [('text_%d' % i, i, i / 9.) for i in range(12)] listOfLists = [list(row) for row in listOfTuples] plainArray = np.array(listOfLists, dtype=object) recordArray = np.array(listOfTuples, dtype=[('string', object), ('integer', int), ('floating', float)]) dictOfLists = OrderedDict([(name, list(recordArray[name])) for name in recordArray.dtype.names]) listOfDicts = [ OrderedDict([(name, rec[name]) for name in recordArray.dtype.names]) for rec in recordArray ] transposed = [[row[col] for row in listOfTuples] for col in range(len(listOfTuples[0]))] def assertTableData(table, data): assert len(data) == table.rowCount() rows = list(range(table.rowCount())) columns = list(range(table.columnCount())) for r in rows: assert len(data[r]) == table.columnCount() row = [] for c in columns: item = table.item(r, c)
# -*- coding: utf-8 -*- from pyqtgraph.pgcollections import OrderedDict from pyqtgraph import importModules import os, types from pyqtgraph.debug import printExc from ..Node import Node import pyqtgraph.reload as reload NODE_LIST = OrderedDict( ) ## maps name:class for all registered Node subclasses NODE_TREE = OrderedDict() ## categorized tree of Node subclasses def getNodeType(name): try: return NODE_LIST[name] except KeyError: raise Exception("No node type called '%s'" % name) def getNodeTree(): return NODE_TREE def registerNodeType(cls, paths, override=False): """ Register a new node type. If the type's name is already in use, an exception will be raised (unless override=True). Arguments: cls - a subclass of Node (must have typ.nodeName)
def __init__(self, parent=None, size=[]): super(Window, self).__init__(parent) # set window toolbar options, and title. #deb_gp self.setWindowFlags(Qt.Window | Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) self.setWindowTitle("mmWave People Counting") print('Python is ', struct.calcsize("P") * 8, ' bit') print('Python version: ', sys.version_info) self.frameTime = 50 self.graphFin = 1 self.hGraphFin = 1 self.threeD = 1 self.lastFramePoints = np.zeros((5, 1)) self.plotTargets = 1 self.frameNum = 0 self.lastTID = [] self.profile = {'startFreq': 60.25, 'numLoops': 64, 'numTx': 3} self.lastFrameHadTargets = False self.sensorHeight = 1.5 self.numFrameAvg = 10 self.configSent = 0 self.previousFirstZ = -1 #timer to reset fall detected message self.fallTimer = QTimer() self.fallTimer.setSingleShot(True) self.fallTimer.timeout.connect(self.resetFallText) self.fallResetTimerOn = 0 self.fallThresh = -0.22 #color gradients self.Gradients = OrderedDict([ ('bw', { 'ticks': [(0.0, (0, 0, 0, 255)), (1, (255, 255, 255, 255))], 'mode': 'rgb' }), ('hot', { 'ticks': [(0.3333, (185, 0, 0, 255)), (0.6666, (255, 220, 0, 255)), (1, (255, 255, 255, 255)), (0, (0, 0, 0, 255))], 'mode': 'rgb' }), ('jet', { 'ticks': [(1, (166, 0, 0, 255)), (0.32247191011235954, (0, 255, 255, 255)), (0.11348314606741573, (0, 68, 255, 255)), (0.6797752808988764, (255, 255, 0, 255)), (0.902247191011236, (255, 0, 0, 255)), (0.0, (0, 0, 166, 255)), (0.5022471910112359, (0, 255, 0, 255))], 'mode': 'rgb' }), ('summer', { 'ticks': [(1, (255, 255, 0, 255)), (0.0, (0, 170, 127, 255))], 'mode': 'rgb' }), ('space', { 'ticks': [(0.562, (75, 215, 227, 255)), (0.087, (255, 170, 0, 254)), (0.332, (0, 255, 0, 255)), (0.77, (85, 0, 255, 255)), (0.0, (255, 0, 0, 255)), (1.0, (255, 0, 127, 255))], 'mode': 'rgb' }), ('winter', { 'ticks': [(1, (0, 255, 127, 255)), (0.0, (0, 0, 255, 255))], 'mode': 'rgb' }), ('spectrum2', { 'ticks': [(1.0, (255, 0, 0, 255)), (0.0, (255, 0, 255, 255))], 'mode': 'hsv' }), ]) cmap = 'spectrum2' if (cmap in self.Gradients): self.gradientMode = self.Gradients[cmap] self.zRange = 3 self.plotHeights = 1 #gui size if (size): left = 50 top = 50 width = math.ceil(size.width() * 0.9) height = math.ceil(size.height() * 0.9) self.setGeometry(left, top, width, height) #persistent point cloud self.previousCloud = np.zeros((6, 1150, 10)) self.previousPointCount = np.zeros((10, 1)) #self.previousIndex = np.zeros((1,1150,10)) #images self.standingPicture = QPixmap('images/stickFigureStanding.png') self.fallingPicture = QPixmap('images/stickFigureFalling.png') #remove points outside boundary box self.bbox = [-1000, 1000, -1000, 1000, -1000, 1000] #setup graph pyqtgraph self.plot3DQTGraph() self.colorGradient() #self.heightPlots() #self.fallDetData() #self.plot2DQTGraph() #add connect options self.setConnectionLayout() self.setStatsLayout() self.setPlotControlLayout() self.setConfigLayout() #self.setControlLayout() self.setUpBoundaryBoxControls() self.setSensorPositionControls() # set the layout #create tab for different graphing options self.graphTabs = QTabWidget() self.graphTabs.addTab(self.pcplot, '3D Plot') #self.graphTabs.addTab(self.legacyPlot, '2D Plot') self.graphTabs.currentChanged.connect(self.whoVisible) gridlay = QGridLayout() gridlay.addWidget(self.comBox, 0, 0, 1, 1) gridlay.addWidget(self.statBox, 1, 0, 1, 1) gridlay.addWidget(self.configBox, 2, 0, 1, 1) gridlay.addWidget(self.plotControlBox, 3, 0, 1, 1) gridlay.addWidget(self.boxTab, 4, 0, 1, 1) gridlay.addWidget(self.spBox, 5, 0, 1, 1) gridlay.addWidget(self.graphTabs, 0, 1, 6, 1) gridlay.addWidget(self.gw, 0, 2, 6, 1) #gridlay.addWidget(self.demoData, 0,3,1,2) #gridlay.addWidget(self.hPlot,1,3,4,2) gridlay.setColumnStretch(0, 1) gridlay.setColumnStretch(1, 3) self.setLayout(gridlay)
Gradients = OrderedDict([('bw', { 'ticks': [(0.0, (0, 0, 0, 255)), (1, (255, 255, 255, 255))], 'mode': 'rgb' }), ('rgb', { 'ticks': [(0.0, (0, 0, 255, 255)), (0.5, (0, 255, 0, 255)), (1.0, (255, 0, 0, 255))], 'mode': 'rgb' }), ('hot', { 'ticks': [(0.3333, (185, 0, 0, 255)), (0.6666, (255, 220, 0, 255)), (1, (255, 255, 255, 255)), (0, (0, 0, 0, 255))], 'mode': 'rgb' }), ('jet', { 'ticks': [(1, (166, 0, 0, 255)), (0.32247191011235954, (0, 255, 255, 255)), (0.11348314606741573, (0, 68, 255, 255)), (0.6797752808988764, (255, 255, 0, 255)), (0.902247191011236, (255, 0, 0, 255)), (0.0, (0, 0, 166, 255)), (0.5022471910112359, (0, 255, 0, 255))], 'mode': 'rgb' }), ('summer', { 'ticks': [(1, (255, 255, 0, 255)), (0.0, (0, 170, 127, 255))], 'mode': 'rgb' }), ('space', { 'ticks': [(0.562, (75, 215, 227, 255)), (0.087, (255, 170, 0, 254)), (0.332, (0, 255, 0, 255)), (0.77, (85, 0, 255, 255)), (0.0, (255, 0, 0, 255)), (1.0, (255, 0, 127, 255))], 'mode': 'rgb' }), ('winter', { 'ticks': [(1, (0, 255, 127, 255)), (0.0, (0, 0, 255, 255))], 'mode': 'rgb' })])
from pyqtgraph.Point import Point import pyqtgraph.functions as fn from .GraphicsItem import GraphicsItem from .GraphicsObject import GraphicsObject import numpy as np import weakref import pyqtgraph.debug as debug from pyqtgraph.pgcollections import OrderedDict import pyqtgraph as pg #import pyqtgraph as pg __all__ = ['ScatterPlotItem', 'SpotItem'] ## Build all symbol paths Symbols = OrderedDict([(name, QtGui.QPainterPath()) for name in ['o', 's', 't', 'd', '+', 'x']]) Symbols['o'].addEllipse(QtCore.QRectF(-0.5, -0.5, 1, 1)) Symbols['s'].addRect(QtCore.QRectF(-0.5, -0.5, 1, 1)) coords = { 't': [(-0.5, -0.5), (0, 0.5), (0.5, -0.5)], 'd': [(0., -0.5), (-0.4, 0.), (0, 0.5), (0.4, 0)], '+': [ (-0.5, -0.05), (-0.5, 0.05), (-0.05, 0.05), (-0.05, 0.5), (0.05, 0.5), (0.05, 0.05), (0.5, 0.05), (0.5, -0.05), (0.05, -0.05), (0.05, -0.5), (-0.05, -0.5), (-0.05, -0.05) ], } for k, c in coords.items(): Symbols[k].moveTo(*c[0]) for x,y in c[1:]: Symbols[k].lineTo(x, y)
import pyqtgraph.functions as fn from pyqtgraph.graphicsItems.GraphicsObject import GraphicsObject from pyqtgraph.graphicsItems.GraphicsWidget import GraphicsWidget from pyqtgraph.widgets.SpinBox import SpinBox from pyqtgraph.pgcollections import OrderedDict from pyqtgraph.colormap import ColorMap from pyqtgraph.python2_3 import cmp __all__ = ['MTFSliderItem', 'GradientEditorItem'] Gradients = OrderedDict([ ('thermal', {'ticks': [(0.3333, (185, 0, 0, 255)), (0.6666, (255, 220, 0, 255)), (1, (255, 255, 255, 255)), (0, (0, 0, 0, 255))], 'mode': 'rgb'}), ('flame', {'ticks': [(0.2, (7, 0, 220, 255)), (0.5, (236, 0, 134, 255)), (0.8, (246, 246, 0, 255)), (1.0, (255, 255, 255, 255)), (0.0, (0, 0, 0, 255))], 'mode': 'rgb'}), ('yellowy', {'ticks': [(0.0, (0, 0, 0, 255)), (0.2328863796753704, (32, 0, 129, 255)), (0.8362738179251941, (255, 255, 0, 255)), (0.5257586450247, (115, 15, 255, 255)), (1.0, (255, 255, 255, 255))], 'mode': 'rgb'} ), ('bipolar', {'ticks': [(0.0, (0, 255, 255, 255)), (1.0, (255, 255, 0, 255)), (0.5, (0, 0, 0, 255)), (0.25, (0, 0, 255, 255)), (0.75, (255, 0, 0, 255))], 'mode': 'rgb'}), ('spectrum', {'ticks': [(1.0, (255, 0, 255, 255)), (0.0, (255, 0, 0, 255))], 'mode': 'hsv'}), ('cyclic', {'ticks': [(0.0, (255, 0, 4, 255)), (1.0, (255, 0, 0, 255))], 'mode': 'hsv'}), ('greyclip', {'ticks': [(0.0, (0, 0, 0, 255)), (0.99, (255, 255, 255, 255)), (1.0, (255, 0, 0, 255))], 'mode': 'rgb'}), ('grey', {'ticks': [(0.0, (0, 0, 0, 255)), (1.0, (255, 255, 255, 255))], 'mode': 'rgb'}), ]) def addGradientListToDocstring(): """Decorator to add list of current pre-defined gradients to the end of a function docstring.""" def dec(fn): fn.__doc__ = fn.__doc__ + str(Gradients.keys()).strip('[').strip(']') return fn return dec class MTFSliderItem(GraphicsWidget):
def saveTerminals(self): terms = OrderedDict() for n, t in self.terminals.items(): terms[n] = (t.saveState()) return terms
def __init__(self, name, **kwargs): """ ============== ============================================================ **Arguments:** name The name of this specific node instance. It can be any string, but must be unique within a flowchart. Usually, we simply let the flowchart decide on a name when calling Flowchart.addNode(...) terminals Dict-of-dicts specifying the terminals present on this Node. Terminal specifications look like:: 'inputTerminalName': {'io': 'in'} 'outputTerminalName': {'io': 'out'} There are a number of optional parameters for terminals: multi, pos, renamable, removable, multiable, bypass. See the Terminal class for more information. allowAddInput bool; whether the user is allowed to add inputs by the context menu. allowAddOutput bool; whether the user is allowed to add outputs by the context menu. allowRemove bool; whether the user is allowed to remove this node by the context menu. allowOptional bool; whether terminals are allowed to be optional viewable bool; whether a pick one should be inserted into the graph to view node inputs buffered bool; whether a node has a to_operation which returns a rolling buffer exportable bool; whether export should be called filter bool; whether a node is a filter ============== ============================================================ """ super().__init__() self._name = name self._graphicsItem = None self.terminals = OrderedDict() self._inputs = OrderedDict() self._outputs = OrderedDict() self._groups = OrderedDict() # terminal group {"name": set(terminals)} self._allowAddInput = kwargs.get("allowAddInput", False) self._allowAddOutput = kwargs.get("allowAddOutput", False) self._allowRemove = kwargs.get("allowRemove", True) self._allowOptional = kwargs.get("allowOptional", True) self._viewable = kwargs.get("viewable", False) self._buffered = kwargs.get("buffered", False) self._exportable = kwargs.get("exportable", False) self._filter = kwargs.get("filter", False) self._editor = None self._enabled = True self.created = False self.changed = True self.viewed = False self.exception = None self.global_op = kwargs.get("global_op", False) self._input_vars = {} # term:var terminals = kwargs.get("terminals", {}) self.brush = self.determineColor(terminals, self.global_op) self.graphicsItem(self.brush) for name, opts in terminals.items(): self.addTerminal(name, **opts)
Gradients = OrderedDict([('bw', { 'ticks': [(0.0, (0, 0, 0, 255)), (1, (255, 255, 255, 255))], 'mode': 'rgb' }), ('hot', { 'ticks': [(0.33, (185, 0, 0, 255)), (0.66, (255, 220, 0, 255)), (1, (255, 255, 255, 255)), (0, (0, 0, 0, 255))], 'mode': 'rgb' }), ('jet', { 'ticks': [(1, (166, 0, 0, 255)), (0.322, (0, 255, 255, 255)), (0.113, (0, 68, 255, 255)), (0.68, (255, 255, 0, 255)), (0.9, (255, 0, 0, 255)), (0.0, (0, 0, 166, 255)), (0.5, (0, 255, 0, 255))], 'mode': 'rgb' }), ('summer', { 'ticks': [(1, (255, 255, 0, 255)), (0.0, (0, 170, 127, 255))], 'mode': 'rgb' }), ('space', { 'ticks': [(0.562, (75, 215, 227, 255)), (0.087, (255, 170, 0, 254)), (0.332, (0, 255, 0, 255)), (0.77, (85, 0, 255, 255)), (0.0, (255, 0, 0, 255)), (1.0, (255, 0, 127, 255))], 'mode': 'rgb' }), ('winter', { 'ticks': [(1, (0, 255, 127, 255)), (0.0, (0, 0, 255, 255))], 'mode': 'rgb' })])
def setFields(self, fields): self.fields = OrderedDict(fields) names = self.fieldNames() self.setAddList(names)
def getValues(self): """Return a tree of all values that are children of this parameter""" vals = OrderedDict() for ch in self: vals[ch.name()] = (ch.value(), ch.getValues()) return vals