def execute(self, progress):
     self.alg = ModelerUtils.getAlgorithm(self.description["algname"]).getCopy()
     for name, value in self.description["parameters"].iteritems():
         self.alg.setParameterValue(name, value)
     for name, value in self.description["outputs"].iteritems():
         self.alg.setOutputValue(name, value)
     self.alg.execute(progress)
     self.outputs = self.alg.outputs
Example #2
0
 def checkBeforeOpeningParametersDialog(self):
     for alg in self.algs.values():
         algInstance = ModelerUtils.getAlgorithm(alg.consoleName)
         if algInstance is None:
             return (
                 "The model you are trying to run contains an algorithm that is not available: <i>%s</i>"
                 % alg.consoleName
             )
 def execute(self, progress):
     self.alg = ModelerUtils.getAlgorithm(
         self.description["algname"]).getCopy()
     for name, value in self.description["parameters"].iteritems():
         self.alg.setParameterValue(name, value)
     for name, value in self.description["outputs"].iteritems():
         self.alg.setOutputValue(name, value)
     self.alg.execute(progress)
     self.outputs = self.alg.outputs
 def addAlgorithm(self):
     item = self.algorithmTree.currentItem()
     if isinstance(item, TreeAlgorithmItem):
         alg = ModelerUtils.getAlgorithm(item.alg.commandLineName())
         alg = alg.getCopy()#copy.deepcopy(alg)
         
         # create a tab for this algorithm
         stepDialog = StepDialog(alg, self)      
         self.canvasTabWidget.addTab(stepDialog, alg.name)
         
         # add this step to the workflow 
         self.workflow.addStep(alg, stepDialog.getMode(), stepDialog.getInstructions())
Example #5
0
 def _dropEvent(event):
     if event.mimeData().hasText():
         text = event.mimeData().text()
         if text in ModelerParameterDefinitionDialog.paramTypes:
             self.addInputOfType(text, event.pos())
         else:
             alg = ModelerUtils.getAlgorithm(text)
             if alg is not None:
                 self._addAlgorithm(alg.getCopy(), event.pos())
         event.accept()
     else:
         event.ignore()
Example #6
0
 def _dropEvent(event):
     if event.mimeData().hasText():
         text = event.mimeData().text()
         if text in ModelerParameterDefinitionDialog.paramTypes:
             self.addInputOfType(text, event.pos())
         else:
             alg = ModelerUtils.getAlgorithm(text)
             if alg is not None:
                 self._addAlgorithm(alg.getCopy(), event.pos())
         event.accept()
     else:
         event.ignore()
Example #7
0
 def addAlgorithm(self):
     item = self.algorithmTree.currentItem()
     if isinstance(item, TreeAlgorithmItem):
         alg = ModelerUtils.getAlgorithm(item.alg.commandLineName())
         self._addAlgorithm(alg.getCopy())
Example #8
0
    def openWorkflow(self, filename):
        self._steps = list()
        self.descriptionFile = filename
        instructions = False
        try:
            for line in fileinput.input(filename, openhook = fileinput.hook_encoded("utf-8")):
                line= line.rstrip()
                
                # comment line
                if line.startswith("#"):
                    pass
                
                if line.startswith(".NAME:"):
                    self.name = line[len(".NAME:"):]
                    
                elif line.startswith(".GROUP:"):
                    self.group = line[len(".GROUP:"):]
                    
                elif line.startswith(".ALGORITHM:"):
                    alg = ModelerUtils.getAlgorithm(line[len(".ALGORITHM:"):])
                    if alg:
                        alg = alg.getCopy()
                        self.addStep(alg, NORMAL_MODE, '')
                    else:
                        raise(WrongWorkflowException())
                    
                elif line.startswith(".MODE:"):
                    if line[len(".MODE:"):] == NORMAL_MODE:
                        self._steps[-1]['mode'] = NORMAL_MODE
                    elif line[len(".MODE:"):] == BATCH_MODE:
                        self._steps[-1]['mode'] = BATCH_MODE
                    else:
                        raise(WrongWorkflowException())  
                
                elif line.startswith(".PARAMETERS:"):
                    try:
                        params = json.loads(line[len(".PARAMETERS:"):])
                    except:
                        pass
                    else:
                        if type(params) == dict:
                            self._steps[-1]['parameters'] = params
                            self.setStepParameters(self._steps[-1])
                        else:
                            raise(WrongWorkflowException())
                      
                elif line.startswith(".INSTRUCTIONS"):
                    instructions = line[len(".INSTRUCTIONS:"):]+"\n"
                    self._steps[-1]['instructions'] = instructions
                    instructions = True
                
                elif instructions:
                    if line == "!INSTRUCTIONS":
                        instructions = False
                    elif line == "":
                        self._steps[-1]['instructions'] +="\n"
                    else:
                        self._steps[-1]['instructions'] +=line+"\n"

        except WrongWorkflowException:
            msg = "Error on line number "+unicode(fileinput.filelineno())+": "+line+"\n"
            fileinput.close()
            raise WrongWorkflowException(msg)
        except Exception, e:
            fileinput.close()
            raise e
