SHARE
TWEET

Untitled

a guest Jul 17th, 2019 115 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # -*- coding: utf-8 -*-
  2.  
  3. """
  4. ***************************************************************************
  5. *                                                                         *
  6. *   This program is free software; you can redistribute it and/or modify  *
  7. *   it under the terms of the GNU General Public License as published by  *
  8. *   the Free Software Foundation; either version 2 of the License, or     *
  9. *   (at your option) any later version.                                   *
  10. *                                                                         *
  11. ***************************************************************************
  12. """
  13.  
  14. from processing.gui.wrappers import WidgetWrapper
  15. from qgis.PyQt.QtWidgets import QDateTimeEdit
  16. from qgis.PyQt.QtCore import QCoreApplication, QDate
  17. from qgis.core import (QgsProcessing,
  18.                    QgsFeatureSink,
  19.                    QgsProcessingException,
  20.                    QgsProcessingAlgorithm,
  21.                    QgsProcessingParameterString,
  22.                    QgsProcessingParameterFeatureSource,
  23.                    QgsProcessingParameterFeatureSink)
  24. from qgis import processing
  25.  
  26. class DateTimeWidget(WidgetWrapper):
  27.     """
  28.     QDateTimeEdit widget with calendar pop up
  29.     """
  30.  
  31.     def createWidget(self):
  32.         self._combo = QDateTimeEdit()
  33.         self._combo.setCalendarPopup(True)
  34.  
  35.         today = QDate.currentDate()
  36.         self._combo.setDate(today)
  37.  
  38.         return self._combo
  39.  
  40.     def value(self):
  41.         date_chosen = self._combo.dateTime()
  42.         return date_chosen.toString(Qt.ISODate)
  43.  
  44.  
  45. class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
  46.     """
  47.     This is an example algorithm that takes a vector layer and
  48.     creates a new identical one.
  49.  
  50.     It is meant to be used as an example of how to create your own
  51.     algorithms and explain methods and variables used to do it. An
  52.     algorithm like this will be available in all elements, and there
  53.     is not need for additional work.
  54.  
  55.     All Processing algorithms should extend the QgsProcessingAlgorithm
  56.     class.
  57.     """
  58.  
  59.     # Constants used to refer to parameters and outputs. They will be
  60.     # used when calling the algorithm from another algorithm, or when
  61.     # calling from the QGIS console.
  62.  
  63.     INPUT = 'INPUT'
  64.     DATEINI = 'DATEINI'
  65.     OUTPUT = 'OUTPUT'
  66.  
  67.     def tr(self, string):
  68.         """
  69.         Returns a translatable string with the self.tr() function.
  70.         """
  71.         return QCoreApplication.translate('Processing', string)
  72.  
  73.     def createInstance(self):
  74.         return ExampleProcessingAlgorithm()
  75.  
  76.     def name(self):
  77.         """
  78.         Returns the algorithm name, used for identifying the algorithm. This
  79.         string should be fixed for the algorithm, and must not be localised.
  80.         The name should be unique within each provider. Names should contain
  81.         lowercase alphanumeric characters only and no spaces or other
  82.         formatting characters.
  83.         """
  84.         return 'myscript'
  85.  
  86.     def displayName(self):
  87.         """
  88.         Returns the translated algorithm name, which should be used for any
  89.         user-visible display of the algorithm name.
  90.         """
  91.         return self.tr('My Script')
  92.  
  93.     def group(self):
  94.         """
  95.         Returns the name of the group this algorithm belongs to. This string
  96.         should be localised.
  97.         """
  98.         return self.tr('Example scripts')
  99.  
  100.     def groupId(self):
  101.         """
  102.         Returns the unique ID of the group this algorithm belongs to. This
  103.         string should be fixed for the algorithm, and must not be localised.
  104.         The group id should be unique within each provider. Group id should
  105.         contain lowercase alphanumeric characters only and no spaces or other
  106.         formatting characters.
  107.         """
  108.         return 'examplescripts'
  109.  
  110.     def shortHelpString(self):
  111.         """
  112.         Returns a localised short helper string for the algorithm. This string
  113.         should provide a basic description about what the algorithm does and the
  114.         parameters and outputs associated with it..
  115.         """
  116.         return self.tr("Example algorithm short description")
  117.  
  118.     def initAlgorithm(self, config=None):
  119.         """
  120.         Here we define the inputs and output of the algorithm, along
  121.         with some other properties.
  122.         """
  123.  
  124.         # We add the input vector features source. It can have any kind of
  125.         # geometry.
  126.         self.addParameter(
  127.             QgsProcessingParameterFeatureSource(
  128.                 self.INPUT,
  129.                 self.tr('Input layer'),
  130.                 [QgsProcessing.TypeVectorAnyGeometry]
  131.             )
  132.         )
  133.        
  134.         param = QgsProcessingParameterString(self.DATEINI, 'Initial Date')
  135.         param.setMetadata({
  136.             'widget_wrapper': {
  137.                 'class': DateTimeWidget}})
  138.  
  139.         self.addParameter(param)
  140.  
  141.         # We add a feature sink in which to store our processed features (this
  142.         # usually takes the form of a newly created vector layer when the
  143.         # algorithm is run in QGIS).
  144.         self.addParameter(
  145.             QgsProcessingParameterFeatureSink(
  146.                 self.OUTPUT,
  147.                 self.tr('Output layer')
  148.             )
  149.         )
  150.  
  151.     def processAlgorithm(self, parameters, context, feedback):
  152.         """
  153.         Here is where the processing itself takes place.
  154.         """
  155.  
  156.         # Retrieve the feature source and sink. The 'dest_id' variable is used
  157.         # to uniquely identify the feature sink, and must be included in the
  158.         # dictionary returned by the processAlgorithm function.
  159.         source = self.parameterAsSource(
  160.             parameters,
  161.             self.INPUT,
  162.             context
  163.         )
  164.        
  165.         mydate = self.parameterAsString(
  166.             parameters,
  167.             self.INIDATE,
  168.             context
  169.         )
  170.  
  171.         # If source was not found, throw an exception to indicate that the algorithm
  172.         # encountered a fatal error. The exception text can be any string, but in this
  173.         # case we use the pre-built invalidSourceError method to return a standard
  174.         # helper text for when a source cannot be evaluated
  175.         if source is None:
  176.             raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
  177.  
  178.         (sink, dest_id) = self.parameterAsSink(
  179.             parameters,
  180.             self.OUTPUT,
  181.             context,
  182.             source.fields(),
  183.             source.wkbType(),
  184.             source.sourceCrs()
  185.         )
  186.  
  187.         # Send some information to the user
  188.         feedback.pushInfo('CRS is {}'.format(source.sourceCrs().authid()))
  189.  
  190.         # If sink was not created, throw an exception to indicate that the algorithm
  191.         # encountered a fatal error. The exception text can be any string, but in this
  192.         # case we use the pre-built invalidSinkError method to return a standard
  193.         # helper text for when a sink cannot be evaluated
  194.         if sink is None:
  195.             raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
  196.  
  197.         # Compute the number of steps to display within the progress bar and
  198.         # get features from source
  199.         total = 100.0 / source.featureCount() if source.featureCount() else 0
  200.         features = source.getFeatures()
  201.  
  202.         for current, feature in enumerate(features):
  203.             # Stop the algorithm if cancel button has been clicked
  204.             if feedback.isCanceled():
  205.                 break
  206.  
  207.             # Add a feature in the sink
  208.             sink.addFeature(feature, QgsFeatureSink.FastInsert)
  209.  
  210.             # Update the progress bar
  211.             feedback.setProgress(int(current * total))
  212.  
  213.         # To run another Processing algorithm as part of this algorithm, you can use
  214.         # processing.run(...). Make sure you pass the current context and feedback
  215.         # to processing.run to ensure that all temporary layer outputs are available
  216.         # to the executed algorithm, and that the executed algorithm can send feedback
  217.         # reports to the user (and correctly handle cancellation and progress reports!)
  218.         if False:
  219.             buffered_layer = processing.run("native:buffer", {
  220.                 'INPUT': dest_id,
  221.                 'DISTANCE': 1.5,
  222.                 'SEGMENTS': 5,
  223.                 'END_CAP_STYLE': 0,
  224.                 'JOIN_STYLE': 0,
  225.                 'MITER_LIMIT': 2,
  226.                 'DISSOLVE': False,
  227.                 'OUTPUT': 'memory:'
  228.             }, context=context, feedback=feedback)['OUTPUT']
  229.  
  230.         # Return the results of the algorithm. In this case our only result is
  231.         # the feature sink which contains the processed features, but some
  232.         # algorithms may return multiple feature sinks, calculated numeric
  233.         # statistics, etc. These should all be included in the returned
  234.         # dictionary, with keys matching the feature corresponding parameter
  235.         # or output names.
  236.         return {self.OUTPUT: dest_id}
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top