AlgorithmExecutor.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. """
  2. ***************************************************************************
  3. AlgorithmExecutor.py
  4. ---------------------
  5. Date : August 2012
  6. Copyright : (C) 2012 by Victor Olaya
  7. Email : volayaf at gmail dot com
  8. ***************************************************************************
  9. * *
  10. * This program is free software; you can redistribute it and/or modify *
  11. * it under the terms of the GNU General Public License as published by *
  12. * the Free Software Foundation; either version 2 of the License, or *
  13. * (at your option) any later version. *
  14. * *
  15. ***************************************************************************
  16. """
  17. __author__ = 'Victor Olaya'
  18. __date__ = 'August 2012'
  19. __copyright__ = '(C) 2012, Victor Olaya'
  20. import sys
  21. from qgis.PyQt.QtCore import QCoreApplication
  22. from qgis.core import (Qgis,
  23. QgsApplication,
  24. QgsFeatureSink,
  25. QgsProcessingFeedback,
  26. QgsProcessingUtils,
  27. QgsMessageLog,
  28. QgsProcessingException,
  29. QgsProcessingFeatureSourceDefinition,
  30. QgsProcessingFeatureSource,
  31. QgsProcessingParameters,
  32. QgsProject,
  33. QgsFeatureRequest,
  34. QgsFeature,
  35. QgsExpression,
  36. QgsWkbTypes,
  37. QgsGeometry,
  38. QgsVectorLayerUtils,
  39. QgsVectorLayer)
  40. from processing.gui.Postprocessing import handleAlgorithmResults
  41. from processing.tools import dataobjects
  42. from qgis.utils import iface
  43. def execute(alg, parameters, context=None, feedback=None, catch_exceptions=True):
  44. """Executes a given algorithm, showing its progress in the
  45. progress object passed along.
  46. Return true if everything went OK, false if the algorithm
  47. could not be completed.
  48. """
  49. if feedback is None:
  50. feedback = QgsProcessingFeedback()
  51. if context is None:
  52. context = dataobjects.createContext(feedback)
  53. if catch_exceptions:
  54. try:
  55. results, ok = alg.run(parameters, context, feedback)
  56. return ok, results
  57. except QgsProcessingException as e:
  58. QgsMessageLog.logMessage(str(sys.exc_info()[0]), 'Processing', Qgis.Critical)
  59. if feedback is not None:
  60. feedback.reportError(e.msg)
  61. return False, {}
  62. else:
  63. results, ok = alg.run(parameters, context, feedback, {}, False)
  64. return ok, results
  65. def execute_in_place_run(alg, parameters, context=None, feedback=None, raise_exceptions=False):
  66. """Executes an algorithm modifying features in-place in the input layer.
  67. :param alg: algorithm to run
  68. :type alg: QgsProcessingAlgorithm
  69. :param parameters: parameters of the algorithm
  70. :type parameters: dict
  71. :param context: context, defaults to None
  72. :type context: QgsProcessingContext, optional
  73. :param feedback: feedback, defaults to None
  74. :type feedback: QgsProcessingFeedback, optional
  75. :param raise_exceptions: useful for testing, if True exceptions are raised, normally exceptions will be forwarded to the feedback
  76. :type raise_exceptions: boo, default to False
  77. :raises QgsProcessingException: raised when there is no active layer, or it cannot be made editable
  78. :return: a tuple with true if success and results
  79. :rtype: tuple
  80. """
  81. if feedback is None:
  82. feedback = QgsProcessingFeedback()
  83. if context is None:
  84. context = dataobjects.createContext(feedback)
  85. # Only feature based algs have sourceFlags
  86. try:
  87. if alg.sourceFlags() & QgsProcessingFeatureSource.FlagSkipGeometryValidityChecks:
  88. context.setInvalidGeometryCheck(QgsFeatureRequest.GeometryNoCheck)
  89. except AttributeError:
  90. pass
  91. in_place_input_parameter_name = 'INPUT'
  92. if hasattr(alg, 'inputParameterName'):
  93. in_place_input_parameter_name = alg.inputParameterName()
  94. active_layer = parameters[in_place_input_parameter_name]
  95. # prepare expression context for feature iteration
  96. alg_context = context.expressionContext()
  97. alg_context.appendScope(active_layer.createExpressionContextScope())
  98. context.setExpressionContext(alg_context)
  99. # Run some checks and prepare the layer for in-place execution by:
  100. # - getting the active layer and checking that it is a vector
  101. # - making the layer editable if it was not already
  102. # - selecting all features if none was selected
  103. # - checking in-place support for the active layer/alg/parameters
  104. # If one of the check fails and raise_exceptions is True an exception
  105. # is raised, else the execution is aborted and the error reported in
  106. # the feedback
  107. try:
  108. if active_layer is None:
  109. raise QgsProcessingException(tr("There is no active layer."))
  110. if not isinstance(active_layer, QgsVectorLayer):
  111. raise QgsProcessingException(tr("Active layer is not a vector layer."))
  112. if not active_layer.isEditable():
  113. if not active_layer.startEditing():
  114. raise QgsProcessingException(tr("Active layer is not editable (and editing could not be turned on)."))
  115. if not alg.supportInPlaceEdit(active_layer):
  116. raise QgsProcessingException(tr("Selected algorithm and parameter configuration are not compatible with in-place modifications."))
  117. except QgsProcessingException as e:
  118. if raise_exceptions:
  119. raise e
  120. QgsMessageLog.logMessage(str(sys.exc_info()[0]), 'Processing', Qgis.Critical)
  121. if feedback is not None:
  122. feedback.reportError(getattr(e, 'msg', str(e)), fatalError=True)
  123. return False, {}
  124. if not active_layer.selectedFeatureIds():
  125. active_layer.selectAll()
  126. # Make sure we are working on selected features only
  127. parameters[in_place_input_parameter_name] = QgsProcessingFeatureSourceDefinition(active_layer.id(), True)
  128. parameters['OUTPUT'] = 'memory:'
  129. req = QgsFeatureRequest(QgsExpression(r"$id < 0"))
  130. req.setFlags(QgsFeatureRequest.NoGeometry)
  131. req.setSubsetOfAttributes([])
  132. # Start the execution
  133. # If anything goes wrong and raise_exceptions is True an exception
  134. # is raised, else the execution is aborted and the error reported in
  135. # the feedback
  136. try:
  137. new_feature_ids = []
  138. active_layer.beginEditCommand(alg.displayName())
  139. # Checks whether the algorithm has a processFeature method
  140. if hasattr(alg, 'processFeature'): # in-place feature editing
  141. # Make a clone or it will crash the second time the dialog
  142. # is opened and run
  143. alg = alg.create({'IN_PLACE': True})
  144. if not alg.prepare(parameters, context, feedback):
  145. raise QgsProcessingException(tr("Could not prepare selected algorithm."))
  146. # Check again for compatibility after prepare
  147. if not alg.supportInPlaceEdit(active_layer):
  148. raise QgsProcessingException(tr("Selected algorithm and parameter configuration are not compatible with in-place modifications."))
  149. # some algorithms have logic in outputFields/outputCrs/outputWkbType which they require to execute before
  150. # they can start processing features
  151. _ = alg.outputFields(active_layer.fields())
  152. _ = alg.outputWkbType(active_layer.wkbType())
  153. _ = alg.outputCrs(active_layer.crs())
  154. field_idxs = range(len(active_layer.fields()))
  155. iterator_req = QgsFeatureRequest(active_layer.selectedFeatureIds())
  156. iterator_req.setInvalidGeometryCheck(context.invalidGeometryCheck())
  157. feature_iterator = active_layer.getFeatures(iterator_req)
  158. step = 100 / len(active_layer.selectedFeatureIds()) if active_layer.selectedFeatureIds() else 1
  159. current = 0
  160. for current, f in enumerate(feature_iterator):
  161. if feedback.isCanceled():
  162. break
  163. # need a deep copy, because python processFeature implementations may return
  164. # a shallow copy from processFeature
  165. input_feature = QgsFeature(f)
  166. context.expressionContext().setFeature(input_feature)
  167. new_features = alg.processFeature(input_feature, context, feedback)
  168. new_features = QgsVectorLayerUtils.makeFeaturesCompatible(new_features, active_layer)
  169. if len(new_features) == 0:
  170. active_layer.deleteFeature(f.id())
  171. elif len(new_features) == 1:
  172. new_f = new_features[0]
  173. if not f.geometry().equals(new_f.geometry()):
  174. active_layer.changeGeometry(f.id(), new_f.geometry())
  175. if f.attributes() != new_f.attributes():
  176. active_layer.changeAttributeValues(f.id(), dict(zip(field_idxs, new_f.attributes())), dict(zip(field_idxs, f.attributes())))
  177. new_feature_ids.append(f.id())
  178. else:
  179. active_layer.deleteFeature(f.id())
  180. # Get the new ids
  181. old_ids = {f.id() for f in active_layer.getFeatures(req)}
  182. # If multiple new features were created, we need to pass
  183. # them to createFeatures to manage constraints correctly
  184. features_data = []
  185. for f in new_features:
  186. features_data.append(QgsVectorLayerUtils.QgsFeatureData(f.geometry(), dict(enumerate(f.attributes()))))
  187. new_features = QgsVectorLayerUtils.createFeatures(active_layer, features_data, context.expressionContext())
  188. if not active_layer.addFeatures(new_features):
  189. raise QgsProcessingException(tr("Error adding processed features back into the layer."))
  190. new_ids = {f.id() for f in active_layer.getFeatures(req)}
  191. new_feature_ids += list(new_ids - old_ids)
  192. feedback.setProgress(int((current + 1) * step))
  193. results, ok = {'__count': current + 1}, True
  194. else: # Traditional 'run' with delete and add features cycle
  195. # There is no way to know if some features have been skipped
  196. # due to invalid geometries
  197. if context.invalidGeometryCheck() == QgsFeatureRequest.GeometrySkipInvalid:
  198. selected_ids = active_layer.selectedFeatureIds()
  199. else:
  200. selected_ids = []
  201. results, ok = alg.run(parameters, context, feedback, configuration={'IN_PLACE': True})
  202. if ok:
  203. result_layer = QgsProcessingUtils.mapLayerFromString(results['OUTPUT'], context)
  204. # TODO: check if features have changed before delete/add cycle
  205. new_features = []
  206. # Check if there are any skipped features
  207. if context.invalidGeometryCheck() == QgsFeatureRequest.GeometrySkipInvalid:
  208. missing_ids = list(set(selected_ids) - set(result_layer.allFeatureIds()))
  209. if missing_ids:
  210. for f in active_layer.getFeatures(QgsFeatureRequest(missing_ids)):
  211. if not f.geometry().isGeosValid():
  212. new_features.append(f)
  213. active_layer.deleteFeatures(active_layer.selectedFeatureIds())
  214. regenerate_primary_key = result_layer.customProperty('OnConvertFormatRegeneratePrimaryKey', False)
  215. sink_flags = QgsFeatureSink.SinkFlags(QgsFeatureSink.RegeneratePrimaryKey) if regenerate_primary_key \
  216. else QgsFeatureSink.SinkFlags()
  217. for f in result_layer.getFeatures():
  218. new_features.extend(QgsVectorLayerUtils.
  219. makeFeaturesCompatible([f], active_layer, sink_flags))
  220. # Get the new ids
  221. old_ids = {f.id() for f in active_layer.getFeatures(req)}
  222. if not active_layer.addFeatures(new_features):
  223. raise QgsProcessingException(tr("Error adding processed features back into the layer."))
  224. new_ids = {f.id() for f in active_layer.getFeatures(req)}
  225. new_feature_ids += list(new_ids - old_ids)
  226. results['__count'] = len(new_feature_ids)
  227. active_layer.endEditCommand()
  228. if ok and new_feature_ids:
  229. active_layer.selectByIds(new_feature_ids)
  230. elif not ok:
  231. active_layer.rollBack()
  232. return ok, results
  233. except QgsProcessingException as e:
  234. active_layer.endEditCommand()
  235. active_layer.rollBack()
  236. if raise_exceptions:
  237. raise e
  238. QgsMessageLog.logMessage(str(sys.exc_info()[0]), 'Processing', Qgis.Critical)
  239. if feedback is not None:
  240. feedback.reportError(getattr(e, 'msg', str(e)), fatalError=True)
  241. return False, {}
  242. def execute_in_place(alg, parameters, context=None, feedback=None):
  243. """Executes an algorithm modifying features in-place, if the INPUT
  244. parameter is not defined, the current active layer will be used as
  245. INPUT.
  246. :param alg: algorithm to run
  247. :type alg: QgsProcessingAlgorithm
  248. :param parameters: parameters of the algorithm
  249. :type parameters: dict
  250. :param context: context, defaults to None
  251. :param context: QgsProcessingContext, optional
  252. :param feedback: feedback, defaults to None
  253. :param feedback: QgsProcessingFeedback, optional
  254. :raises QgsProcessingException: raised when the layer is not editable or the layer cannot be found in the current project
  255. :return: a tuple with true if success and results
  256. :rtype: tuple
  257. """
  258. if feedback is None:
  259. feedback = QgsProcessingFeedback()
  260. if context is None:
  261. context = dataobjects.createContext(feedback)
  262. in_place_input_parameter_name = 'INPUT'
  263. if hasattr(alg, 'inputParameterName'):
  264. in_place_input_parameter_name = alg.inputParameterName()
  265. in_place_input_layer_name = 'INPUT'
  266. if hasattr(alg, 'inputParameterDescription'):
  267. in_place_input_layer_name = alg.inputParameterDescription()
  268. if in_place_input_parameter_name not in parameters or not parameters[in_place_input_parameter_name]:
  269. parameters[in_place_input_parameter_name] = iface.activeLayer()
  270. ok, results = execute_in_place_run(alg, parameters, context=context, feedback=feedback)
  271. if ok:
  272. if isinstance(parameters[in_place_input_parameter_name], QgsProcessingFeatureSourceDefinition):
  273. layer = alg.parameterAsVectorLayer({in_place_input_parameter_name: parameters[in_place_input_parameter_name].source}, in_place_input_layer_name, context)
  274. elif isinstance(parameters[in_place_input_parameter_name], QgsVectorLayer):
  275. layer = parameters[in_place_input_parameter_name]
  276. if layer:
  277. layer.triggerRepaint()
  278. return ok, results
  279. def executeIterating(alg, parameters, paramToIter, context, feedback):
  280. # Generate all single-feature layers
  281. parameter_definition = alg.parameterDefinition(paramToIter)
  282. if not parameter_definition:
  283. return False
  284. iter_source = QgsProcessingParameters.parameterAsSource(parameter_definition, parameters, context)
  285. sink_list = []
  286. if iter_source.featureCount() == 0:
  287. return False
  288. step = 100.0 / iter_source.featureCount()
  289. for current, feat in enumerate(iter_source.getFeatures()):
  290. if feedback.isCanceled():
  291. return False
  292. sink, sink_id = QgsProcessingUtils.createFeatureSink('memory:', context, iter_source.fields(), iter_source.wkbType(), iter_source.sourceCrs())
  293. sink_list.append(sink_id)
  294. sink.addFeature(feat, QgsFeatureSink.FastInsert)
  295. del sink
  296. feedback.setProgress(int((current + 1) * step))
  297. # store output values to use them later as basenames for all outputs
  298. outputs = {}
  299. for out in alg.destinationParameterDefinitions():
  300. if out.name() in parameters:
  301. outputs[out.name()] = parameters[out.name()]
  302. # now run all the algorithms
  303. for i, f in enumerate(sink_list):
  304. if feedback.isCanceled():
  305. return False
  306. parameters[paramToIter] = f
  307. for out in alg.destinationParameterDefinitions():
  308. if out.name() not in outputs:
  309. continue
  310. o = outputs[out.name()]
  311. parameters[out.name()] = QgsProcessingUtils.generateIteratingDestination(o, i, context)
  312. feedback.setProgressText(QCoreApplication.translate('AlgorithmExecutor', 'Executing iteration {0}/{1}…').format(i + 1, len(sink_list)))
  313. feedback.setProgress(int((i + 1) * 100 / len(sink_list)))
  314. ret, results = execute(alg, parameters, context, feedback)
  315. if not ret:
  316. return False
  317. handleAlgorithmResults(alg, context, feedback)
  318. return True
  319. def tr(string, context=''):
  320. if context == '':
  321. context = 'AlgorithmExecutor'
  322. return QCoreApplication.translate(context, string)