Example #9
0
 def algorithm(self):
     if self._algInstance is None:
         self._algInstance = ModelerUtils.getAlgorithm(self.consoleName).getCopy();
     return self._algInstance
Example #10
0
    def fromOldFormatFile(filename):
        def _tr(s):
            return QtCore.QCoreApplication.translate('ModelerAlgorithm', s)
        hardcodedValues = {}
        modelParameters = []
        modelAlgs = []
        model = ModelerAlgorithm()
        model.descriptionFile = filename
        lines = codecs.open(filename, 'r', encoding='utf-8')
        line = lines.readline().strip('\n').strip('\r')
        try:
            while line != '':
                if line.startswith('PARAMETER:'):
                    paramLine = line[len('PARAMETER:'):]
                    param = getParameterFromString(paramLine)
                    if param:
                        pass
                    else:
                        raise WrongModelException(
                            _tr('Error in parameter line: %s', 'ModelerAlgorithm') % line)
                    line = lines.readline().strip('\n')
                    tokens = line.split(',')
                    model.addParameter(ModelerParameter(param, QtCore.QPointF(
                                            float(tokens[0]), float(tokens[1]))))
                    modelParameters.append(param.name)
                elif line.startswith('VALUE:'):
                    valueLine = line[len('VALUE:'):]
                    tokens = valueLine.split('===')
                    name = tokens[0]
                    value = tokens[1].replace(ModelerAlgorithm.LINE_BREAK_STRING, '\n')
                    hardcodedValues[name] = value
                elif line.startswith('NAME:'):
                    model.name = line[len('NAME:'):]
                elif line.startswith('GROUP:'):
                    model.group = line[len('GROUP:'):]
                elif line.startswith('ALGORITHM:'):
                    algLine = line[len('ALGORITHM:'):]
                    alg = ModelerUtils.getAlgorithm(algLine)
                    if alg is not None:
                        modelAlg = Algorithm(alg.commandLineName())
                        modelAlg.description = alg.name
                        posline = lines.readline().strip('\n').strip('\r')
                        tokens = posline.split(',')
                        modelAlg.pos = QtCore.QPointF(float(tokens[0]), float(tokens[1]))
                        dependenceline = lines.readline().strip('\n').strip('\r') #unused
                        for param in alg.parameters:
                            if not param.hidden:
                                line = lines.readline().strip('\n').strip('\r')
                                if line == str(None):
                                    modelAlg.params[param.name]  = None
                                else:
                                    tokens = line.split('|')
                                    algIdx = int(tokens[0])
                                    if algIdx == -1:
                                        if tokens[1] in modelParameters:
                                            modelAlg.params[param.name] = ValueFromInput(tokens[1])
                                        else:
                                            modelAlg.params[param.name] = hardcodedValues[tokens[1]]
                                    else:
                                        modelAlg.params[param.name] = ValueFromOutput(algIdx, tokens[1])

                        for out in alg.outputs:
                            if not out.hidden:
                                line = lines.readline().strip('\n').strip('\r')
                                if str(None) != line:
                                    if '|' in line:
                                        tokens = line.split('|')
                                        name = tokens[0]
                                        tokens = tokens[1].split(',')
                                        pos = QtCore.QPointF(
                                                float(tokens[0]), float(tokens[1]))
                                    else:
                                        name = line
                                        pos = None
                                    modelerOutput = ModelerOutput(name)
                                    modelerOutput.pos = pos
                                    modelAlg.outputs[out.name] = modelerOutput

                        model.addAlgorithm(modelAlg)
                        modelAlgs.append(modelAlg.name)
                    else:
                        raise WrongModelException(
                            _tr('Error in algorithm name: %s', ) % algLine)
                line = lines.readline().strip('\n').strip('\r')
            for modelAlg in model.algs.values():
                for name, value in modelAlg.params.iteritems():
                    if isinstance(value, ValueFromOutput):
                        value.alg = modelAlgs[value.alg]
            return model
        except Exception, e:
            if isinstance(e, WrongModelException):
                raise e
            else:
                raise WrongModelException(_tr('Error in model definition line: ') + '%s\n%s' % (line.strip(), traceback.format_exc()))
