コード例 #1
0
ファイル: ColorMapWidget.py プロジェクト: 3rdcycle/pyqtgraph
 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'),
         ])
コード例 #2
0
 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)
コード例 #3
0
    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)
コード例 #4
0
    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'),
            ])
コード例 #5
0
ファイル: Node.py プロジェクト: initbrain/intelwiz
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()
コード例 #6
0
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()
コード例 #7
0
ファイル: Node.py プロジェクト: slac-lcls/ami
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