def modelFromFile(filepath): """ Initiates a model from a filepath. :param filepath: (str) filepath for target file. :return: (QgsProcessingModelAlgorithm) model as a processing algorithm. """ alg = QgsProcessingModelAlgorithm() alg.fromFile(filepath) alg.initAlgorithm() return alg
def runModel(self, modelName=None): """ Executes chosen model, if possible. :param modelPath: (str) path to the model to be registered. """ if self.modelComboBox.currentIndex() < 1: return if not modelName or isinstance(modelName, bool): modelName = self.model() modelPath = self.modelPath() else: modelPath = os.path.join(self.defaultModelPath(), modelName) alg = QgsProcessingModelAlgorithm() if not self.modelExists(modelName): # if model was manually removed and combo box was not refreshed self.iface.messageBar().pushMessage( self.tr('Failed'), self.tr("model {model} seems to have been deleted.").format(model=modelName), level=Qgis.Critical, duration=5 ) return alg.fromFile(modelPath) alg.initAlgorithm() # as this tool assumes that every parameter is pre-set, only output shall # be passed on - ALL outputs from this tool is set to memory layers. param = {vl.name() : "memory:" for vl in alg.parameterDefinitions()} msg = self.tr("Would you like to run {model}").format(model=modelName) if self.options()["checkBeforeRunModel"] and not self.confirmAction(msg): return try: out = processing.run(alg, param) self.iface.messageBar().pushMessage( self.tr('Sucess'), self.tr("model {model} finished.").format(model=modelName), level=Qgis.Info, duration=5 ) QgsMessageLog.logMessage( self.tr( "Model {model} finished running with no errors. You may" " check model output on Processing log tab." ).format(model=modelName), 'DSGTools Plugin', Qgis.Info ) if not self.options()["loadModelOutput"]: return for var, value in out.items(): if isinstance(value, QgsMapLayer): value.setName( "{model} {layername}".format(model=modelName, layername=var) ) self.addLayerToGroup( value, "DSGTools Validation Toolbar Output", modelName ) except Exception as e: msg = self.tr( "Unable to run (check Processing tab for details on model " "execution log) {model}:\n{error}" ).format(model=modelName, error=str(e)) self.iface.messageBar().pushMessage( self.tr("Model {model} failed").format(model=modelName), self.tr("check log for more information."), level=Qgis.Critical, duration=5 ) QgsMessageLog.logMessage(msg, 'DSGTools Plugin',Qgis.Info)