Example #11
0
    def openModel(self, filename):
        self.algPos = []
        self.paramPos = []
        self.outputOutputs = []
        self.algs = []
        self.algParameters = []
        self.algOutputs = []
        self.paramValues = {}
        self.dependencies = []

        self.descriptionFile = filename
        lines = codecs.open(filename, "r", encoding='utf-8')
        line = lines.readline().strip("\n").strip("\r")
        iAlg = 0
        try:
            while line != "":
                if line.startswith("PARAMETER:"):
                    paramLine = line[len("PARAMETER:"):]
                    param = ParameterFactory.getFromString(paramLine)
                    if param:
                        self.parameters.append(param)
                    else:
                        raise WrongModelException("Error in parameter line: " +
                                                  line)
                    line = lines.readline().strip("\n")
                    tokens = line.split(",")
                    self.paramPos.append(
                        QtCore.QPointF(float(tokens[0]), float(tokens[1])))
                elif line.startswith("VALUE:"):
                    valueLine = line[len("VALUE:"):]
                    tokens = valueLine.split("===")
                    self.paramValues[tokens[0]] = tokens[1].replace(
                        ModelerAlgorithm.LINE_BREAK_STRING, '\n')
                elif line.startswith("NAME:"):
                    self.name = line[len("NAME:"):]
                elif line.startswith("GROUP:"):
                    self.group = line[len("GROUP:"):]
                elif line.startswith("ALGORITHM:"):
                    algParams = {}
                    algOutputs = {}
                    algLine = line[len("ALGORITHM:"):]
                    alg = ModelerUtils.getAlgorithm(algLine)
                    if alg is not None:
                        posline = lines.readline().strip("\n").strip("\r")
                        tokens = posline.split(",")
                        self.algPos.append(
                            QtCore.QPointF(float(tokens[0]), float(tokens[1])))
                        self.algs.append(alg)
                        dependenceline = lines.readline().strip("\n").strip(
                            "\r")
                        dependencies = []
                        if dependenceline != str(None):
                            for index in dependenceline.split(","):
                                try:
                                    dependencies.append(int(index))
                                except:
                                    pass  #a quick fix while I figure out how to solve problems when parsing this
                        for param in alg.parameters:
                            line = lines.readline().strip("\n").strip("\r")
                            if line == str(None):
                                algParams[param.name] = None
                            else:
                                tokens = line.split("|")
                                algParams[param.name] = AlgorithmAndParameter(
                                    int(tokens[0]), tokens[1])
                        outputPos = {}
                        for out in alg.outputs:
                            line = lines.readline().strip("\n").strip("\r")
                            if str(None) != line:
                                if "|" in line:
                                    tokens = line.split("|")
                                    name = tokens[0]
                                    tokens = tokens[1].split(",")
                                    outputPos[out.name] = QtCore.QPointF(
                                        float(tokens[0]), float(tokens[1]))
                                else:
                                    name = line
                                    outputPos[out.name] = None
                                algOutputs[out.name] = name
                                #we add the output to the algorithm, with a name indicating where it comes from
                                #that guarantees that the name is unique
                                output = copy.deepcopy(out)
                                output.description = name
                                output.name = self.getSafeNameForOutput(
                                    iAlg, output)
                                self.addOutput(output)
                            else:
                                algOutputs[out.name] = None
                        self.outputPos.append(outputPos)
                        self.algOutputs.append(algOutputs)
                        self.algParameters.append(algParams)
                        self.dependencies.append(dependencies)
                        iAlg += 1
                    else:
                        raise WrongModelException("Error in algorithm name: " +
                                                  algLine)
                line = lines.readline().strip("\n").strip("\r")
        except Exception, e:
            if isinstance(e, WrongModelException):
                raise e
            else:
                raise WrongModelException("Error in model definition line:" +
                                          line.strip() + " : " +
                                          traceback.format_exc())
