Esempio n. 1
0
    def accept(self):
        alg_parameters = []

        feedback = self.createFeedback()

        load_layers = self.mainWidget().checkLoadLayersOnCompletion.isChecked()
        project = QgsProject.instance() if load_layers else None

        for row in range(self.mainWidget().tblParameters.rowCount()):
            col = 0
            parameters = {}
            for param in self.algorithm().parameterDefinitions():
                if param.flags(
                ) & QgsProcessingParameterDefinition.FlagHidden or param.isDestination(
                ):
                    continue
                wrapper = self.mainWidget().wrappers[row][col]
                parameters[param.name()] = wrapper.parameterValue()
                if not param.checkValueIsAcceptable(wrapper.parameterValue()):
                    self.messageBar().pushMessage(
                        "",
                        self.tr(
                            'Wrong or missing parameter value: {0} (row {1})').
                        format(param.description(), row + 1),
                        level=Qgis.Warning,
                        duration=5)
                    return
                col += 1
            count_visible_outputs = 0
            for out in self.algorithm().destinationParameterDefinitions():
                if out.flags() & QgsProcessingParameterDefinition.FlagHidden:
                    continue

                count_visible_outputs += 1
                widget = self.mainWidget().tblParameters.cellWidget(row, col)
                text = widget.getValue()
                if out.checkValueIsAcceptable(text):
                    if isinstance(out,
                                  (QgsProcessingParameterRasterDestination,
                                   QgsProcessingParameterVectorDestination,
                                   QgsProcessingParameterFeatureSink)):
                        # load rasters and sinks on completion
                        parameters[
                            out.name()] = QgsProcessingOutputLayerDefinition(
                                text, project)
                    else:
                        parameters[out.name()] = text
                    col += 1
                else:
                    self.messageBar().pushMessage(
                        "",
                        self.tr('Wrong or missing output value: {0} (row {1})'
                                ).format(out.description(), row + 1),
                        level=Qgis.Warning,
                        duration=5)
                    return

            alg_parameters.append(parameters)

        task = QgsScopedProxyProgressTask(
            self.tr('Batch Processing - {0}').format(
                self.algorithm().displayName()))
        multi_feedback = QgsProcessingMultiStepFeedback(
            len(alg_parameters), feedback)
        feedback.progressChanged.connect(task.setProgress)

        with OverrideCursor(Qt.WaitCursor):

            self.mainWidget().setEnabled(False)
            self.cancelButton().setEnabled(True)

            # Make sure the Log tab is visible before executing the algorithm
            try:
                self.showLog()
                self.repaint()
            except:
                pass

            start_time = time.time()

            algorithm_results = []
            for count, parameters in enumerate(alg_parameters):
                if feedback.isCanceled():
                    break
                self.setProgressText(
                    QCoreApplication.translate(
                        'BatchAlgorithmDialog',
                        '\nProcessing algorithm {0}/{1}…').format(
                            count + 1, len(alg_parameters)))
                self.setInfo(
                    self.tr('<b>Algorithm {0} starting&hellip;</b>').format(
                        self.algorithm().displayName()),
                    escapeHtml=False)
                multi_feedback.setCurrentStep(count)

                parameters = self.algorithm().preprocessParameters(parameters)

                feedback.pushInfo(self.tr('Input parameters:'))
                feedback.pushCommandInfo(pformat(parameters))
                feedback.pushInfo('')

                # important - we create a new context for each iteration
                # this avoids holding onto resources and layers from earlier iterations,
                # and allows batch processing of many more items then is possible
                # if we hold on to these layers
                context = dataobjects.createContext(feedback)

                alg_start_time = time.time()
                ret, results = execute(self.algorithm(), parameters, context,
                                       multi_feedback)
                if ret:
                    self.setInfo(QCoreApplication.translate(
                        'BatchAlgorithmDialog',
                        'Algorithm {0} correctly executed…').format(
                            self.algorithm().displayName()),
                                 escapeHtml=False)
                    feedback.pushInfo(
                        self.tr(
                            'Execution completed in {0:0.2f} seconds'.format(
                                time.time() - alg_start_time)))
                    feedback.pushInfo(self.tr('Results:'))
                    feedback.pushCommandInfo(pformat(results))
                    feedback.pushInfo('')
                    algorithm_results.append(results)
                else:
                    break

                handleAlgorithmResults(self.algorithm(), context,
                                       multi_feedback, False)

        feedback.pushInfo(
            self.tr('Batch execution completed in {0:0.2f} seconds'.format(
                time.time() - start_time)))
        task = None

        self.finish(algorithm_results)
        self.cancelButton().setEnabled(False)
Esempio n. 2
0
    def runAlgorithm(self):
        alg_parameters = []

        feedback = self.createFeedback()

        load_layers = self.mainWidget().checkLoadLayersOnCompletion.isChecked()
        project = QgsProject.instance() if load_layers else None

        for row in range(self.mainWidget().batchRowCount()):
            parameters = self.mainWidget().parametersForRow(
                row, destinationProject=project, warnOnInvalid=True)
            alg_parameters.append(parameters)

        task = QgsScopedProxyProgressTask(
            self.tr('Batch Processing - {0}').format(
                self.algorithm().displayName()))
        multi_feedback = QgsProcessingMultiStepFeedback(
            len(alg_parameters), feedback)
        feedback.progressChanged.connect(task.setProgress)

        with OverrideCursor(Qt.WaitCursor):

            self.mainWidget().setEnabled(False)
            self.cancelButton().setEnabled(True)

            # Make sure the Log tab is visible before executing the algorithm
            try:
                self.showLog()
                self.repaint()
            except:
                pass

            start_time = time.time()

            algorithm_results = []
            for count, parameters in enumerate(alg_parameters):
                if feedback.isCanceled():
                    break
                self.setProgressText(
                    QCoreApplication.translate(
                        'BatchAlgorithmDialog',
                        '\nProcessing algorithm {0}/{1}…').format(
                            count + 1, len(alg_parameters)))
                self.setInfo(
                    self.tr('<b>Algorithm {0} starting&hellip;</b>').format(
                        self.algorithm().displayName()),
                    escapeHtml=False)
                multi_feedback.setCurrentStep(count)

                parameters = self.algorithm().preprocessParameters(parameters)

                feedback.pushInfo(self.tr('Input parameters:'))
                feedback.pushCommandInfo(pformat(parameters))
                feedback.pushInfo('')

                # important - we create a new context for each iteration
                # this avoids holding onto resources and layers from earlier iterations,
                # and allows batch processing of many more items then is possible
                # if we hold on to these layers
                context = dataobjects.createContext(feedback)

                alg_start_time = time.time()
                ret, results = execute(self.algorithm(), parameters, context,
                                       multi_feedback)
                if ret:
                    self.setInfo(QCoreApplication.translate(
                        'BatchAlgorithmDialog',
                        'Algorithm {0} correctly executed…').format(
                            self.algorithm().displayName()),
                                 escapeHtml=False)
                    feedback.pushInfo(
                        self.tr(
                            'Execution completed in {0:0.2f} seconds'.format(
                                time.time() - alg_start_time)))
                    feedback.pushInfo(self.tr('Results:'))
                    feedback.pushCommandInfo(pformat(results))
                    feedback.pushInfo('')
                    algorithm_results.append(results)
                else:
                    break

                handleAlgorithmResults(self.algorithm(), context,
                                       multi_feedback, False, parameters)

        feedback.pushInfo(
            self.tr('Batch execution completed in {0:0.2f} seconds'.format(
                time.time() - start_time)))
        task = None

        self.finish(algorithm_results)
        self.cancelButton().setEnabled(False)