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'), ])
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 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 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 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 __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, 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._freeze = False #TODO added self.freezeButton = 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 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 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, 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'), ])
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, 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)
class ListParameter(Parameter): itemClass = ListParameterItem 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 setLimits(self, limits): self.forward, self.reverse = self.mapping(limits) Parameter.setLimits(self, limits) #print self.name(), self.value(), limits if self.value() not in self.reverse and len(self.reverse) > 0: self.setValue(list(self.reverse.keys())[0]) @staticmethod 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
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' })])
def clearTerminals(self): for t in self.terminals.values(): t.close() self.terminals = OrderedDict() self._inputs = OrderedDict() self._outputs = OrderedDict()
class Node(QtCore.QObject): """ Node represents the basic processing unit of a flowchart. A Node subclass implements at least: 1) A list of input / ouptut terminals and their properties A flowchart thus consists of multiple instances of Node subclasses, each of which is connected to other by wires between their terminals. A flowchart is, itself, also a special subclass of Node. This allows Nodes within the flowchart to connect to the input/output nodes of the flowchart itself. Optionally, a node class can implement the ctrlWidget() method, which must return a QWidget (usually containing other widgets) that will be displayed in the flowchart control panel. Some nodes implement fairly complex control widgets, but most nodes follow a simple form-like pattern: a list of parameter names and a single value (represented as spin box, check box, etc..) for each parameter. To make this easier, the CtrlNode subclass allows you to instead define a simple data structure that CtrlNode will use to automatically generate the control widget. """ sigClosed = QtCore.Signal(object, object) # name, input_vars sigTerminalAdded = QtCore.Signal(object, object) # self, term sigTerminalRemoved = QtCore.Signal(object, object) # self, term sigTerminalConnected = QtCore.Signal(object, object) # localTerm, remoteTerm sigTerminalDisconnected = QtCore.Signal(object, object) # localTerm, remoteTerm sigTerminalEdited = QtCore.Signal(object, object) sigTerminalOptional = QtCore.Signal(object, object) # self, term sigNodeEnabled = QtCore.Signal(object) # self 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) def nextGroupName(self): group = "group.%d" i = 1 while (group % i) in self._groups: i += 1 return (group % i) def nextTerminalName(self, name): """Return an unused terminal name""" name2 = name i = 1 while name2 in self.terminals: name2 = "%s.%d" % (name, i) i += 1 return name2 def determineColor(self, terminals, global_op=False): isInput = True isOutput = True for name, term in terminals.items(): if term['io'] == 'in': isInput = False elif term['io'] == 'out': isOutput = False brush = None if global_op: brush = fn.mkBrush(100, 150, 255, 255) if isInput and not isOutput: brush = fn.mkBrush(255, 0, 0, 255) elif isOutput and not isInput: brush = fn.mkBrush(0, 255, 0, 255) return brush def nodeEnabled(self, enabled): self._enabled = enabled # block signals so that flowchart.nodeEnabled doesn't get called recursively self.graphicsItem().enabled.blockSignals(True) self.graphicsItem().enabled.setChecked(enabled) self.graphicsItem().enabled.blockSignals(False) if enabled: if self.brush: self.graphicsItem().setBrush(self.brush) else: self.graphicsItem().setBrush(fn.mkBrush(255, 255, 255, 255)) else: self.graphicsItem().setBrush(fn.mkBrush(255, 255, 0, 255)) def addInput(self, name="In", **kwargs): """Add a new input terminal to this Node with the given name. Extra keyword arguments are passed to Terminal.__init__. This is a convenience function that just calls addTerminal(io='in', ...)""" ttype = typing.Any if 'ttype' in kwargs: ttype = kwargs.pop('ttype') elif 'In' in self.terminals: ttype = self.terminals['In'].type() return self.addTerminal(name, io='in', ttype=ttype, **kwargs) def addOutput(self, name="Out", **kwargs): """Add a new output terminal to this Node with the given name. Extra keyword arguments are passed to Terminal.__init__. This is a convenience function that just calls addTerminal(io='out', ...)""" ttype = typing.Any if 'ttype' in kwargs: ttype = kwargs.pop('ttype') elif 'Out' in self.terminals: ttype = self.terminals['Out'].type() return self.addTerminal(name, io='out', ttype=ttype, **kwargs) def removeTerminal(self, term): """Remove the specified terminal from this Node. May specify either the terminal's name or the terminal itself. Causes sigTerminalRemoved to be emitted.""" if isinstance(term, Terminal): name = term.name() else: name = term term = self.terminals[name] # print "remove", name # term.disconnectAll() term.close() del self.terminals[name] if name in self._inputs: del self._inputs[name] if name in self._outputs: del self._outputs[name] self.graphicsItem().updateTerminals() self.sigTerminalRemoved.emit(self, term) self.graphicsItem().buildMenu(reset=True) group_name = term._group if group_name in self._groups: group = self._groups[group_name] group.discard(name) terms = [] for term in group: terms.append(term) for term in terms: self.removeTerminal(term) if group_name in self._groups: del self._groups[group_name] def addTerminal(self, name, group=None, **opts): """Add a new terminal to this Node with the given name. Extra keyword arguments are passed to Terminal.__init__. Causes sigTerminalAdded to be emitted.""" name = self.nextTerminalName(name) term = Terminal(self, name, group=group, **opts) self.terminals[name] = term if term.isInput(): self._inputs[name] = weakref.ref(self.terminals[name]) term.sigTerminalOptional.connect(self.optionalTerm) elif term.isOutput(): self._outputs[name] = weakref.ref(self.terminals[name]) if group: if group not in self._groups: self._groups[group] = set() group = self._groups[group] group.add(name) self.graphicsItem().updateTerminals() self.sigTerminalAdded.emit(self, term) return term def inputs(self): """Return dict of all input terminals. Warning: do not modify.""" return self._inputs def outputs(self): """Return dict of all output terminals. Warning: do not modify.""" return self._outputs def viewable(self): return self._viewable def buffered(self): return self._buffered def buffered_topics(self): """ Buffered nodes can override their topics/terms. """ return { in_var: self.name() + '.' + term for term, in_var in self.input_vars().items() } def buffered_terms(self): """ Buffered nodes can override their topics/terms. """ return self.input_vars() def exportable(self): return self._exportable def filter(self): return self._filter def enabled(self): return self._enabled def input_vars(self): # we need to sort input_vars input_vars = {} for name, term in self.terminals.items(): if name in self._input_vars: if term.optional(): input_vars[name] = modifiers.optional( self._input_vars[name]) else: input_vars[name] = self._input_vars[name] return input_vars def input_units(self): units = {} for key, term in self.terminals.items(): if key in self._input_vars: units[key] = term.unit() return units def output_vars(self): output_vars = [] for name, output in self._outputs.items(): output_vars.append('.'.join([self.name(), name])) return output_vars def graphicsItem(self, brush=None): """Return the GraphicsItem for this node. Subclasses may re-implement this method to customize their appearance in the flowchart.""" if self._graphicsItem is None: self._graphicsItem = NodeGraphicsItem(self, brush) return self._graphicsItem def __getitem__(self, item): # return getattr(self, item) """Return the terminal with the given name""" if item not in self.terminals: raise KeyError(item) else: return self.terminals[item] def name(self): """Return the name of this node.""" return self._name def __repr__(self): return "<Node %s @%x>" % (self.name(), id(self)) def ctrlWidget(self): """Return this Node's control widget. By default, Nodes have no control widget. Subclasses may reimplement this method to provide a custom widget. This method is called by Flowcharts when they are constructing their Node list.""" return None def connected(self, localTerm, remoteTerm, pos=None): """Called whenever one of this node's terminals is connected elsewhere.""" node = remoteTerm.node() if localTerm.isInput() and remoteTerm.isOutput(): if node.exportable() and node.values['alias']: self._input_vars[localTerm.name()] = node.values['alias'] elif node.isSource(): self._input_vars[localTerm.name()] = node.name() else: self._input_vars[localTerm.name()] = '.'.join( [node.name(), remoteTerm.name()]) if not self.changed: self.changed = localTerm.isInput() self.sigTerminalConnected.emit(localTerm, remoteTerm) def disconnected(self, localTerm, remoteTerm): """Called whenever one of this node's terminals is disconnected from another.""" if localTerm.isInput() and remoteTerm.isOutput(): del self._input_vars[localTerm.name()] self.changed = localTerm.isInput() self.sigTerminalDisconnected.emit(localTerm, remoteTerm) def isConnected(self): for name, term in self.terminals.items(): if not term.isConnected(): return False return True def hasInput(self): for name, term in self.inputs().items(): if not term().isConnected(): return False return True def setException(self, exc): self.exception = exc self.recolor(typ="exception") def clearException(self): self.setException(None) def recolor(self, typ=None): if typ == "exception": self.graphicsItem().setPen(QtGui.QPen(QtGui.QColor(255, 0, 0), 5)) elif typ == "selected": self.graphicsItem().setPen(QtGui.QPen(QtGui.QColor(250, 150, 0), 3)) else: self.graphicsItem().setPen(QtGui.QPen(QtGui.QColor(0, 0, 0))) def saveState(self): """Return a dictionary representing the current state of this node (excluding input / output values). This is used for saving/reloading flowcharts. The default implementation returns this Node's position, bypass state, and information about each of its terminals. Subclasses may want to extend this method, adding extra keys to the returned dict.""" pos = self.graphicsItem().pos() state = { 'pos': (pos.x(), pos.y()), 'enabled': self._enabled, 'viewed': self.viewed } state['terminals'] = self.saveTerminals() return state def restoreState(self, state): """Restore the state of this node from a structure previously generated by saveState(). """ pos = state.get('pos', (0, 0)) self.graphicsItem().setPos(*pos) self._enabled = state.get('enabled') self.viewed = state.get('viewed', False) if 'terminals' in state: self.restoreTerminals(state['terminals']) def saveTerminals(self): terms = OrderedDict() for n, t in self.terminals.items(): terms[n] = (t.saveState()) return terms def restoreTerminals(self, state): for name in list(self.terminals.keys()): if name not in state: self.removeTerminal(name) for name, opts in state.items(): if type(opts['ttype']) is str: opts['ttype'] = eval(opts['ttype']) if name in self.terminals: term = self[name] term.setOpts(**opts) continue try: self.addTerminal(name, **opts) except Exception: printExc("Error restoring terminal %s (%s):" % (str(name), str(opts))) def clearTerminals(self): for t in self.terminals.values(): t.close() self.terminals = OrderedDict() self._inputs = OrderedDict() self._outputs = OrderedDict() def close(self, emit=True): """Cleans up after the node--removes terminals, graphicsItem, widget""" if emit: self.sigClosed.emit(self, self.input_vars()) self.disconnectAll() self.clearTerminals() item = self.graphicsItem() if item.scene() is not None: item.scene().removeItem(item) self._graphicsItem = None w = self.ctrlWidget() if w is not None: w.setParent(None) w.close() def disconnectAll(self): for t in self.terminals.values(): t.disconnectAll() def isSource(self): return False def isChanged(self, restore_ctrl, restore_widget): return False def setGraph(self, graph): self._graph = graph def optionalTerm(self, term): if self._allowOptional: checked = all([ term.isInput() and term.optional() for name, term in self.terminals.items() ]) self.graphicsItem().optional.setChecked(checked) self.sigTerminalOptional.emit(self, term) def plotMetadata(self, **kwargs): return {} def onCreate(self): pass
class Node(QtCore.QObject): """ Node represents the basic processing unit of a flowchart. A Node subclass implements at least: 1) A list of input / ouptut terminals and their properties 2) a process() function which takes the names of input terminals as keyword arguments and returns a dict with the names of output terminals as keys. A flowchart thus consists of multiple instances of Node subclasses, each of which is connected to other by wires between their terminals. A flowchart is, itself, also a special subclass of Node. This allows Nodes within the flowchart to connect to the input/output nodes of the flowchart itself. Optionally, a node class can implement the ctrlWidget() method, which must return a QWidget (usually containing other widgets) that will be displayed in the flowchart control panel. Some nodes implement fairly complex control widgets, but most nodes follow a simple form-like pattern: a list of parameter names and a single value (represented as spin box, check box, etc..) for each parameter. To make this easier, the CtrlNode subclass allows you to instead define a simple data structure that CtrlNode will use to automatically generate the control widget. """ sigOutputChanged = QtCore.Signal(object) # self sigClosed = QtCore.Signal(object) sigRenamed = QtCore.Signal(object, object) sigTerminalRenamed = QtCore.Signal(object, object) # term, oldName sigTerminalAdded = QtCore.Signal(object, object) # self, term sigTerminalRemoved = QtCore.Signal(object, object) # self, term 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._freeze = False #TODO added self.freezeButton = 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 nextTerminalName(self, name): """Return an unused terminal name""" name2 = name i = 1 while name2 in self.terminals: name2 = "%s.%d" % (name, i) i += 1 return name2 def addInput(self, name="Input", **args): """Add a new input terminal to this Node with the given name. Extra keyword arguments are passed to Terminal.__init__. This is a convenience function that just calls addTerminal(io='in', ...)""" #print "Node.addInput called." return self.addTerminal(name, io='in', **args) def addOutput(self, name="Output", **args): """Add a new output terminal to this Node with the given name. Extra keyword arguments are passed to Terminal.__init__. This is a convenience function that just calls addTerminal(io='out', ...)""" return self.addTerminal(name, io='out', **args) def removeTerminal(self, term): """Remove the specified terminal from this Node. May specify either the terminal's name or the terminal itself. Causes sigTerminalRemoved to be emitted.""" if isinstance(term, Terminal): name = term.name() else: name = term term = self.terminals[name] #print "remove", name #term.disconnectAll() term.close() del self.terminals[name] if name in self._inputs: del self._inputs[name] if name in self._outputs: del self._outputs[name] self.graphicsItem().updateTerminals() self.sigTerminalRemoved.emit(self, term) def terminalRenamed(self, term, oldName): """Called after a terminal has been renamed Causes sigTerminalRenamed to be emitted.""" newName = term.name() for d in [self.terminals, self._inputs, self._outputs]: if oldName not in d: continue d[newName] = d[oldName] del d[oldName] self.graphicsItem().updateTerminals() self.sigTerminalRenamed.emit(term, oldName) def addTerminal(self, name, **opts): """Add a new terminal to this Node with the given name. Extra keyword arguments are passed to Terminal.__init__. Causes sigTerminalAdded to be emitted.""" name = self.nextTerminalName(name) term = Terminal(self, name, **opts) self.terminals[name] = term if term.isInput(): self._inputs[name] = term elif term.isOutput(): self._outputs[name] = term self.graphicsItem().updateTerminals() self.sigTerminalAdded.emit(self, term) return term def inputs(self): """Return dict of all input terminals. Warning: do not modify.""" return self._inputs def outputs(self): """Return dict of all output terminals. Warning: do not modify.""" return self._outputs def process(self, **kargs): """Process data through this node. This method is called any time the flowchart wants the node to process data. It will be called with one keyword argument corresponding to each input terminal, and must return a dict mapping the name of each output terminal to its new value. This method is also called with a 'display' keyword argument, which indicates whether the node should update its display (if it implements any) while processing this data. This is primarily used to disable expensive display operations during batch processing. """ return {} def graphicsItem(self): """Return the GraphicsItem for this node. Subclasses may re-implement this method to customize their appearance in the flowchart.""" if self._graphicsItem is None: self._graphicsItem = NodeGraphicsItem(self) return self._graphicsItem ## this is just bad planning. Causes too many bugs. def __getattr__(self, attr): """Return the terminal with the given name""" if attr not in self.terminals: raise AttributeError(attr) else: import traceback traceback.print_stack() print("Warning: use of node.terminalName is deprecated; use node['terminalName'] instead.") return self.terminals[attr] def __getitem__(self, item): #return getattr(self, item) """Return the terminal with the given name""" if item not in self.terminals: raise KeyError(item) else: return self.terminals[item] def name(self): """Return the name of this node.""" return self._name def rename(self, name): """Rename this node. This will cause sigRenamed to be emitted.""" oldName = self._name self._name = name #self.emit(QtCore.SIGNAL('renamed'), self, oldName) self.sigRenamed.emit(self, oldName) def dependentNodes(self): """Return the list of nodes which provide direct input to this node""" nodes = set() for t in self.inputs().values(): nodes |= set([i.node() for i in t.inputTerminals()]) return nodes #return set([t.inputTerminals().node() for t in self.listInputs().itervalues()]) def __repr__(self): return "<Node %s @%x>" % (self.name(), id(self)) def ctrlWidget(self): """Return this Node's control widget. By default, Nodes have no control widget. Subclasses may reimplement this method to provide a custom widget. This method is called by Flowcharts when they are constructing their Node list.""" return None def bypass(self, byp): """Set whether this node should be bypassed. When bypassed, a Node's process() method is never called. In some cases, data is automatically copied directly from specific input nodes to output nodes instead (see the bypass argument to Terminal.__init__). This is usually called when the user disables a node from the flowchart control panel. """ self._bypass = byp if self.bypassButton is not None: self.bypassButton.setChecked(byp) self.update() def freeze(self, freeze): """Set whether this node should be freezed. When freezed, a Node's process() method is never called. This is usually called when the user freeze a node from the flowchart control panel. """ self._freeze = self.processFreezed() if freeze else False #TODO Added if self.freezeButton is not None: self.freezeButton.setChecked(freeze) self.update() self.recolor() def isBypassed(self): """Return True if this Node is currently bypassed.""" return self._bypass def isFreezed(self): #TODO added """Return True if this Node is currently freezed.""" return True if self._freeze else False def setInput(self, **args): """Set the values on input terminals. For most nodes, this will happen automatically through Terminal.inputChanged. This is normally only used for nodes with no connected inputs.""" changed = False for k, v in args.items(): term = self._inputs[k] oldVal = term.value() if not eq(oldVal, v): changed = True term.setValue(v, process=False) if changed and '_updatesHandled_' not in args: self.update() def inputValues(self): """Return a dict of all input values currently assigned to this node.""" vals = {} for n, t in self.inputs().items(): vals[n] = t.value() return vals def outputValues(self): """Return a dict of all output values currently generated by this node.""" vals = {} for n, t in self.outputs().items(): vals[n] = t.value() return vals def connected(self, localTerm, remoteTerm): """Called whenever one of this node's terminals is connected elsewhere.""" pass def disconnected(self, localTerm, remoteTerm): """Called whenever one of this node's terminals is disconnected from another.""" pass def update(self, signal=True): """Collect all input values, attempt to process new output values, and propagate downstream. Subclasses should call update() whenever thir internal state has changed (such as when the user interacts with the Node's control widget). Update is automatically called when the inputs to the node are changed. """ vals = self.inputValues() #print " inputs:", vals try: if self.isBypassed(): out = self.processBypassed(vals) elif self.isFreezed(): #TODO added out = self.processFreezed() else: out = self.process(**strDict(vals)) #print " output:", out if out is not None: if signal: self.setOutput(**out) else: self.setOutputNoSignal(**out) for n,t in self.inputs().items(): t.setValueAcceptable(True) self.clearException() except: #printExc( "Exception while processing %s:" % self.name()) for n,t in self.outputs().items(): t.setValue(None) self.setException(sys.exc_info()) if signal: #self.emit(QtCore.SIGNAL('outputChanged'), self) ## triggers flowchart to propagate new data self.sigOutputChanged.emit(self) ## triggers flowchart to propagate new data def processBypassed(self, args): """Called when the flowchart would normally call Node.process, but this node is currently bypassed. The default implementation looks for output terminals with a bypass connection and returns the corresponding values. Most Node subclasses will _not_ need to reimplement this method.""" result = {} for term in list(self.outputs().values()): byp = term.bypassValue() if byp is None: result[term.name()] = None else: result[term.name()] = args.get(byp, None) return result def processFreezed(self): #TODO added """Called when the flowchart would normally call Node.process, but this node is currently freezed.""" result = {} for term in list(self.outputs().values()): result[term.name()] = term.value() return result def setOutput(self, **vals): self.setOutputNoSignal(**vals) #self.emit(QtCore.SIGNAL('outputChanged'), self) ## triggers flowchart to propagate new data self.sigOutputChanged.emit(self) ## triggers flowchart to propagate new data def setOutputNoSignal(self, **vals): for k, v in vals.items(): term = self.outputs()[k] term.setValue(v) #targets = term.connections() #for t in targets: ## propagate downstream #if t is term: #continue #t.inputChanged(term) term.setValueAcceptable(True) def setException(self, exc): self.exception = exc self.recolor() def clearException(self): self.setException(None) def recolor(self): if self.exception is None: if self.isFreezed(): #TODO Added self.graphicsItem().setPen(QtGui.QPen(QtGui.QColor(0, 128, 255), 3)) else: self.graphicsItem().setPen(QtGui.QPen(QtGui.QColor(0, 0, 0))) else: self.graphicsItem().setPen(QtGui.QPen(QtGui.QColor(150, 0, 0), 3)) def saveState(self): """Return a dictionary representing the current state of this node (excluding input / output values). This is used for saving/reloading flowcharts. The default implementation returns this Node's position, bypass state, and information about each of its terminals. Subclasses may want to extend this method, adding extra keys to the returned dict.""" pos = self.graphicsItem().pos() state = {'pos': (pos.x(), pos.y()), 'bypass': self.isBypassed(), 'freeze': self._freeze} #TODO Added termsEditable = self._allowAddInput | self._allowAddOutput for term in self._inputs.values() + self._outputs.values(): termsEditable |= term._renamable | term._removable | term._multiable if termsEditable: state['terminals'] = self.saveTerminals() return state def restoreState(self, state): """Restore the state of this node from a structure previously generated by saveState(). """ pos = state.get('pos', (0,0)) freeze = state.get('freeze', False) self._freeze = freeze self.graphicsItem().setPos(*pos) self.bypass(state.get('bypass', False)) self.freeze(True if freeze else False) #TODO Added self._freeze = freeze if freeze: self.setOutput(**freeze) if 'terminals' in state: self.restoreTerminals(state['terminals']) def saveTerminals(self): terms = OrderedDict() for n, t in self.terminals.items(): terms[n] = (t.saveState()) return terms def restoreTerminals(self, state): for name in list(self.terminals.keys()): if name not in state: self.removeTerminal(name) for name, opts in state.items(): if name in self.terminals: term = self[name] term.setOpts(**opts) continue try: opts = strDict(opts) self.addTerminal(name, **opts) except: printExc("Error restoring terminal %s (%s):" % (str(name), str(opts))) def clearTerminals(self): for t in self.terminals.values(): t.close() self.terminals = OrderedDict() self._inputs = OrderedDict() self._outputs = OrderedDict() def close(self): """Cleans up after the node--removes terminals, graphicsItem, widget""" self.disconnectAll() self.clearTerminals() item = self.graphicsItem() if item.scene() is not None: item.scene().removeItem(item) self._graphicsItem = None w = self.ctrlWidget() if w is not None: w.setParent(None) #self.emit(QtCore.SIGNAL('closed'), self) self.sigClosed.emit(self) def disconnectAll(self): for t in self.terminals.values(): t.disconnectAll()
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)
def __setitem__(self, item, val): self.pop(item, None) # make sure item is added to end OrderedDict.__setitem__(self, item, val) while len(self) > self._length: del self[list(self.keys())[0]]
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)
class Node(QtCore.QObject): """ Node represents the basic processing unit of a flowchart. A Node subclass implements at least: 1) A list of input / ouptut terminals and their properties 2) a process() function which takes the names of input terminals as keyword arguments and returns a dict with the names of output terminals as keys. A flowchart thus consists of multiple instances of Node subclasses, each of which is connected to other by wires between their terminals. A flowchart is, itself, also a special subclass of Node. This allows Nodes within the flowchart to connect to the input/output nodes of the flowchart itself. Optionally, a node class can implement the ctrlWidget() method, which must return a QWidget (usually containing other widgets) that will be displayed in the flowchart control panel. Some nodes implement fairly complex control widgets, but most nodes follow a simple form-like pattern: a list of parameter names and a single value (represented as spin box, check box, etc..) for each parameter. To make this easier, the CtrlNode subclass allows you to instead define a simple data structure that CtrlNode will use to automatically generate the control widget. """ sigOutputChanged = QtCore.Signal(object) # self sigClosed = QtCore.Signal(object) sigRenamed = QtCore.Signal(object, object) sigTerminalRenamed = QtCore.Signal(object, object) # term, oldName sigTerminalAdded = QtCore.Signal(object, object) # self, term sigTerminalRemoved = QtCore.Signal(object, object) # self, term 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 nextTerminalName(self, name): """Return an unused terminal name""" name2 = name i = 1 while name2 in self.terminals: name2 = "%s.%d" % (name, i) i += 1 return name2 def addInput(self, name="Input", **args): """Add a new input terminal to this Node with the given name. Extra keyword arguments are passed to Terminal.__init__. This is a convenience function that just calls addTerminal(io='in', ...)""" #print "Node.addInput called." return self.addTerminal(name, io='in', **args) def addOutput(self, name="Output", **args): """Add a new output terminal to this Node with the given name. Extra keyword arguments are passed to Terminal.__init__. This is a convenience function that just calls addTerminal(io='out', ...)""" return self.addTerminal(name, io='out', **args) def removeTerminal(self, term): """Remove the specified terminal from this Node. May specify either the terminal's name or the terminal itself. Causes sigTerminalRemoved to be emitted.""" if isinstance(term, Terminal): name = term.name() else: name = term term = self.terminals[name] #print "remove", name #term.disconnectAll() term.close() del self.terminals[name] if name in self._inputs: del self._inputs[name] if name in self._outputs: del self._outputs[name] self.graphicsItem().updateTerminals() self.sigTerminalRemoved.emit(self, term) def terminalRenamed(self, term, oldName): """Called after a terminal has been renamed Causes sigTerminalRenamed to be emitted.""" newName = term.name() for d in [self.terminals, self._inputs, self._outputs]: if oldName not in d: continue d[newName] = d[oldName] del d[oldName] self.graphicsItem().updateTerminals() self.sigTerminalRenamed.emit(term, oldName) def addTerminal(self, name, **opts): """Add a new terminal to this Node with the given name. Extra keyword arguments are passed to Terminal.__init__. Causes sigTerminalAdded to be emitted.""" name = self.nextTerminalName(name) term = Terminal(self, name, **opts) self.terminals[name] = term if term.isInput(): self._inputs[name] = term elif term.isOutput(): self._outputs[name] = term self.graphicsItem().updateTerminals() self.sigTerminalAdded.emit(self, term) return term def inputs(self): """Return dict of all input terminals. Warning: do not modify.""" return self._inputs def outputs(self): """Return dict of all output terminals. Warning: do not modify.""" return self._outputs def process(self, **kargs): """Process data through this node. This method is called any time the flowchart wants the node to process data. It will be called with one keyword argument corresponding to each input terminal, and must return a dict mapping the name of each output terminal to its new value. This method is also called with a 'display' keyword argument, which indicates whether the node should update its display (if it implements any) while processing this data. This is primarily used to disable expensive display operations during batch processing. """ return {} def graphicsItem(self): """Return the GraphicsItem for this node. Subclasses may re-implement this method to customize their appearance in the flowchart.""" if self._graphicsItem is None: self._graphicsItem = NodeGraphicsItem(self) return self._graphicsItem ## this is just bad planning. Causes too many bugs. def __getattr__(self, attr): """Return the terminal with the given name""" if attr not in self.terminals: raise AttributeError(attr) else: import traceback traceback.print_stack() print( "Warning: use of node.terminalName is deprecated; use node['terminalName'] instead." ) return self.terminals[attr] def __getitem__(self, item): #return getattr(self, item) """Return the terminal with the given name""" if item not in self.terminals: raise KeyError(item) else: return self.terminals[item] def name(self): """Return the name of this node.""" return self._name def rename(self, name): """Rename this node. This will cause sigRenamed to be emitted.""" oldName = self._name self._name = name #self.emit(QtCore.SIGNAL('renamed'), self, oldName) self.sigRenamed.emit(self, oldName) def dependentNodes(self): """Return the list of nodes which provide direct input to this node""" nodes = set() for t in self.inputs().values(): nodes |= set([i.node() for i in t.inputTerminals()]) return nodes #return set([t.inputTerminals().node() for t in self.listInputs().itervalues()]) def __repr__(self): return "<Node %s @%x>" % (self.name(), id(self)) def ctrlWidget(self): """Return this Node's control widget. By default, Nodes have no control widget. Subclasses may reimplement this method to provide a custom widget. This method is called by Flowcharts when they are constructing their Node list.""" return None def bypass(self, byp): """Set whether this node should be bypassed. When bypassed, a Node's process() method is never called. In some cases, data is automatically copied directly from specific input nodes to output nodes instead (see the bypass argument to Terminal.__init__). This is usually called when the user disables a node from the flowchart control panel. """ self._bypass = byp if self.bypassButton is not None: self.bypassButton.setChecked(byp) self.update() def isBypassed(self): """Return True if this Node is currently bypassed.""" return self._bypass def setInput(self, **args): """Set the values on input terminals. For most nodes, this will happen automatically through Terminal.inputChanged. This is normally only used for nodes with no connected inputs.""" changed = False for k, v in args.items(): term = self._inputs[k] oldVal = term.value() if not eq(oldVal, v): changed = True term.setValue(v, process=False) if changed and '_updatesHandled_' not in args: self.update() def inputValues(self): """Return a dict of all input values currently assigned to this node.""" vals = {} for n, t in self.inputs().items(): vals[n] = t.value() return vals def outputValues(self): """Return a dict of all output values currently generated by this node.""" vals = {} for n, t in self.outputs().items(): vals[n] = t.value() return vals def connected(self, localTerm, remoteTerm): """Called whenever one of this node's terminals is connected elsewhere.""" pass def disconnected(self, localTerm, remoteTerm): """Called whenever one of this node's terminals is disconnected from another.""" pass def update(self, signal=True): """Collect all input values, attempt to process new output values, and propagate downstream. Subclasses should call update() whenever thir internal state has changed (such as when the user interacts with the Node's control widget). Update is automatically called when the inputs to the node are changed. """ vals = self.inputValues() #print " inputs:", vals try: if self.isBypassed(): out = self.processBypassed(vals) else: out = self.process(**strDict(vals)) #print " output:", out if out is not None: if signal: self.setOutput(**out) else: self.setOutputNoSignal(**out) for n, t in self.inputs().items(): t.setValueAcceptable(True) self.clearException() except: #printExc( "Exception while processing %s:" % self.name()) for n, t in self.outputs().items(): t.setValue(None) self.setException(sys.exc_info()) if signal: #self.emit(QtCore.SIGNAL('outputChanged'), self) ## triggers flowchart to propagate new data self.sigOutputChanged.emit( self) ## triggers flowchart to propagate new data def processBypassed(self, args): """Called when the flowchart would normally call Node.process, but this node is currently bypassed. The default implementation looks for output terminals with a bypass connection and returns the corresponding values. Most Node subclasses will _not_ need to reimplement this method.""" result = {} for term in list(self.outputs().values()): byp = term.bypassValue() if byp is None: result[term.name()] = None else: result[term.name()] = args.get(byp, None) return result def setOutput(self, **vals): self.setOutputNoSignal(**vals) #self.emit(QtCore.SIGNAL('outputChanged'), self) ## triggers flowchart to propagate new data self.sigOutputChanged.emit( self) ## triggers flowchart to propagate new data def setOutputNoSignal(self, **vals): for k, v in vals.items(): term = self.outputs()[k] term.setValue(v) #targets = term.connections() #for t in targets: ## propagate downstream #if t is term: #continue #t.inputChanged(term) term.setValueAcceptable(True) def setException(self, exc): self.exception = exc self.recolor() def clearException(self): self.setException(None) def recolor(self): if self.exception is None: self.graphicsItem().setPen(QtGui.QPen(QtGui.QColor(0, 0, 0))) else: self.graphicsItem().setPen(QtGui.QPen(QtGui.QColor(150, 0, 0), 3)) def saveState(self): """Return a dictionary representing the current state of this node (excluding input / output values). This is used for saving/reloading flowcharts. The default implementation returns this Node's position, bypass state, and information about each of its terminals. Subclasses may want to extend this method, adding extra keys to the returned dict.""" pos = self.graphicsItem().pos() state = {'pos': (pos.x(), pos.y()), 'bypass': self.isBypassed()} termsEditable = self._allowAddInput | self._allowAddOutput for term in self._inputs.values() + self._outputs.values(): termsEditable |= term._renamable | term._removable | term._multiable if termsEditable: state['terminals'] = self.saveTerminals() return state def restoreState(self, state): """Restore the state of this node from a structure previously generated by saveState(). """ pos = state.get('pos', (0, 0)) self.graphicsItem().setPos(*pos) self.bypass(state.get('bypass', False)) if 'terminals' in state: self.restoreTerminals(state['terminals']) def saveTerminals(self): terms = OrderedDict() for n, t in self.terminals.items(): terms[n] = (t.saveState()) return terms def restoreTerminals(self, state): for name in list(self.terminals.keys()): if name not in state: self.removeTerminal(name) for name, opts in state.items(): if name in self.terminals: term = self[name] term.setOpts(**opts) continue try: opts = strDict(opts) self.addTerminal(name, **opts) except: printExc("Error restoring terminal %s (%s):" % (str(name), str(opts))) def clearTerminals(self): for t in self.terminals.values(): t.close() self.terminals = OrderedDict() self._inputs = OrderedDict() self._outputs = OrderedDict() def close(self): """Cleans up after the node--removes terminals, graphicsItem, widget""" self.disconnectAll() self.clearTerminals() item = self.graphicsItem() if item.scene() is not None: item.scene().removeItem(item) self._graphicsItem = None w = self.ctrlWidget() if w is not None: w.setParent(None) #self.emit(QtCore.SIGNAL('closed'), self) self.sigClosed.emit(self) def disconnectAll(self): for t in self.terminals.values(): t.disconnectAll()
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)
def __getitem__(self, item): val = OrderedDict.__getitem__(self, item) del self[item] self[item] = val ## promote this key return val
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'), ])
def setFields(self, fields): self.fields = OrderedDict(fields) names = self.fieldNames() self.setAddList(names)
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)
# -*- 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 saveTerminals(self): terms = OrderedDict() for n, t in self.terminals.items(): terms[n] = (t.saveState()) return terms
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 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
def __init__(self, length): self._length = length OrderedDict.__init__(self)
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'), ])
def __setitem__(self, item, val): self.pop(item, None) # make sure item is added to end OrderedDict.__setitem__(self, item, val) while len(self) > self._length: del self[self.keys()[0]]