Example #12
0
    def fromOldFormatFile(filename):
        def _tr(s):
            return QCoreApplication.translate("ModelerAlgorithm", s)

        hardcodedValues = {}
        modelParameters = []
        modelAlgs = []
        model = ModelerAlgorithm()
        model.descriptionFile = filename
        lines = codecs.open(filename, "r", encoding="utf-8")
        line = lines.readline().strip("\n").strip("\r")
        try:
            while line != "":
                if line.startswith("PARAMETER:"):
                    paramLine = line[len("PARAMETER:") :]
                    param = getParameterFromString(paramLine)
                    if param:
                        pass
                    else:
                        raise WrongModelException(_tr("Error in parameter line: %s", "ModelerAlgorithm") % line)
                    line = lines.readline().strip("\n")
                    tokens = line.split(",")
                    model.addParameter(ModelerParameter(param, QPointF(float(tokens[0]), float(tokens[1]))))
                    modelParameters.append(param.name)
                elif line.startswith("VALUE:"):
                    valueLine = line[len("VALUE:") :]
                    tokens = valueLine.split("===")
                    name = tokens[0]
                    value = tokens[1].replace(ModelerAlgorithm.LINE_BREAK_STRING, "\n")
                    hardcodedValues[name] = value
                elif line.startswith("NAME:"):
                    model.name = line[len("NAME:") :]
                elif line.startswith("GROUP:"):
                    model.group = line[len("GROUP:") :]
                elif line.startswith("ALGORITHM:"):
                    algLine = line[len("ALGORITHM:") :]
                    alg = ModelerUtils.getAlgorithm(algLine)
                    if alg is not None:
                        modelAlg = Algorithm(alg.commandLineName())
                        modelAlg.description = alg.name
                        posline = lines.readline().strip("\n").strip("\r")
                        tokens = posline.split(",")
                        modelAlg.pos = QPointF(float(tokens[0]), float(tokens[1]))
                        # dependenceline = lines.readline().strip('\n').strip('\r')
                        for param in alg.parameters:
                            if not param.hidden:
                                line = lines.readline().strip("\n").strip("\r")
                                if line == unicode(None):
                                    modelAlg.params[param.name] = None
                                else:
                                    tokens = line.split("|")
                                    try:
                                        algIdx = int(tokens[0])
                                    except:
                                        raise WrongModelException(
                                            _tr(
                                                "Number of parameters in the "
                                                "{} algorithm does not match "
                                                "current Processing "
                                                "implementation".format(alg.name)
                                            )
                                        )
                                    if algIdx == -1:
                                        if tokens[1] in modelParameters:
                                            modelAlg.params[param.name] = ValueFromInput(tokens[1])
                                        else:
                                            modelAlg.params[param.name] = hardcodedValues[tokens[1]]
                                    else:
                                        modelAlg.params[param.name] = ValueFromOutput(algIdx, tokens[1])

                        for out in alg.outputs:
                            if not out.hidden:
                                line = lines.readline().strip("\n").strip("\r")
                                if unicode(None) != line:
                                    if "|" in line:
                                        tokens = line.split("|")
                                        name = tokens[0]
                                        tokens = tokens[1].split(",")
                                        pos = QPointF(float(tokens[0]), float(tokens[1]))
                                    else:
                                        name = line
                                        pos = None
                                    modelerOutput = ModelerOutput(name)
                                    modelerOutput.pos = pos
                                    modelAlg.outputs[out.name] = modelerOutput

                        model.addAlgorithm(modelAlg)
                        modelAlgs.append(modelAlg.name)
                    else:
                        raise WrongModelException(_tr("Error in algorithm name: %s") % algLine)
                line = lines.readline().strip("\n").strip("\r")
            for modelAlg in model.algs.values():
                for name, value in modelAlg.params.iteritems():
                    if isinstance(value, ValueFromOutput):
                        value.alg = modelAlgs[value.alg]
            return model
        except Exception as e:
            if isinstance(e, WrongModelException):
                raise e
            else:
                raise WrongModelException(
                    _tr("Error in model definition line: ") + "%s\n%s" % (line.strip(), traceback.format_exc())
                )
