ScriptTemplate.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. """
  2. ***************************************************************************
  3. * *
  4. * This program is free software; you can redistribute it and/or modify *
  5. * it under the terms of the GNU General Public License as published by *
  6. * the Free Software Foundation; either version 2 of the License, or *
  7. * (at your option) any later version. *
  8. * *
  9. ***************************************************************************
  10. """
  11. from qgis.PyQt.QtCore import QCoreApplication
  12. from qgis.core import (QgsProcessing,
  13. QgsFeatureSink,
  14. QgsProcessingException,
  15. QgsProcessingAlgorithm,
  16. QgsProcessingParameterFeatureSource,
  17. QgsProcessingParameterFeatureSink)
  18. from qgis import processing
  19. class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
  20. """
  21. This is an example algorithm that takes a vector layer and
  22. creates a new identical one.
  23. It is meant to be used as an example of how to create your own
  24. algorithms and explain methods and variables used to do it. An
  25. algorithm like this will be available in all elements, and there
  26. is not need for additional work.
  27. All Processing algorithms should extend the QgsProcessingAlgorithm
  28. class.
  29. """
  30. # Constants used to refer to parameters and outputs. They will be
  31. # used when calling the algorithm from another algorithm, or when
  32. # calling from the QGIS console.
  33. INPUT = 'INPUT'
  34. OUTPUT = 'OUTPUT'
  35. def tr(self, string):
  36. """
  37. Returns a translatable string with the self.tr() function.
  38. """
  39. return QCoreApplication.translate('Processing', string)
  40. def createInstance(self):
  41. return ExampleProcessingAlgorithm()
  42. def name(self):
  43. """
  44. Returns the algorithm name, used for identifying the algorithm. This
  45. string should be fixed for the algorithm, and must not be localised.
  46. The name should be unique within each provider. Names should contain
  47. lowercase alphanumeric characters only and no spaces or other
  48. formatting characters.
  49. """
  50. return 'myscript'
  51. def displayName(self):
  52. """
  53. Returns the translated algorithm name, which should be used for any
  54. user-visible display of the algorithm name.
  55. """
  56. return self.tr('My Script')
  57. def group(self):
  58. """
  59. Returns the name of the group this algorithm belongs to. This string
  60. should be localised.
  61. """
  62. return self.tr('Example scripts')
  63. def groupId(self):
  64. """
  65. Returns the unique ID of the group this algorithm belongs to. This
  66. string should be fixed for the algorithm, and must not be localised.
  67. The group id should be unique within each provider. Group id should
  68. contain lowercase alphanumeric characters only and no spaces or other
  69. formatting characters.
  70. """
  71. return 'examplescripts'
  72. def shortHelpString(self):
  73. """
  74. Returns a localised short helper string for the algorithm. This string
  75. should provide a basic description about what the algorithm does and the
  76. parameters and outputs associated with it..
  77. """
  78. return self.tr("Example algorithm short description")
  79. def initAlgorithm(self, config=None):
  80. """
  81. Here we define the inputs and output of the algorithm, along
  82. with some other properties.
  83. """
  84. # We add the input vector features source. It can have any kind of
  85. # geometry.
  86. self.addParameter(
  87. QgsProcessingParameterFeatureSource(
  88. self.INPUT,
  89. self.tr('Input layer'),
  90. [QgsProcessing.TypeVectorAnyGeometry]
  91. )
  92. )
  93. # We add a feature sink in which to store our processed features (this
  94. # usually takes the form of a newly created vector layer when the
  95. # algorithm is run in QGIS).
  96. self.addParameter(
  97. QgsProcessingParameterFeatureSink(
  98. self.OUTPUT,
  99. self.tr('Output layer')
  100. )
  101. )
  102. def processAlgorithm(self, parameters, context, feedback):
  103. """
  104. Here is where the processing itself takes place.
  105. """
  106. # Retrieve the feature source and sink. The 'dest_id' variable is used
  107. # to uniquely identify the feature sink, and must be included in the
  108. # dictionary returned by the processAlgorithm function.
  109. source = self.parameterAsSource(
  110. parameters,
  111. self.INPUT,
  112. context
  113. )
  114. # If source was not found, throw an exception to indicate that the algorithm
  115. # encountered a fatal error. The exception text can be any string, but in this
  116. # case we use the pre-built invalidSourceError method to return a standard
  117. # helper text for when a source cannot be evaluated
  118. if source is None:
  119. raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
  120. (sink, dest_id) = self.parameterAsSink(
  121. parameters,
  122. self.OUTPUT,
  123. context,
  124. source.fields(),
  125. source.wkbType(),
  126. source.sourceCrs()
  127. )
  128. # Send some information to the user
  129. feedback.pushInfo(f'CRS is {source.sourceCrs().authid()}')
  130. # If sink was not created, throw an exception to indicate that the algorithm
  131. # encountered a fatal error. The exception text can be any string, but in this
  132. # case we use the pre-built invalidSinkError method to return a standard
  133. # helper text for when a sink cannot be evaluated
  134. if sink is None:
  135. raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
  136. # Compute the number of steps to display within the progress bar and
  137. # get features from source
  138. total = 100.0 / source.featureCount() if source.featureCount() else 0
  139. features = source.getFeatures()
  140. for current, feature in enumerate(features):
  141. # Stop the algorithm if cancel button has been clicked
  142. if feedback.isCanceled():
  143. break
  144. # Add a feature in the sink
  145. sink.addFeature(feature, QgsFeatureSink.FastInsert)
  146. # Update the progress bar
  147. feedback.setProgress(int(current * total))
  148. # To run another Processing algorithm as part of this algorithm, you can use
  149. # processing.run(...). Make sure you pass the current context and feedback
  150. # to processing.run to ensure that all temporary layer outputs are available
  151. # to the executed algorithm, and that the executed algorithm can send feedback
  152. # reports to the user (and correctly handle cancellation and progress reports!)
  153. if False:
  154. buffered_layer = processing.run("native:buffer", {
  155. 'INPUT': dest_id,
  156. 'DISTANCE': 1.5,
  157. 'SEGMENTS': 5,
  158. 'END_CAP_STYLE': 0,
  159. 'JOIN_STYLE': 0,
  160. 'MITER_LIMIT': 2,
  161. 'DISSOLVE': False,
  162. 'OUTPUT': 'memory:'
  163. }, context=context, feedback=feedback)['OUTPUT']
  164. # Return the results of the algorithm. In this case our only result is
  165. # the feature sink which contains the processed features, but some
  166. # algorithms may return multiple feature sinks, calculated numeric
  167. # statistics, etc. These should all be included in the returned
  168. # dictionary, with keys matching the feature corresponding parameter
  169. # or output names.
  170. return {self.OUTPUT: dest_id}