Esempio n. 1
0
 def __init__(self, name, **kw):
     """Object initialization."""
     self.call__init__(TaurusDevice, name, **kw)
     safedict = {}
     for s in self._symbols:
         if hasattr(self, s):
             safedict[s] = getattr(self, s)
     SafeEvaluator.__init__(self, safedict=safedict)
Esempio n. 2
0
 def __init__(self, name, **kw):
     """Object initialization."""
     self.call__init__(TaurusDevice, name, **kw)
     safedict = {}
     for s in self._symbols:
         if hasattr(self, s):
             safedict[s] = getattr(self, s)
     SafeEvaluator.__init__(self, safedict=safedict)
 def __init__(self, xmodel=None, id=None):
     Qt.QObject.__init__(self)
     TaurusBaseComponent.__init__(self, self.__class__.__name__)
     self._attrnamevalidator = ATTRNAMEVALIDATOR
     self.id = id
     self.sev = SafeEvaluator()
     self._referencedQAttrs = []
     self.value = None
     self._setExtendedModel(xmodel)
Esempio n. 4
0
 def onAddCurveButtonClicked(self):
     """ Emit a AddCurve signal with a rawdata dictionary as a parameter.
     The rawdata dictionary is prepared from the from the GUI's selection."""
     rawdata = {}
     if self.xRangeRB.isChecked():
         rawdata['x'] = numpy.arange(float(self.xFromLE.text()), float(
             self.xToLE.text()), float(self.xStepLE.text()))
     else:
         sev = SafeEvaluator()
         try:
             rawdata['x'] = sev.eval(str(self.xValuesLE.text()))
         except:
             Qt.QMessageBox.warning(
                 self, 'Invalid x values' 'Cannot interpret the x values.\n Use Python expressions like "[1, 3 , 67]" or "arange(100)")')
             return
     rawdata['f(x)'] = str(self.f_xLE.text())
     self.emit(Qt.SIGNAL("AddCurve"), rawdata)
Esempio n. 5
0
 def onAddCurveButtonClicked(self):
     """ Emit a AddCurve signal with a rawdata dictionary as a parameter.
     The rawdata dictionary is prepared from the from the GUI's selection."""
     rawdata = {}
     if self.xRangeRB.isChecked():
         rawdata["x"] = numpy.arange(
             float(self.xFromLE.text()), float(self.xToLE.text()), float(self.xStepLE.text())
         )
     else:
         sev = SafeEvaluator()
         try:
             rawdata["x"] = sev.eval(str(self.xValuesLE.text()))
         except:
             Qt.QMessageBox.warning(
                 self,
                 "Invalid x values"
                 'Cannot interpret the x values.\n Use Python expressions like "[1, 3 , 67]" or "arange(100)")',
             )
             return
     rawdata["f(x)"] = str(self.f_xLE.text())
     self.AddCurve.emit(rawdata)
class TaurusQAttribute(Qt.QObject, TaurusBaseComponent):
    '''A listener for taurus attributes.
    It stores the value in a numpy array and emits a
    dataChanged signal when the data has changed.
    '''
    pyVar_RegExp = re.compile(
        "[a-zA-Z_][a-zA-Z0-9_]*")  # regexp for a variable/method name (symbol)
    # regexp for references to qAttrs in extended models
    cref_RegExp = re.compile("\$\{(.+?)\}")

    def __init__(self, xmodel=None, id=None):
        Qt.QObject.__init__(self)
        TaurusBaseComponent.__init__(self, self.__class__.__name__)
        self._attrnamevalidator = ATTRNAMEVALIDATOR
        self.id = id
        self.sev = SafeEvaluator()
        self._referencedQAttrs = []
        self.value = None
        self._setExtendedModel(xmodel)

    def _setExtendedModel(self, xmodel):
        self._xmodel = xmodel
        if xmodel is None:
            self.value = None
            self._transformationString = None
            self.setModel('')
            return
        xmodel = str(xmodel)
        # for formulas
        if xmodel.startswith('='):
            trstring, ok = self.preProcessTransformation(xmodel[1:])
            if ok:
                self._transformationString = trstring
                self.applyTransformation()
            else:
                print "!!!!!!!!!!!!!", self._transformationString
                return
        # for tango attributes
        elif self._attrnamevalidator.isValid(xmodel):
            self.setModel(xmodel)
            self.fireEvent(None, None, None)  # fake event to force a reading
        else:
            self.warning('Unsupported extended model "%s". Skipping', xmodel)
#        #for nexus files
#        m = re.match(NEXUS_src,model)
#        if m is not None:
#            host,path,nxpath,slice = m.group(4,5,9,10)
#            #@todo:open file and check the data is accessible
#            return model, nxpath, getThemeIcon('x-office-spreadsheet'), True
#        #for ascii files
#        m = re.match(ASCII_src,model)
#        if m is not None:
#            host,path, = m.group(4,5)
#        #@todo: open and check the file
#        #If nothing matches...
#        return model, model, getThemeIcon('dialog-warning'), False

    def preProcessTransformation(self, trstring):
        """
        parses the transformation string and creates the necessary symbols for
        the evaluator. It also connects any referenced qAttrs so that the
        transformation gets re-evaluated if they change.
        :param trstring: (str) a string to be pre-processed

        :return: (tuple<str,bool>) a tuple containing the processed string
                 and a boolean indicating if the preprocessing was successful.
                 if ok==True, the string is ready to be evaluated
        """
        # disconnect previously referenced qAttrs and clean the list
        for c in self._referencedQAttrs:
            self.disconnect(c, Qt.SIGNAL("dataChanged"),
                            self.applyTransformation)
        self._referencedQAttrs = []

        # reset symbols
        self.sev.resetSafe()

        # Find references in the string, create qAttrs if needed, connect to
        # them and change the string to use the qAttr id
        trstring = re.sub(self.cref_RegExp, self.__Match2Id, trstring)

        safesymbols = self.sev.getSafe().keys()
        # validate the expression (look for missing symbols)
        for s in set(re.findall(self.pyVar_RegExp, trstring)):
            if s not in safesymbols:
                self.warning('Missing symbol "%s"' % s)
                return trstring, False
        return trstring, True

    def __Match2Id(self, match):
        """
        receives a re.match object for cref_RegExp. Returns the id of an
        existing qAttr corresponding to the match. The qAttr is created
        if it didn't previously exist.
        """
        return self.__createReference(match.groups()[0]).id

    def __createReference(self, ref):
        '''creates a (or gets an existing)qAttr and connects to it and adds
        its id to the safe evaluation symbols. It returns the qAttr.
        '''
        c = taurusQAttributeFactory.getQAttr(ref)
        self.connect(c, Qt.SIGNAL("dataChanged"), self.applyTransformation)
        self.sev.addSafe({c.id: c.value})
        self._referencedQAttrs.append(c)
        return c

    def applyTransformation(self):
        try:
            sender = self.sender()
            if isinstance(sender, TaurusQAttribute):
                self.sev.addSafe({sender.id: sender.value})
            self.value = self.sev.eval(self._transformationString)
            self.emit(Qt.SIGNAL("dataChanged"))
        except Exception, e:
            self.warning(
                "the function '%s' could not be evaluated. Reason: %s" %
                (self._transformationString, repr(e)))