Example #13
0
    def openModel(self, filename):
        self.algPos = []
        self.paramPos = []
        self.outputOutputs = []
        self.algs = []
        self.algParameters = []
        self.algOutputs = []
        self.paramValues = {}
        self.dependencies = []

        self.descriptionFile = filename
        lines = codecs.open(filename, "r", encoding='utf-8')
        line = lines.readline().strip("\n").strip("\r")
        iAlg = 0
        try:
            while line != "":
                if line.startswith("PARAMETER:"):
                    paramLine = line[len("PARAMETER:"):]
                    param = ParameterFactory.getFromString(paramLine)
                    if param:
                        self.parameters.append(param)
                    else:
                        raise WrongModelException("Error in parameter line: " + line)
                    line = lines.readline().strip("\n")
                    tokens = line.split(",")
                    self.paramPos.append(QtCore.QPointF(float(tokens[0]), float(tokens[1])))
                elif line.startswith("VALUE:"):
                    valueLine = line[len("VALUE:"):]
                    tokens = valueLine.split("===")
                    self.paramValues[tokens[0]] = tokens[1].replace(ModelerAlgorithm.LINE_BREAK_STRING, '\n')
                elif line.startswith("NAME:"):
                    self.name = line[len("NAME:"):]
                elif line.startswith("GROUP:"):
                    self.group = line[len("GROUP:"):]
                    if self.group == "[Test models]":
                        self.showInModeler = False
                        self.showInToolbox = False
                elif line.startswith("ALGORITHM:"):
                    algParams={}
                    algOutputs={}
                    algLine = line[len("ALGORITHM:"):]
                    alg = ModelerUtils.getAlgorithm(algLine)
                    if alg is not None:
                        posline = lines.readline().strip("\n").strip("\r")
                        tokens = posline.split(",")
                        self.algPos.append(QtCore.QPointF(float(tokens[0]), float(tokens[1])))
                        self.algs.append(alg)
                        dependenceline = lines.readline().strip("\n").strip("\r")
                        dependencies = [];
                        if dependenceline != str(None):
                            for index in dependenceline.split(","):
                                try:
                                    dependencies.append(int(index))
                                except:
                                    pass #a quick fix while I figure out how to solve problems when parsing this
                        for param in alg.parameters:
                            line = lines.readline().strip("\n").strip("\r")
                            if line==str(None):
                                algParams[param.name] = None
                            else:
                                tokens = line.split("|")
                                algParams[param.name] = AlgorithmAndParameter(int(tokens[0]), tokens[1])
                        outputPos = {}
                        for out in alg.outputs:
                            line = lines.readline().strip("\n").strip("\r")
                            if str(None)!=line:
                                if "|" in line:
                                    tokens = line.split("|")
                                    name = tokens[0]
                                    tokens = tokens[1].split(",")
                                    outputPos[out.name] = QtCore.QPointF(float(tokens[0]), float(tokens[1]))
                                else:
                                    name = line
                                    outputPos[out.name] = None
                                algOutputs[out.name] = name
                                #we add the output to the algorithm, with a name indicating where it comes from
                                #that guarantees that the name is unique
                                output = copy.deepcopy(out)
                                output.description = name
                                output.name = self.getSafeNameForOutput(iAlg, output)
                                self.addOutput(output)
                            else:
                                algOutputs[out.name] = None
                        self.outputPos.append(outputPos)
                        self.algOutputs.append(algOutputs)
                        self.algParameters.append(algParams)
                        self.dependencies.append(dependencies)
                        iAlg += 1
                    else:
                        raise WrongModelException("Error in algorithm name: " + algLine)
                line = lines.readline().strip("\n").strip("\r")
        except Exception, e:
            if isinstance (e, WrongModelException):
                raise e
            else:
                raise WrongModelException("Error in model definition line:"  + line.strip() + " : " + traceback.format_exc())
Example #14
0
 def algorithm(self):
     if self._algInstance is None:
         self._algInstance = ModelerUtils.getAlgorithm(
             self.consoleName).getCopy()
     return self._algInstance
Example #15
0
    def fromOldFormatFile(filename):
        hardcodedValues = {}
        modelParameters = []
        modelAlgs = []
        model = ModelerAlgorithm()
        model.descriptionFile = filename
        lines = codecs.open(filename, 'r', encoding='utf-8')
        line = lines.readline().strip('\n').strip('\r')
        try:
            while line != '':
                if line.startswith('PARAMETER:'):
                    paramLine = line[len('PARAMETER:'):]
                    param = getParameterFromString(paramLine)
                    if param:
                        pass
                    else:
                        raise WrongModelException('Error in parameter line: ' +
                                                  line)
                    line = lines.readline().strip('\n')
                    tokens = line.split(',')
                    model.addParameter(
                        ModelerParameter(
                            param,
                            QtCore.QPointF(float(tokens[0]),
                                           float(tokens[1]))))
                    modelParameters.append(param.name)
                elif line.startswith('VALUE:'):
                    valueLine = line[len('VALUE:'):]
                    tokens = valueLine.split('===')
                    name = tokens[0]
                    value = tokens[1].replace(
                        ModelerAlgorithm.LINE_BREAK_STRING, '\n')
                    hardcodedValues[name] = value
                elif line.startswith('NAME:'):
                    model.name = line[len('NAME:'):]
                elif line.startswith('GROUP:'):
                    model.group = line[len('GROUP:'):]
                elif line.startswith('ALGORITHM:'):
                    algLine = line[len('ALGORITHM:'):]
                    alg = ModelerUtils.getAlgorithm(algLine)
                    if alg is not None:
                        modelAlg = Algorithm(alg.commandLineName())
                        modelAlg.description = alg.name
                        posline = lines.readline().strip('\n').strip('\r')
                        tokens = posline.split(',')
                        modelAlg.pos = QtCore.QPointF(float(tokens[0]),
                                                      float(tokens[1]))
                        dependenceline = lines.readline().strip('\n').strip(
                            '\r')  #unused
                        for param in alg.parameters:
                            if not param.hidden:
                                line = lines.readline().strip('\n').strip('\r')
                                if line == str(None):
                                    modelAlg.params[param.name] = None
                                else:
                                    tokens = line.split('|')
                                    algIdx = int(tokens[0])
                                    if algIdx == -1:
                                        if tokens[1] in modelParameters:
                                            modelAlg.params[
                                                param.name] = ValueFromInput(
                                                    tokens[1])
                                        else:
                                            modelAlg.params[
                                                param.name] = hardcodedValues[
                                                    tokens[1]]
                                    else:
                                        modelAlg.params[
                                            param.name] = ValueFromOutput(
                                                algIdx, tokens[1])

                        for out in alg.outputs:
                            if not out.hidden:
                                line = lines.readline().strip('\n').strip('\r')
                                if str(None) != line:
                                    if '|' in line:
                                        tokens = line.split('|')
                                        name = tokens[0]
                                        tokens = tokens[1].split(',')
                                        pos = QtCore.QPointF(
                                            float(tokens[0]), float(tokens[1]))
                                    else:
                                        name = line
                                        pos = None
                                    modelerOutput = ModelerOutput(name)
                                    modelerOutput.pos = pos
                                    modelAlg.outputs[out.name] = modelerOutput

                        model.addAlgorithm(modelAlg)
                        modelAlgs.append(modelAlg.name)
                    else:
                        raise WrongModelException('Error in algorithm name: ' +
                                                  algLine)
                line = lines.readline().strip('\n').strip('\r')
            for modelAlg in model.algs.values():
                for name, value in modelAlg.params.iteritems():
                    if isinstance(value, ValueFromOutput):
                        value.alg = modelAlgs[value.alg]
            return model
        except Exception, e:
            if isinstance(e, WrongModelException):
                raise e
            else:
                raise WrongModelException('Error in model definition line:' +
                                          line.strip() + ' : ' +
                                          traceback.format_exc())
Example #16
0
    def openModel(self, filename):
        self.algPos = []
        self.paramPos = []
        self.outputOutputs = []
        self.algs = []
        self.algParameters = []
        self.algOutputs = []
        self.paramValues = {}
        self.dependencies = []
        self.descriptionFile = filename
        lines = codecs.open(filename, 'r', encoding='utf-8')
        line = lines.readline().strip('\n').strip('\r')
        iAlg = 0
        try:
            while line != '':
                if line.startswith('PARAMETER:'):
                    paramLine = line[len('PARAMETER:'):]
                    param = ParameterFactory.getFromString(paramLine)
                    if param:
                        self.parameters.append(param)
                    else:
                        raise WrongModelException('Error in parameter line: '
                                + line)
                    line = lines.readline().strip('\n')
                    tokens = line.split(',')
                    self.paramPos.append(QtCore.QPointF(float(tokens[0]),
                            float(tokens[1])))
                elif line.startswith('VALUE:'):
                    valueLine = line[len('VALUE:'):]
                    tokens = valueLine.split('===')
                    self.paramValues[tokens[0]] = \
                        tokens[1].replace(ModelerAlgorithm.LINE_BREAK_STRING,
                            '\n')
                elif line.startswith('NAME:'):
                    self.name = line[len('NAME:'):]
                elif line.startswith('GROUP:'):
                    self.group = line[len('GROUP:'):]
                    if self.group == '[Test models]':
                        self.showInModeler = False
                        self.showInToolbox = False
                elif line.startswith('ALGORITHM:'):
                    algParams = {}
                    algOutputs = {}
                    algLine = line[len('ALGORITHM:'):]
                    alg = ModelerUtils.getAlgorithm(algLine)
                    if alg is not None:
                        posline = lines.readline().strip('\n').strip('\r')
                        tokens = posline.split(',')
                        self.algPos.append(QtCore.QPointF(float(tokens[0]),
                                float(tokens[1])))
                        self.algs.append(alg)
                        dependenceline = lines.readline().strip('\n'
                                ).strip('\r')
                        dependencies = []
                        if dependenceline != str(None):
                            for index in dependenceline.split(','):
                                try:
                                    dependencies.append(int(index))
                                except:
                                    # A quick fix while I figure out
                                    # how to solve problems when
                                    # parsing this
                                    pass
                        for param in alg.parameters:
                            if not param.hidden:
                                line = lines.readline().strip('\n').strip('\r')
                                if line == str(None):
                                    algParams[param.name] = None
                                else:
                                    tokens = line.split('|')
                                    algParams[param.name] = \
                                        AlgorithmAndParameter(int(tokens[0]),
                                            tokens[1])
                        outputPos = {}
                        for out in alg.outputs:
                            if not out.hidden:
                                line = lines.readline().strip('\n').strip('\r')
                                if str(None) != line:
                                    if '|' in line:
                                        tokens = line.split('|')
                                        name = tokens[0]
                                        tokens = tokens[1].split(',')
                                        outputPos[out.name] = QtCore.QPointF(
                                                float(tokens[0]), float(tokens[1]))
                                    else:
                                        name = line
                                        outputPos[out.name] = None
                                    algOutputs[out.name] = name

                                    # We add the output to the algorithm,
                                    # with a name indicating where it comes
                                    # from that guarantees that the name is
                                    # unique
                                    output = copy.deepcopy(out)
                                    output.description = name
                                    output.name = self.getSafeNameForOutput(iAlg,
                                            output)
                                    self.addOutput(output)
                                else:
                                    algOutputs[out.name] = None
                        self.outputPos.append(outputPos)
                        self.algOutputs.append(algOutputs)
                        self.algParameters.append(algParams)
                        self.dependencies.append(dependencies)
                        iAlg += 1
                    else:
                        raise WrongModelException('Error in algorithm name: '
                                + algLine)
                line = lines.readline().strip('\n').strip('\r')
        except Exception, e:
            if isinstance(e, WrongModelException):
                raise e
            else:
                raise WrongModelException('Error in model definition line:'
                        + line.strip() + ' : ' + traceback.format_exc())
Example #17
0
 def addAlgorithm(self):
     item = self.algorithmTree.currentItem()
     if isinstance(item, TreeAlgorithmItem):
         alg = ModelerUtils.getAlgorithm(item.alg.commandLineName())
         self._addAlgorithm(alg.getCopy())
Example #18
0
    def openModel(self, filename):
        self.algPos = []
        self.paramPos = []
        self.outputOutputs = []
        self.algs = []
        self.algParameters = []
        self.algOutputs = []
        self.paramValues = {}
        self.dependencies = []
        self.descriptionFile = filename
        lines = codecs.open(filename, 'r', encoding='utf-8')
        line = lines.readline().strip('\n').strip('\r')
        iAlg = 0
        try:
            while line != '':
                if line.startswith('PARAMETER:'):
                    paramLine = line[len('PARAMETER:'):]
                    param = ParameterFactory.getFromString(paramLine)
                    if param:
                        self.parameters.append(param)
                    else:
                        raise WrongModelException('Error in parameter line: ' +
                                                  line)
                    line = lines.readline().strip('\n')
                    tokens = line.split(',')
                    self.paramPos.append(
                        QtCore.QPointF(float(tokens[0]), float(tokens[1])))
                elif line.startswith('VALUE:'):
                    valueLine = line[len('VALUE:'):]
                    tokens = valueLine.split('===')
                    self.paramValues[tokens[0]] = \
                        tokens[1].replace(ModelerAlgorithm.LINE_BREAK_STRING,
                            '\n')
                elif line.startswith('NAME:'):
                    self.name = line[len('NAME:'):]
                elif line.startswith('GROUP:'):
                    self.group = line[len('GROUP:'):]
                    if self.group == '[Test models]':
                        self.showInModeler = False
                        self.showInToolbox = False
                elif line.startswith('ALGORITHM:'):
                    algParams = {}
                    algOutputs = {}
                    algLine = line[len('ALGORITHM:'):]
                    alg = ModelerUtils.getAlgorithm(algLine)
                    if alg is not None:
                        posline = lines.readline().strip('\n').strip('\r')
                        tokens = posline.split(',')
                        self.algPos.append(
                            QtCore.QPointF(float(tokens[0]), float(tokens[1])))
                        self.algs.append(alg)
                        dependenceline = lines.readline().strip('\n').strip(
                            '\r')
                        dependencies = []
                        if dependenceline != str(None):
                            for index in dependenceline.split(','):
                                try:
                                    dependencies.append(int(index))
                                except:
                                    # A quick fix while I figure out
                                    # how to solve problems when
                                    # parsing this
                                    pass
                        for param in alg.parameters:
                            line = lines.readline().strip('\n').strip('\r')
                            if line == str(None):
                                algParams[param.name] = None
                            else:
                                tokens = line.split('|')
                                algParams[param.name] = \
                                    AlgorithmAndParameter(int(tokens[0]),
                                        tokens[1])
                        outputPos = {}
                        for out in alg.outputs:
                            line = lines.readline().strip('\n').strip('\r')
                            if str(None) != line:
                                if '|' in line:
                                    tokens = line.split('|')
                                    name = tokens[0]
                                    tokens = tokens[1].split(',')
                                    outputPos[out.name] = QtCore.QPointF(
                                        float(tokens[0]), float(tokens[1]))
                                else:
                                    name = line
                                    outputPos[out.name] = None
                                algOutputs[out.name] = name

                                # We add the output to the algorithm,
                                # with a name indicating where it comes
                                # from that guarantees that the name is
                                # unique
                                output = copy.deepcopy(out)
                                output.description = name
                                output.name = self.getSafeNameForOutput(
                                    iAlg, output)
                                self.addOutput(output)
                            else:
                                algOutputs[out.name] = None
                        self.outputPos.append(outputPos)
                        self.algOutputs.append(algOutputs)
                        self.algParameters.append(algParams)
                        self.dependencies.append(dependencies)
                        iAlg += 1
                    else:
                        raise WrongModelException('Error in algorithm name: ' +
                                                  algLine)
                line = lines.readline().strip('\n').strip('\r')
        except Exception, e:
            if isinstance(e, WrongModelException):
                raise e
            else:
                raise WrongModelException('Error in model definition line:' +
                                          line.strip() + ' : ' +
                                          traceback.format_exc())
Example #19
0
 def checkBeforeOpeningParametersDialog(self):
     for alg in self.algs.values():
         algInstance = ModelerUtils.getAlgorithm(alg.consoleName)
         if algInstance is None:
             return "The model you are trying to run contains an algorithm that is not available: <i>%s</i>" % alg.consoleName