Exemplo n.º 1
0
 def testMinValue(self):
     parameter = ParameterNumber("myName", "myDescription", minValue=3)
     self.assertFalse(parameter.setValue(1))
     self.assertEqual(parameter.value, None)
     self.assertFalse(parameter.setValue(-2))
     self.assertEqual(parameter.value, None)
     self.assertTrue(parameter.setValue(3))
     self.assertEqual(parameter.value, 3)
Exemplo n.º 2
0
    def testScriptCode(self):
        parameter = ParameterNumber('myName', 'myDescription')
        code = parameter.getAsScriptCode()
        result = getParameterFromString(code)
        self.assertIsInstance(result, ParameterNumber)

        parameter.optional = True
        code = parameter.getAsScriptCode()
        result = getParameterFromString(code)
        self.assertIsInstance(result, ParameterNumber)
        self.assertTrue(result.optional)
Exemplo n.º 3
0
    def defineCharacteristics(self):
        self.name, self.i18n_name = self.trAlgorithm('Heatmap (Kernel Density Estimation)')
        self.group, self.i18n_group = self.trAlgorithm('Interpolation')
        self.tags = self.tr('heatmap,kde,hotspot')

        self.addParameter(ParameterVector(self.INPUT_LAYER,
                                          self.tr('Point layer'), [dataobjects.TYPE_VECTOR_POINT]))
        self.addParameter(ParameterNumber(self.RADIUS,
                                          self.tr('Radius (layer units)'),
                                          0.0, 9999999999, 100.0))

        radius_field_param = ParameterTableField(self.RADIUS_FIELD,
                                                 self.tr('Radius from field'), self.INPUT_LAYER, optional=True, datatype=ParameterTableField.DATA_TYPE_NUMBER)
        radius_field_param.isAdvanced = True
        self.addParameter(radius_field_param)

        class ParameterHeatmapPixelSize(ParameterNumber):

            def __init__(self, name='', description='', parent_layer=None, radius_param=None, radius_field_param=None, minValue=None, maxValue=None,
                         default=None, optional=False, metadata={}):
                ParameterNumber.__init__(self, name, description, minValue, maxValue, default, optional, metadata)
                self.parent_layer = parent_layer
                self.radius_param = radius_param
                self.radius_field_param = radius_field_param

        self.addParameter(ParameterHeatmapPixelSize(self.PIXEL_SIZE,
                                                    self.tr('Output raster size'), parent_layer=self.INPUT_LAYER, radius_param=self.RADIUS,
                                                    radius_field_param=self.RADIUS_FIELD,
                                                    minValue=0.0, maxValue=9999999999, default=0.1,
                                                    metadata={'widget_wrapper': HeatmapPixelSizeWidgetWrapper}))

        weight_field_param = ParameterTableField(self.WEIGHT_FIELD,
                                                 self.tr('Weight from field'), self.INPUT_LAYER, optional=True, datatype=ParameterTableField.DATA_TYPE_NUMBER)
        weight_field_param.isAdvanced = True
        self.addParameter(weight_field_param)
        kernel_shape_param = ParameterSelection(self.KERNEL,
                                                self.tr('Kernel shape'), self.KERNELS)
        kernel_shape_param.isAdvanced = True
        self.addParameter(kernel_shape_param)
        decay_ratio = ParameterNumber(self.DECAY,
                                      self.tr('Decay ratio (Triangular kernels only)'),
                                      -100.0, 100.0, 0.0)
        decay_ratio.isAdvanced = True
        self.addParameter(decay_ratio)
        output_scaling = ParameterSelection(self.OUTPUT_VALUE,
                                            self.tr('Output value scaling'), self.OUTPUT_VALUES)
        output_scaling.isAdvanced = True
        self.addParameter(output_scaling)
        self.addOutput(OutputRaster(self.OUTPUT_LAYER,
                                    self.tr('Heatmap')))
Exemplo n.º 4
0
    def defineCharacteristics(self):
        self.addParameter(ParameterVector(self.INPUT_LAYER,
                                          self.tr('Input layer'), [dataobjects.TYPE_VECTOR_LINE,
                                                                   dataobjects.TYPE_VECTOR_POLYGON]))
        self.addParameter(ParameterNumber(self.ANGLE_TOLERANCE,
                                          self.tr('Maximum angle tolerance (degrees)'),
                                          0.0, 45.0, 15.0))

        max_iterations = ParameterNumber(self.MAX_ITERATIONS,
                                         self.tr('Maximum algorithm iterations'),
                                         1, 10000, 1000)
        max_iterations.isAdvanced = True
        self.addParameter(max_iterations)

        self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Orthogonalized')))
Exemplo n.º 5
0
    def __init__(self):
        super().__init__()
        self.addParameter(ParameterVector(self.INPUT_LAYER,
                                          self.tr('Input layer'), [dataobjects.TYPE_VECTOR_LINE,
                                                                   dataobjects.TYPE_VECTOR_POLYGON]))
        self.addParameter(ParameterNumber(self.ANGLE_TOLERANCE,
                                          self.tr('Maximum angle tolerance (degrees)'),
                                          0.0, 45.0, 15.0))

        max_iterations = ParameterNumber(self.MAX_ITERATIONS,
                                         self.tr('Maximum algorithm iterations'),
                                         1, 10000, 1000)
        max_iterations.setFlags(max_iterations.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(max_iterations)

        self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Orthogonalized')))
Exemplo n.º 6
0
    def __init__(self):
        super().__init__()
        self.addParameter(ParameterVector(self.INPUT_LAYER,
                                          self.tr('Point layer'), [dataobjects.TYPE_VECTOR_POINT]))
        self.addParameter(ParameterNumber(self.RADIUS,
                                          self.tr('Radius (layer units)'),
                                          0.0, 9999999999, 100.0))

        radius_field_param = ParameterTableField(self.RADIUS_FIELD,
                                                 self.tr('Radius from field'), self.INPUT_LAYER, optional=True, datatype=ParameterTableField.DATA_TYPE_NUMBER)
        radius_field_param.setFlags(radius_field_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(radius_field_param)

        class ParameterHeatmapPixelSize(ParameterNumber):

            def __init__(self, name='', description='', parent_layer=None, radius_param=None, radius_field_param=None, minValue=None, maxValue=None,
                         default=None, optional=False, metadata={}):
                ParameterNumber.__init__(self, name, description, minValue, maxValue, default, optional, metadata)
                self.parent_layer = parent_layer
                self.radius_param = radius_param
                self.radius_field_param = radius_field_param

        self.addParameter(ParameterHeatmapPixelSize(self.PIXEL_SIZE,
                                                    self.tr('Output raster size'), parent_layer=self.INPUT_LAYER, radius_param=self.RADIUS,
                                                    radius_field_param=self.RADIUS_FIELD,
                                                    minValue=0.0, maxValue=9999999999, default=0.1,
                                                    metadata={'widget_wrapper': HeatmapPixelSizeWidgetWrapper}))

        weight_field_param = ParameterTableField(self.WEIGHT_FIELD,
                                                 self.tr('Weight from field'), self.INPUT_LAYER, optional=True, datatype=ParameterTableField.DATA_TYPE_NUMBER)
        weight_field_param.setFlags(weight_field_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(weight_field_param)
        kernel_shape_param = ParameterSelection(self.KERNEL,
                                                self.tr('Kernel shape'), self.KERNELS)
        kernel_shape_param.setFlags(kernel_shape_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(kernel_shape_param)
        decay_ratio = ParameterNumber(self.DECAY,
                                      self.tr('Decay ratio (Triangular kernels only)'),
                                      -100.0, 100.0, 0.0)
        decay_ratio.setFlags(decay_ratio.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(decay_ratio)
        output_scaling = ParameterSelection(self.OUTPUT_VALUE,
                                            self.tr('Output value scaling'), self.OUTPUT_VALUES)
        output_scaling.setFlags(output_scaling.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(output_scaling)
        self.addOutput(OutputRaster(self.OUTPUT_LAYER,
                                    self.tr('Heatmap')))
Exemplo n.º 7
0
 def __init__(
     self,
     name="",
     description="",
     parent_layer=None,
     radius_param=None,
     radius_field_param=None,
     minValue=None,
     maxValue=None,
     default=None,
     optional=False,
     metadata={},
 ):
     ParameterNumber.__init__(self, name, description, minValue, maxValue, default, optional, metadata)
     self.parent_layer = parent_layer
     self.radius_param = radius_param
     self.radius_field_param = radius_field_param
Exemplo n.º 8
0
    def defineCharacteristics(self):
        self.name, self.i18n_name = self.trAlgorithm('Orthogonalize')
        self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools')
        self.tags = self.tr('rectangle,perpendicular,right,angles,square,quadrilateralise')

        self.addParameter(ParameterVector(self.INPUT_LAYER,
                                          self.tr('Input layer'), [dataobjects.TYPE_VECTOR_LINE,
                                                                   dataobjects.TYPE_VECTOR_POLYGON]))
        self.addParameter(ParameterNumber(self.ANGLE_TOLERANCE,
                                          self.tr('Maximum angle tolerance (degrees)'),
                                          0.0, 45.0, 15.0))

        max_iterations = ParameterNumber(self.MAX_ITERATIONS,
                                         self.tr('Maximum algorithm iterations'),
                                         1, 10000, 1000)
        max_iterations.isAdvanced = True
        self.addParameter(max_iterations)

        self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Orthogonalized')))
Exemplo n.º 9
0
    def testOptional(self):
        optionalParameter = ParameterNumber("myName", "myDescription", default=1.0, optional=True)
        self.assertEqual(optionalParameter.value, 1.0)
        optionalParameter.setValue(5)
        self.assertEqual(optionalParameter.value, 5)
        self.assertTrue(optionalParameter.setValue(None))
        self.assertEqual(optionalParameter.value, None)

        requiredParameter = ParameterNumber("myName", "myDescription", default=1.0, optional=False)
        self.assertEqual(requiredParameter.value, 1.0)
        requiredParameter.setValue(5)
        self.assertEqual(requiredParameter.value, 5)
        self.assertFalse(requiredParameter.setValue(None))
        self.assertEqual(requiredParameter.value, 5)
Exemplo n.º 10
0
 def testParameterNumber(self):
     param = ParameterNumber('name', 'desc', 0, 10)
     assert not param.setValue('wrongvalue')
     assert param.value is None
     assert not param.setValue(25)
     assert param.value is None
     assert param.setValue(5)
     assert param.value == 5
     assert param.setValue(None)
     assert param.value == param.default
     s = param.serialize()
     param2 = ParameterNumber()
     param2.deserialize(s)
     assert param.default == param2.default
     assert param.max == param2.max
     assert param.min == param2.min
     assert param.description == param2.description
     assert param.name == param2.name
 def testParameterNumber(self):
     param = ParameterNumber('name', 'desc', 0, 10)
     assert not param.setValue('wrongvalue')
     assert param.value is None
     assert not param.setValue(25)
     assert param.value is None
     assert param.setValue(5)
     assert param.value == 5
     assert param.setValue(None)
     assert param.value == param.default
     s = param.serialize()
     param2 = ParameterNumber()
     param2.deserialize(s)
     assert param.default == param2.default
     assert param.max == param2.max
     assert param.min == param2.min
     assert param.description == param2.description
     assert param.name == param2.name
Exemplo n.º 12
0
 def defineCharacteristics(self):
     self.name, self.i18n_name = self.trAlgorithm('lascanopyPro')
     self.group, self.i18n_group = self.trAlgorithm('LAStools Production')
     self.addParametersPointInputFolderGUI()
     self.addParametersPointInputMergedGUI()
     self.addParameter(
         ParameterNumber(lascanopyPro.PLOT_SIZE,
                         self.tr("square plot size"), 0, None, 20))
     self.addParameter(
         ParameterNumber(lascanopyPro.HEIGHT_CUTOFF,
                         self.tr("height cutoff / breast height"), 0, None,
                         1.37))
     self.addParameter(
         ParameterSelection(lascanopyPro.PRODUCT1, self.tr("create"),
                            lascanopyPro.PRODUCTS, 0))
     self.addParameter(
         ParameterSelection(lascanopyPro.PRODUCT2, self.tr("create"),
                            lascanopyPro.PRODUCTS, 0))
     self.addParameter(
         ParameterSelection(lascanopyPro.PRODUCT3, self.tr("create"),
                            lascanopyPro.PRODUCTS, 0))
     self.addParameter(
         ParameterSelection(lascanopyPro.PRODUCT4, self.tr("create"),
                            lascanopyPro.PRODUCTS, 0))
     self.addParameter(
         ParameterSelection(lascanopyPro.PRODUCT5, self.tr("create"),
                            lascanopyPro.PRODUCTS, 0))
     self.addParameter(
         ParameterSelection(lascanopyPro.PRODUCT6, self.tr("create"),
                            lascanopyPro.PRODUCTS, 0))
     self.addParameter(
         ParameterSelection(lascanopyPro.PRODUCT7, self.tr("create"),
                            lascanopyPro.PRODUCTS, 0))
     self.addParameter(
         ParameterSelection(lascanopyPro.PRODUCT8, self.tr("create"),
                            lascanopyPro.PRODUCTS, 0))
     self.addParameter(
         ParameterSelection(lascanopyPro.PRODUCT9, self.tr("create"),
                            lascanopyPro.PRODUCTS, 0))
     self.addParameter(
         ParameterString(lascanopyPro.COUNTS,
                         self.tr("count rasters (e.g. 2.0 5.0 10.0 20.0)"),
                         ""))
     self.addParameter(
         ParameterString(
             lascanopyPro.DENSITIES,
             self.tr("density rasters (e.g. 2.0 5.0 10.0 20.0)"), ""))
     self.addParameter(
         ParameterBoolean(
             lascanopyPro.USE_TILE_BB,
             self.tr("use tile bounding box (after tiling with buffer)"),
             False))
     self.addParameter(
         ParameterBoolean(lascanopyPro.FILES_ARE_PLOTS,
                          self.tr("input file is single plot"), False))
     self.addParametersOutputDirectoryGUI()
     self.addParametersOutputAppendixGUI()
     self.addParametersRasterOutputFormatGUI()
     self.addParametersRasterOutputGUI()
     self.addParametersAdditionalGUI()
     self.addParametersCoresGUI()
     self.addParametersVerboseGUI()
Exemplo n.º 13
0
 def testSetValue(self):
     parameter = ParameterNumber('myName', 'myDescription')
     self.assertTrue(parameter.setValue(5))
     self.assertEqual(parameter.value, 5)
Exemplo n.º 14
0
    def defineCharacteristics(self):
        self.addParameter(
            ParameterVector(self.INPUT_LAYER, self.tr('Point layer'),
                            [dataobjects.TYPE_VECTOR_POINT]))
        self.addParameter(
            ParameterNumber(self.RADIUS, self.tr('Radius (layer units)'), 0.0,
                            9999999999, 100.0))

        radius_field_param = ParameterTableField(
            self.RADIUS_FIELD,
            self.tr('Radius from field'),
            self.INPUT_LAYER,
            optional=True,
            datatype=ParameterTableField.DATA_TYPE_NUMBER)
        radius_field_param.isAdvanced = True
        self.addParameter(radius_field_param)

        class ParameterHeatmapPixelSize(ParameterNumber):
            def __init__(self,
                         name='',
                         description='',
                         parent_layer=None,
                         radius_param=None,
                         radius_field_param=None,
                         minValue=None,
                         maxValue=None,
                         default=None,
                         optional=False,
                         metadata={}):
                ParameterNumber.__init__(self, name, description, minValue,
                                         maxValue, default, optional, metadata)
                self.parent_layer = parent_layer
                self.radius_param = radius_param
                self.radius_field_param = radius_field_param

        self.addParameter(
            ParameterHeatmapPixelSize(
                self.PIXEL_SIZE,
                self.tr('Output raster size'),
                parent_layer=self.INPUT_LAYER,
                radius_param=self.RADIUS,
                radius_field_param=self.RADIUS_FIELD,
                minValue=0.0,
                maxValue=9999999999,
                default=0.1,
                metadata={'widget_wrapper': HeatmapPixelSizeWidgetWrapper}))

        weight_field_param = ParameterTableField(
            self.WEIGHT_FIELD,
            self.tr('Weight from field'),
            self.INPUT_LAYER,
            optional=True,
            datatype=ParameterTableField.DATA_TYPE_NUMBER)
        weight_field_param.isAdvanced = True
        self.addParameter(weight_field_param)
        kernel_shape_param = ParameterSelection(self.KERNEL,
                                                self.tr('Kernel shape'),
                                                self.KERNELS)
        kernel_shape_param.isAdvanced = True
        self.addParameter(kernel_shape_param)
        decay_ratio = ParameterNumber(
            self.DECAY, self.tr('Decay ratio (Triangular kernels only)'),
            -100.0, 100.0, 0.0)
        decay_ratio.isAdvanced = True
        self.addParameter(decay_ratio)
        output_scaling = ParameterSelection(self.OUTPUT_VALUE,
                                            self.tr('Output value scaling'),
                                            self.OUTPUT_VALUES)
        output_scaling.isAdvanced = True
        self.addParameter(output_scaling)
        self.addOutput(OutputRaster(self.OUTPUT_LAYER, self.tr('Heatmap')))
Exemplo n.º 15
0
    def defineCharacteristicsFromFile(self):
        with open(self.descriptionFile) as lines:
            line = lines.readline().strip('\n').strip()
            self.grass7Name = line
            line = lines.readline().strip('\n').strip()
            self._name = line
            self._display_name = QCoreApplication.translate("GrassAlgorithm", line)
            if " - " not in self._name:
                self._name = self.grass7Name + " - " + self._name
                self._display_name = self.grass7Name + " - " + self._display_name

            self._name = self._name[:self._name.find(' ')].lower()

            line = lines.readline().strip('\n').strip()
            self._group = QCoreApplication.translate("GrassAlgorithm", line)
            hasRasterOutput = False
            hasVectorInput = False
            vectorOutputs = 0
            line = lines.readline().strip('\n').strip()
            while line != '':
                try:
                    line = line.strip('\n').strip()
                    if line.startswith('Hardcoded'):
                        self.hardcodedStrings.append(line[len('Hardcoded|'):])
                    parameter = getParameterFromString(line)
                    if parameter is not None:
                        self.addParameter(parameter)
                        if isinstance(parameter, ParameterVector):
                            hasVectorInput = True
                        if isinstance(parameter, ParameterMultipleInput) \
                           and parameter.datatype < 3:
                            hasVectorInput = True
                    else:
                        output = getOutputFromString(line)
                        self.addOutput(output)
                        if isinstance(output, OutputRaster):
                            hasRasterOutput = True
                        elif isinstance(output, OutputVector):
                            vectorOutputs += 1
                        if isinstance(output, OutputHTML):
                            self.addOutput(OutputFile("rawoutput",
                                                      self.tr("{0} (raw output)").format(output.description()),
                                                      "txt"))
                    line = lines.readline().strip('\n').strip()
                except Exception as e:
                    QgsMessageLog.logMessage(self.tr('Could not open GRASS GIS 7 algorithm: {0}\n{1}').format(self.descriptionFile, line), self.tr('Processing'), QgsMessageLog.CRITICAL)
                    raise e

        self.addParameter(ParameterExtent(
            self.GRASS_REGION_EXTENT_PARAMETER,
            self.tr('GRASS GIS 7 region extent'))
        )
        if hasRasterOutput:
            self.addParameter(ParameterNumber(
                self.GRASS_REGION_CELLSIZE_PARAMETER,
                self.tr('GRASS GIS 7 region cellsize (leave 0 for default)'),
                0, None, 0.0))
        if hasVectorInput:
            param = ParameterNumber(self.GRASS_SNAP_TOLERANCE_PARAMETER,
                                    'v.in.ogr snap tolerance (-1 = no snap)',
                                    -1, None, -1.0)
            param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
            self.addParameter(param)
            param = ParameterNumber(self.GRASS_MIN_AREA_PARAMETER,
                                    'v.in.ogr min area', 0, None, 0.0001)
            param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
            self.addParameter(param)
        if vectorOutputs == 1:
            param = ParameterSelection(self.GRASS_OUTPUT_TYPE_PARAMETER,
                                       'v.out.ogr output type',
                                       self.OUTPUT_TYPES)
            param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
            self.addParameter(param)
Exemplo n.º 16
0
    def processParameterLine(self, line):
        param = None
        out = None
        line = line.replace('#', '')

        # If the line is in the format of the text description files for
        # normal algorithms, then process it using parameter and output
        # factories
        if '|' in line:
            self.processDescriptionParameterLine(line)
            return
        if line == "nomodeler":
            self.showInModeler = False
            return
        tokens = line.split('=', 1)
        desc = self.createDescriptiveName(tokens[0])
        if tokens[1].lower().strip() == 'group':
            self.group = tokens[0]
            return
        if tokens[1].lower().strip() == 'name':
            self.name = tokens[0]
            return
        if tokens[1].lower().strip() == 'raster':
            param = ParameterRaster(tokens[0], desc, False)
        elif tokens[1].lower().strip() == 'vector':
            param = ParameterVector(tokens[0], desc,
                                    [ParameterVector.VECTOR_TYPE_ANY])
        elif tokens[1].lower().strip() == 'vector point':
            param = ParameterVector(tokens[0], desc,
                                    [ParameterVector.VECTOR_TYPE_POINT])
        elif tokens[1].lower().strip() == 'vector line':
            param = ParameterVector(tokens[0], desc,
                                    [ParameterVector.VECTOR_TYPE_LINE])
        elif tokens[1].lower().strip() == 'vector polygon':
            param = ParameterVector(tokens[0], desc,
                                    [ParameterVector.VECTOR_TYPE_POLYGON])
        elif tokens[1].lower().strip() == 'table':
            param = ParameterTable(tokens[0], desc, False)
        elif tokens[1].lower().strip() == 'multiple raster':
            param = ParameterMultipleInput(tokens[0], desc,
                                           ParameterMultipleInput.TYPE_RASTER)
            param.optional = False
        elif tokens[1].lower().strip() == 'multiple vector':
            param = ParameterMultipleInput(
                tokens[0], desc, ParameterMultipleInput.TYPE_VECTOR_ANY)
            param.optional = False
        elif tokens[1].lower().strip().startswith('selection'):
            options = tokens[1].strip()[len('selection '):].split(';')
            param = ParameterSelection(tokens[0], desc, options)
        elif tokens[1].lower().strip().startswith('boolean'):
            default = tokens[1].strip()[len('boolean') + 1:]
            param = ParameterBoolean(tokens[0], desc, default)
        elif tokens[1].lower().strip() == 'extent':
            param = ParameterExtent(tokens[0], desc)
        elif tokens[1].lower().strip() == 'file':
            param = ParameterFile(tokens[0], desc, False)
        elif tokens[1].lower().strip() == 'folder':
            param = ParameterFile(tokens[0], desc, True)
        elif tokens[1].lower().strip().startswith('number'):
            default = tokens[1].strip()[len('number') + 1:]
            param = ParameterNumber(tokens[0], desc, default=default)
        elif tokens[1].lower().strip().startswith('field'):
            field = tokens[1].strip()[len('field') + 1:]
            found = False
            for p in self.parameters:
                if p.name == field:
                    found = True
                    break
            if found:
                param = ParameterTableField(tokens[0], desc, field)
        elif tokens[1].lower().strip().startswith('string'):
            default = tokens[1].strip()[len('string') + 1:]
            param = ParameterString(tokens[0], desc, default)
        elif tokens[1].lower().strip().startswith('longstring'):
            default = tokens[1].strip()[len('longstring') + 1:]
            param = ParameterString(tokens[0], desc, default, multiline=True)
        elif tokens[1].lower().strip().startswith('crs'):
            default = tokens[1].strip()[len('crs') + 1:]
            if not default:
                default = 'EPSG:4326'
            param = ParameterCrs(tokens[0], desc, default)
        elif tokens[1].lower().strip().startswith('output raster'):
            out = OutputRaster()
        elif tokens[1].lower().strip().startswith('output vector'):
            out = OutputVector()
        elif tokens[1].lower().strip().startswith('output table'):
            out = OutputTable()
        elif tokens[1].lower().strip().startswith('output html'):
            out = OutputHTML()
        elif tokens[1].lower().strip().startswith('output file'):
            out = OutputFile()
            subtokens = tokens[1].split(' ')
            if len(subtokens) > 2:
                out.ext = subtokens[2]
        elif tokens[1].lower().strip().startswith('output directory'):
            out = OutputDirectory()
        elif tokens[1].lower().strip().startswith('output number'):
            out = OutputNumber()
        elif tokens[1].lower().strip().startswith('output string'):
            out = OutputString()

        if param is not None:
            self.addParameter(param)
        elif out is not None:
            out.name = tokens[0]
            out.description = desc
            self.addOutput(out)
        else:
            raise WrongScriptException(
                self.tr('Could not load script: %s.\n'
                        'Problem with line %d', 'ScriptAlgorithm') %
                (self.descriptionFile or '', line))
Exemplo n.º 17
0
    def defineCharacteristicsFromFile(self):
        with open(self.descriptionFile) as lines:
            line = lines.readline().strip('\n').strip()
            self.grass7Name = line
            line = lines.readline().strip('\n').strip()
            self.name = line
            self.i18n_name = QCoreApplication.translate("GrassAlgorithm", line)
            if " - " not in self.name:
                self.name = self.grass7Name + " - " + self.name
                self.i18n_name = self.grass7Name + " - " + self.i18n_name
            line = lines.readline().strip('\n').strip()
            self.group = line
            self.i18n_group = QCoreApplication.translate(
                "GrassAlgorithm", line)
            hasRasterOutput = False
            hasVectorInput = False
            vectorOutputs = 0
            line = lines.readline().strip('\n').strip()
            while line != '':
                try:
                    line = line.strip('\n').strip()
                    if line.startswith('Hardcoded'):
                        self.hardcodedStrings.append(line[len('Hardcoded|'):])
                    parameter = getParameterFromString(line)
                    if parameter is not None:
                        self.addParameter(parameter)
                        if isinstance(parameter, ParameterVector):
                            hasVectorInput = True
                        if isinstance(parameter, ParameterMultipleInput) \
                           and parameter.datatype < 3:
                            hasVectorInput = True
                    else:
                        output = getOutputFromString(line)
                        self.addOutput(output)
                        if isinstance(output, OutputRaster):
                            hasRasterOutput = True
                        elif isinstance(output, OutputVector):
                            vectorOutputs += 1
                        if isinstance(output, OutputHTML):
                            self.addOutput(
                                OutputFile(
                                    "rawoutput",
                                    self.tr("{0} (raw output)").format(
                                        output.description), "txt"))
                    line = lines.readline().strip('\n').strip()
                except Exception as e:
                    ProcessingLog.addToLog(
                        ProcessingLog.LOG_ERROR,
                        self.tr(
                            'Could not open GRASS GIS 7 algorithm: {0}\n{1}').
                        format(self.descriptionFile, line))
                    raise e

        self.addParameter(
            ParameterExtent(self.GRASS_REGION_EXTENT_PARAMETER,
                            self.tr('GRASS GIS 7 region extent')))
        if hasRasterOutput:
            self.addParameter(
                ParameterNumber(
                    self.GRASS_REGION_CELLSIZE_PARAMETER,
                    self.tr(
                        'GRASS GIS 7 region cellsize (leave 0 for default)'),
                    0, None, 0.0))
        if hasVectorInput:
            param = ParameterNumber(self.GRASS_SNAP_TOLERANCE_PARAMETER,
                                    'v.in.ogr snap tolerance (-1 = no snap)',
                                    -1, None, -1.0)
            param.isAdvanced = True
            self.addParameter(param)
            param = ParameterNumber(self.GRASS_MIN_AREA_PARAMETER,
                                    'v.in.ogr min area', 0, None, 0.0001)
            param.isAdvanced = True
            self.addParameter(param)
        if vectorOutputs == 1:
            param = ParameterSelection(self.GRASS_OUTPUT_TYPE_PARAMETER,
                                       'v.out.ogr output type',
                                       self.OUTPUT_TYPES)
            param.isAdvanced = True
            self.addParameter(param)
Exemplo n.º 18
0
 def testSetValue(self):
     parameter = ParameterNumber('myName', 'myDescription')
     self.assertTrue(parameter.setValue(5))
     self.assertEquals(parameter.value, 5)
Exemplo n.º 19
0
    def defineCharacteristics(self):
        # Required parameters
        self.addParameter(
            ParameterMultipleInput(self.INPUT, self.tr('Input layers'),
                                   dataobjects.TYPE_RASTER))
        # Advanced parameters
        params = []
        params.append(
            ParameterString(
                self.PIXELSIZE,
                self.
                tr('Pixel size to be used for the output file (XSIZE YSIZE like 512 512)'
                   ), None, False, True))
        params.append(
            ParameterSelection(self.ALGORITHM,
                               self.tr('Resampling algorithm'),
                               self.ALGO,
                               0,
                               False,
                               optional=True))
        params.append(
            ParameterCrs(self.S_SRS, self.tr('Override source CRS'), None,
                         True))
        params.append(
            ParameterNumber(self.PYRAMIDLEVELS,
                            self.tr('Number of pyramids levels to build'),
                            None, None, None, True))
        params.append(
            ParameterBoolean(self.ONLYPYRAMIDS,
                             self.tr('Build only the pyramids'), False, True))
        params.append(
            ParameterSelection(self.RTYPE,
                               self.tr('Output raster type'),
                               self.TYPE,
                               5,
                               False,
                               optional=True))
        params.append(
            ParameterSelection(self.FORMAT,
                               self.tr('Output raster format'),
                               list(GdalUtils.getSupportedRasters().keys()),
                               0,
                               False,
                               optional=True))
        params.append(
            ParameterBoolean(self.USEDIRFOREACHROW,
                             self.tr('Use a directory for each row'), False,
                             True))
        params.append(
            ParameterString(
                self.CSVFILE,
                self.
                tr('Name of the csv file containing the tile(s) georeferencing information'
                   ), None, False, True))
        params.append(
            ParameterString(self.CSVDELIM,
                            self.tr('Column delimiter used in the CSV file'),
                            None, False, True))
        params.append(
            ParameterString(
                self.TILEINDEX,
                self.tr(
                    'name of shape file containing the result tile(s) index'),
                None, False, True))
        params.append(
            ParameterString(
                self.TILEINDEXFIELD,
                self.
                tr('name of the attribute containing the tile name in the result shape file'
                   ), None, False, True))

        for param in params:
            param.isAdvanced = True
            self.addParameter(param)

        self.addOutput(
            OutputDirectory(
                self.TARGETDIR,
                self.tr('The directory where the tile result is created')))
Exemplo n.º 20
0
    def defineCharacteristics(self):
        self.name, self.i18n_name = self.trAlgorithm(
            'Clip raster by mask layer')
        self.group, self.i18n_group = self.trAlgorithm('[GDAL] Extraction')
        self.addParameter(
            ParameterRaster(self.INPUT, self.tr('Input layer'), False))
        self.addParameter(
            ParameterVector(self.MASK, self.tr('Mask layer'),
                            [dataobjects.TYPE_VECTOR_POLYGON]))
        self.addParameter(
            ParameterString(
                self.NO_DATA,
                self.
                tr("Nodata value, leave blank to take the nodata value from input"
                   ),
                '',
                optional=True))
        self.addParameter(
            ParameterBoolean(self.ALPHA_BAND,
                             self.tr('Create and output alpha band'), False))
        self.addParameter(
            ParameterBoolean(
                self.CROP_TO_CUTLINE,
                self.
                tr('Crop the extent of the target dataset to the extent of the cutline'
                   ), True))
        self.addParameter(
            ParameterBoolean(self.KEEP_RESOLUTION,
                             self.tr('Keep resolution of output raster'),
                             False))

        params = []
        params.append(
            ParameterSelection(self.RTYPE, self.tr('Output raster type'),
                               self.TYPE, 5))
        params.append(
            ParameterSelection(self.COMPRESS,
                               self.tr('GeoTIFF options. Compression type:'),
                               self.COMPRESSTYPE, 4))
        params.append(
            ParameterNumber(self.JPEGCOMPRESSION,
                            self.tr('Set the JPEG compression level'), 1, 100,
                            75))
        params.append(
            ParameterNumber(self.ZLEVEL,
                            self.tr('Set the DEFLATE compression level'), 1, 9,
                            6))
        params.append(
            ParameterNumber(
                self.PREDICTOR,
                self.tr('Set the predictor for LZW or DEFLATE compression'), 1,
                3, 1))
        params.append(
            ParameterBoolean(
                self.TILED,
                self.tr(
                    'Create tiled output (only used for the GTiff format)'),
                False))
        params.append(
            ParameterSelection(
                self.BIGTIFF,
                self.
                tr('Control whether the created file is a BigTIFF or a classic TIFF'
                   ), self.BIGTIFFTYPE, 0))
        params.append(
            ParameterBoolean(
                self.TFW,
                self.
                tr('Force the generation of an associated ESRI world file (.tfw))'
                   ), False))
        params.append(
            ParameterString(self.EXTRA,
                            self.tr('Additional creation parameters'),
                            '',
                            optional=True))

        for param in params:
            param.isAdvanced = True
            self.addParameter(param)

        self.addOutput(OutputRaster(self.OUTPUT, self.tr('Clipped (mask)')))
Exemplo n.º 21
0
    def defineCharacteristics(self):
        self.DIRECTIONS = OrderedDict([
            (self.tr('Forward direction'),
             QgsVectorLayerDirector.DirectionForward),
            (self.tr('Backward direction'),
             QgsVectorLayerDirector.DirectionForward),
            (self.tr('Both directions'),
             QgsVectorLayerDirector.DirectionForward)
        ])

        self.STRATEGIES = [self.tr('Shortest'), self.tr('Fastest')]

        self.name, self.i18n_name = self.trAlgorithm(
            'Service area (from layer)')
        self.group, self.i18n_group = self.trAlgorithm('Network analysis')

        self.addParameter(
            ParameterVector(self.INPUT_VECTOR,
                            self.tr('Vector layer representing network'),
                            [dataobjects.TYPE_VECTOR_LINE]))
        self.addParameter(
            ParameterVector(self.START_POINTS,
                            self.tr('Vector layer with start points'),
                            [dataobjects.TYPE_VECTOR_POINT]))
        self.addParameter(
            ParameterSelection(self.STRATEGY,
                               self.tr('Path type to calculate'),
                               self.STRATEGIES,
                               default=0))
        self.addParameter(
            ParameterNumber(
                self.TRAVEL_COST,
                self.tr(
                    'Travel cost (distance for "Shortest", time for "Fastest")'
                ), 0.0, 99999999.999999, 0.0))

        params = []
        params.append(
            ParameterTableField(self.DIRECTION_FIELD,
                                self.tr('Direction field'),
                                self.INPUT_VECTOR,
                                optional=True))
        params.append(
            ParameterString(self.VALUE_FORWARD,
                            self.tr('Value for forward direction'),
                            '',
                            optional=True))
        params.append(
            ParameterString(self.VALUE_BACKWARD,
                            self.tr('Value for backward direction'),
                            '',
                            optional=True))
        params.append(
            ParameterString(self.VALUE_BOTH,
                            self.tr('Value for both directions'),
                            '',
                            optional=True))
        params.append(
            ParameterSelection(self.DEFAULT_DIRECTION,
                               self.tr('Default direction'),
                               list(self.DIRECTIONS.keys()),
                               default=2))
        params.append(
            ParameterTableField(self.SPEED_FIELD,
                                self.tr('Speed field'),
                                self.INPUT_VECTOR,
                                optional=True))
        params.append(
            ParameterNumber(self.DEFAULT_SPEED,
                            self.tr('Default speed (km/h)'), 0.0,
                            99999999.999999, 5.0))
        params.append(
            ParameterNumber(self.TOLERANCE, self.tr('Topology tolerance'), 0.0,
                            99999999.999999, 0.0))

        for p in params:
            p.isAdvanced = True
            self.addParameter(p)

        self.addOutput(
            OutputVector(self.OUTPUT_POINTS,
                         self.tr('Service area (boundary nodes)'),
                         datatype=[dataobjects.TYPE_VECTOR_POINT]))
        self.addOutput(
            OutputVector(self.OUTPUT_POLYGON,
                         self.tr('Service area (convex hull)'),
                         datatype=[dataobjects.TYPE_VECTOR_POLYGON]))
Exemplo n.º 22
0
 def testMaxValue(self):
     parameter = ParameterNumber('myName', 'myDescription', maxValue=10)
     self.assertFalse(parameter.setValue(11))
     self.assertEqual(parameter.value, None)
     self.assertTrue(parameter.setValue(10))
     self.assertEqual(parameter.value, 10)
Exemplo n.º 23
0
 def testSetValueOnlyValidNumbers(self):
     parameter = ParameterNumber('myName', 'myDescription')
     self.assertFalse(parameter.setValue('not a number'))
     self.assertEqual(parameter.value, None)
Exemplo n.º 24
0
    def defineCharacteristics(self):
        self.name, self.i18n_name = self.trAlgorithm('Relief')
        self.group, self.i18n_group = self.trAlgorithm(
            'Raster terrain analysis')

        class ParameterReliefColors(Parameter):
            default_metadata = {
                'widget_wrapper':
                'processing.algs.qgis.ui.ReliefColorsWidget.ReliefColorsWidgetWrapper'
            }

            def __init__(self,
                         name='',
                         description='',
                         parent=None,
                         optional=True):
                Parameter.__init__(self, name, description, None, optional)
                self.parent = parent

            def setValue(self, value):
                if value is None:
                    if not self.optional:
                        return False
                    self.value = None
                    return True

                if value == '':
                    if not self.optional:
                        return False

                if isinstance(value, str):
                    self.value = value if value != '' else None
                else:
                    self.value = ParameterReliefColors.colorsToString(value)
                return True

            def getValueAsCommandLineParameter(self):
                return '"{}"'.format(self.value)

            def getAsScriptCode(self):
                param_type = ''
                param_type += 'relief colors '
                return '##' + self.name + '=' + param_type

            @classmethod
            def fromScriptCode(self, line):
                isOptional, name, definition = _splitParameterOptions(line)
                descName = _createDescriptiveName(name)
                parent = definition.lower().strip()[len('relief colors') + 1:]
                return ParameterReliefColors(name, descName, parent)

            @staticmethod
            def colorsToString(colors):
                s = ''
                for c in colors:
                    s += '{:f}, {:f}, {:d}, {:d}, {:d};'.format(
                        c[0], c[1], c[2], c[3], c[4])
                return s[:-1]

        self.addParameter(
            ParameterRaster(self.INPUT_LAYER, self.tr('Elevation layer')))
        self.addParameter(
            ParameterNumber(self.Z_FACTOR, self.tr('Z factor'), 1.0, 999999.99,
                            1.0))
        self.addParameter(
            ParameterBoolean(self.AUTO_COLORS,
                             self.tr('Generate relief classes automatically'),
                             False))
        self.addParameter(
            ParameterReliefColors(self.COLORS, self.tr('Relief colors'),
                                  self.INPUT_LAYER, True))
        self.addOutput(OutputRaster(self.OUTPUT_LAYER, self.tr('Relief')))
        self.addOutput(
            OutputTable(self.FREQUENCY_DISTRIBUTION,
                        self.tr('Frequency distribution')))
Exemplo n.º 25
0
 def testSetValue(self):
     parameter = ParameterNumber("myName", "myDescription")
     self.assertTrue(parameter.setValue(5))
     self.assertEqual(parameter.value, 5)
Exemplo n.º 26
0
class GrassAlgorithm(GeoAlgorithm):

    GRASS_OUTPUT_TYPE_PARAMETER = 'GRASS_OUTPUT_TYPE_PARAMETER'
    GRASS_MIN_AREA_PARAMETER = 'GRASS_MIN_AREA_PARAMETER'
    GRASS_SNAP_TOLERANCE_PARAMETER = 'GRASS_SNAP_TOLERANCE_PARAMETER'
    GRASS_REGION_EXTENT_PARAMETER = 'GRASS_REGION_PARAMETER'
    GRASS_REGION_CELLSIZE_PARAMETER = 'GRASS_REGION_CELLSIZE_PARAMETER'
    GRASS_REGION_ALIGN_TO_RESOLUTION = '-a_r.region'

    OUTPUT_TYPES = ['auto', 'point', 'line', 'area']

    def __init__(self, descriptionfile):
        GeoAlgorithm.__init__(self)
        self.descriptionFile = descriptionfile
        self.defineCharacteristicsFromFile()
        self.numExportedLayers = 0

        # GRASS console output, needed to do postprocessing in case GRASS
        # dumps results to the console
        self.consoleOutput = []

    def getCopy(self):
        newone = GrassAlgorithm(self.descriptionFile)
        newone.provider = self.provider
        return newone

    def getIcon(self):
        return QIcon(os.path.join(pluginPath, 'images', 'grass.png'))

    def help(self):
        return False, 'http://grass.osgeo.org/grass64/manuals/' + self.grassName + '.html'

    def getParameterDescriptions(self):
        descs = {}
        _, helpfile = self.help()
        try:
            infile = open(helpfile)
            lines = infile.readlines()
            for i in range(len(lines)):
                if lines[i].startswith('<DT><b>'):
                    for param in self.parameters:
                        searchLine = '<b>' + param.name + '</b>'
                        if searchLine in lines[i]:
                            i += 1
                            descs[param.name] = (lines[i])[4:-6]
                            break

            infile.close()
        except Exception:
            pass
        return descs

    def defineCharacteristicsFromFile(self):
        lines = open(self.descriptionFile)
        line = lines.readline().strip('\n').strip()
        self.grassName = line
        line = lines.readline().strip('\n').strip()
        self.name = line
        line = lines.readline().strip('\n').strip()
        self.group = line
        hasRasterOutput = False
        hasVectorInput = False
        vectorOutputs = 0
        line = lines.readline().strip('\n').strip()
        while line != '':
            try:
                line = line.strip('\n').strip()
                if line.startswith('Parameter'):
                    parameter = getParameterFromString(line)
                    self.addParameter(parameter)
                    if isinstance(parameter, ParameterVector):
                        hasVectorInput = True
                    if isinstance(parameter, ParameterMultipleInput) \
                       and parameter.datatype < 3:
                        hasVectorInput = True
                elif line.startswith('*Parameter'):
                    param = getParameterFromString(line[1:])
                    param.isAdvanced = True
                    self.addParameter(param)
                else:
                    output = getOutputFromString(line)
                    self.addOutput(output)
                    if isinstance(output, OutputRaster):
                        hasRasterOutput = True
                    elif isinstance(output, OutputVector):
                        vectorOutputs += 1
                line = lines.readline().strip('\n').strip()
            except Exception, e:
                ProcessingLog.addToLog(
                    ProcessingLog.LOG_ERROR,
                    self.tr('Could not open GRASS algorithm: %s.\n%s' %
                            (self.descriptionFile, line)))
                raise e
        lines.close()

        self.addParameter(
            ParameterExtent(self.GRASS_REGION_EXTENT_PARAMETER,
                            self.tr('GRASS region extent')))
        if hasRasterOutput:
            self.addParameter(
                ParameterNumber(
                    self.GRASS_REGION_CELLSIZE_PARAMETER,
                    self.tr('GRASS region cellsize (leave 0 for default)'), 0,
                    None, 0.0))
        if hasVectorInput:
            param = ParameterNumber(self.GRASS_SNAP_TOLERANCE_PARAMETER,
                                    'v.in.ogr snap tolerance (-1 = no snap)',
                                    -1, None, -1.0)
            param.isAdvanced = True
            self.addParameter(param)
            param = ParameterNumber(self.GRASS_MIN_AREA_PARAMETER,
                                    'v.in.ogr min area', 0, None, 0.0001)
            param.isAdvanced = True
            self.addParameter(param)
        if vectorOutputs == 1:
            param = ParameterSelection(self.GRASS_OUTPUT_TYPE_PARAMETER,
                                       'v.out.ogr output type',
                                       self.OUTPUT_TYPES)
            param.isAdvanced = True
            self.addParameter(param)
Exemplo n.º 27
0
 def testMaxValue(self):
     parameter = ParameterNumber("myName", "myDescription", maxValue=10)
     self.assertFalse(parameter.setValue(11))
     self.assertEqual(parameter.value, None)
     self.assertTrue(parameter.setValue(10))
     self.assertEqual(parameter.value, 10)
Exemplo n.º 28
0
    def defineCharacteristics(self):
        self.name, self.i18n_name = self.trAlgorithm('IDW interpolation')
        self.group, self.i18n_group = self.trAlgorithm('Interpolation')

        class ParameterInterpolationData(Parameter):
            default_metadata = {
                'widget_wrapper':
                'processing.algs.qgis.ui.InterpolationDataWidget.InterpolationDataWidgetWrapper'
            }

            def __init__(self, name='', description=''):
                Parameter.__init__(self, name, description)

            def setValue(self, value):
                if value is None:
                    if not self.optional:
                        return False
                    self.value = None
                    return True

                if value == '':
                    if not self.optional:
                        return False

                if isinstance(value, str):
                    self.value = value if value != '' else None
                else:
                    self.value = ParameterInterpolationData.dataToString(value)
                return True

            def getValueAsCommandLineParameter(self):
                return '"{}"'.format(self.value)

            def getAsScriptCode(self):
                param_type = ''
                param_type += 'interpolation data '
                return '##' + self.name + '=' + param_type

            @classmethod
            def fromScriptCode(self, line):
                isOptional, name, definition = _splitParameterOptions(line)
                descName = _createDescriptiveName(name)
                parent = definition.lower().strip()[len('interpolation data') +
                                                    1:]
                return ParameterInterpolationData(name, description, parent)

            @staticmethod
            def dataToString(data):
                s = ''
                for d in data:
                    s += '{}, {}, {:d}, {:d};'.format(c[0], c[1], c[2], c[3])
                return s[:-1]

        self.addParameter(
            ParameterInterpolationData(self.INTERPOLATION_DATA,
                                       self.tr('Input layer(s)')))
        self.addParameter(
            ParameterNumber(self.DISTANCE_COEFFICIENT,
                            self.tr('Distance coefficient P'), 0.0, 99.99,
                            2.0))
        self.addParameter(
            ParameterNumber(self.COLUMNS, self.tr('Number of columns'), 0,
                            10000000, 300))
        self.addParameter(
            ParameterNumber(self.ROWS, self.tr('Number of rows'), 0, 10000000,
                            300))
        self.addParameter(
            ParameterNumber(self.CELLSIZE_X, self.tr('Cell Size X'), 0.0,
                            999999.000000, 0.0))
        self.addParameter(
            ParameterNumber(self.CELLSIZE_Y, self.tr('Cell Size Y'), 0.0,
                            999999.000000, 0.0))
        self.addParameter(
            ParameterExtent(self.EXTENT, self.tr('Extent'), optional=False))
        self.addOutput(OutputRaster(self.OUTPUT_LAYER,
                                    self.tr('Interpolated')))
Exemplo n.º 29
0
    def defineCharacteristics(self):
        self.name, self.i18n_name = self.trAlgorithm(
            'Translate (convert format)')
        self.group, self.i18n_group = self.trAlgorithm('[GDAL] Conversion')
        self.addParameter(
            ParameterRaster(self.INPUT, self.tr('Input layer'), False))
        self.addParameter(
            ParameterNumber(
                self.OUTSIZE,
                self.tr('Set the size of the output file (In pixels or %)'), 1,
                None, 100))
        self.addParameter(
            ParameterBoolean(
                self.OUTSIZE_PERC,
                self.tr('Output size is a percentage of input size'), True))
        self.addParameter(
            ParameterString(
                self.NO_DATA,
                self.
                tr("Nodata value, leave blank to take the nodata value from input"
                   ),
                '',
                optional=True))
        self.addParameter(
            ParameterSelection(self.EXPAND, self.tr('Expand'),
                               ['none', 'gray', 'rgb', 'rgba']))
        self.addParameter(
            ParameterCrs(
                self.SRS,
                self.
                tr('Output projection for output file [leave blank to use input projection]'
                   ),
                None,
                optional=True))
        self.addParameter(
            ParameterExtent(
                self.PROJWIN,
                self.tr('Subset based on georeferenced coordinates')))
        self.addParameter(
            ParameterBoolean(
                self.SDS,
                self.
                tr('Copy all subdatasets of this file to individual output files'
                   ), False))

        params = []
        params.append(
            ParameterSelection(self.RTYPE, self.tr('Output raster type'),
                               self.TYPE, 5))
        params.append(
            ParameterSelection(self.COMPRESS,
                               self.tr('GeoTIFF options. Compression type:'),
                               self.COMPRESSTYPE, 4))
        params.append(
            ParameterNumber(self.JPEGCOMPRESSION,
                            self.tr('Set the JPEG compression level'), 1, 100,
                            75))
        params.append(
            ParameterNumber(self.ZLEVEL,
                            self.tr('Set the DEFLATE compression level'), 1, 9,
                            6))
        params.append(
            ParameterNumber(
                self.PREDICTOR,
                self.tr('Set the predictor for LZW or DEFLATE compression'), 1,
                3, 1))
        params.append(
            ParameterBoolean(
                self.TILED,
                self.tr(
                    'Create tiled output (only used for the GTiff format)'),
                False))
        params.append(
            ParameterSelection(
                self.BIGTIFF,
                self.
                tr('Control whether the created file is a BigTIFF or a classic TIFF'
                   ), self.BIGTIFFTYPE, 0))
        params.append(
            ParameterBoolean(
                self.TFW,
                self.
                tr('Force the generation of an associated ESRI world file (.tfw))'
                   ), False))
        params.append(
            ParameterString(self.EXTRA,
                            self.tr('Additional creation parameters'),
                            '',
                            optional=True))

        for param in params:
            param.isAdvanced = True
            self.addParameter(param)

        self.addOutput(OutputRaster(self.OUTPUT, self.tr('Converted')))
Exemplo n.º 30
0
    def __init__(self):
        super().__init__()
        self.DIRECTIONS = OrderedDict([
            (self.tr('Forward direction'),
             QgsVectorLayerDirector.DirectionForward),
            (self.tr('Backward direction'),
             QgsVectorLayerDirector.DirectionForward),
            (self.tr('Both directions'),
             QgsVectorLayerDirector.DirectionForward)
        ])

        self.STRATEGIES = [self.tr('Shortest'), self.tr('Fastest')]

        self.addParameter(
            ParameterVector(self.INPUT_VECTOR,
                            self.tr('Vector layer representing network'),
                            [dataobjects.TYPE_VECTOR_LINE]))
        self.addParameter(
            ParameterPoint(self.START_POINT, self.tr('Start point')))
        self.addParameter(
            ParameterVector(self.END_POINTS,
                            self.tr('Vector layer with end points'),
                            [dataobjects.TYPE_VECTOR_POINT]))
        self.addParameter(
            ParameterSelection(self.STRATEGY,
                               self.tr('Path type to calculate'),
                               self.STRATEGIES,
                               default=0))

        params = []
        params.append(
            ParameterTableField(self.DIRECTION_FIELD,
                                self.tr('Direction field'),
                                self.INPUT_VECTOR,
                                optional=True))
        params.append(
            ParameterString(self.VALUE_FORWARD,
                            self.tr('Value for forward direction'),
                            '',
                            optional=True))
        params.append(
            ParameterString(self.VALUE_BACKWARD,
                            self.tr('Value for backward direction'),
                            '',
                            optional=True))
        params.append(
            ParameterString(self.VALUE_BOTH,
                            self.tr('Value for both directions'),
                            '',
                            optional=True))
        params.append(
            ParameterSelection(self.DEFAULT_DIRECTION,
                               self.tr('Default direction'),
                               list(self.DIRECTIONS.keys()),
                               default=2))
        params.append(
            ParameterTableField(self.SPEED_FIELD,
                                self.tr('Speed field'),
                                self.INPUT_VECTOR,
                                optional=True))
        params.append(
            ParameterNumber(self.DEFAULT_SPEED,
                            self.tr('Default speed (km/h)'), 0.0,
                            99999999.999999, 5.0))
        params.append(
            ParameterNumber(self.TOLERANCE, self.tr('Topology tolerance'), 0.0,
                            99999999.999999, 0.0))

        for p in params:
            p.setFlags(p.flags()
                       | QgsProcessingParameterDefinition.FlagAdvanced)
            self.addParameter(p)

        self.addOutput(
            OutputVector(self.OUTPUT_LAYER,
                         self.tr('Shortest path'),
                         datatype=[dataobjects.TYPE_VECTOR_LINE]))
Exemplo n.º 31
0
    def defineCharacteristics(self):
        self.name, self.i18n_name = self.trAlgorithm('Clip raster by extent')
        self.group, self.i18n_group = self.trAlgorithm('[GDAL] Extraction')
        self.addParameter(
            ParameterRaster(self.INPUT, self.tr('Input layer'), False))
        self.addParameter(
            ParameterString(
                self.NO_DATA,
                self.
                tr("Nodata value, leave blank to take the nodata value from input"
                   ),
                '',
                optional=True))
        self.addParameter(
            ParameterExtent(self.PROJWIN, self.tr('Clipping extent')))

        params = []
        params.append(
            ParameterSelection(self.RTYPE, self.tr('Output raster type'),
                               self.TYPE, 5))
        params.append(
            ParameterSelection(self.COMPRESS,
                               self.tr('GeoTIFF options. Compression type:'),
                               self.COMPRESSTYPE, 4))
        params.append(
            ParameterNumber(self.JPEGCOMPRESSION,
                            self.tr('Set the JPEG compression level'), 1, 100,
                            75))
        params.append(
            ParameterNumber(self.ZLEVEL,
                            self.tr('Set the DEFLATE compression level'), 1, 9,
                            6))
        params.append(
            ParameterNumber(
                self.PREDICTOR,
                self.tr('Set the predictor for LZW or DEFLATE compression'), 1,
                3, 1))
        params.append(
            ParameterBoolean(
                self.TILED,
                self.tr(
                    'Create tiled output (only used for the GTiff format)'),
                False))
        params.append(
            ParameterSelection(
                self.BIGTIFF,
                self.
                tr('Control whether the created file is a BigTIFF or a classic TIFF'
                   ), self.BIGTIFFTYPE, 0))
        params.append(
            ParameterBoolean(
                self.TFW,
                self.
                tr('Force the generation of an associated ESRI world file (.tfw))'
                   ), False))
        params.append(
            ParameterString(self.EXTRA,
                            self.tr('Additional creation parameters'),
                            '',
                            optional=True))

        for param in params:
            param.isAdvanced = True
            self.addParameter(param)

        self.addOutput(OutputRaster(self.OUTPUT, self.tr('Clipped (extent)')))
Exemplo n.º 32
0
 def testSetValueOnlyValidNumbers(self):
     parameter = ParameterNumber('myName', 'myDescription')
     self.assertFalse(parameter.setValue('not a number'))
     self.assertEqual(parameter.value, None)
Exemplo n.º 33
0
    def defineCharacteristicsFromFile(self):
        lines = open(self.descriptionFile)
        line = lines.readline().strip('\n').strip()
        self.grass7Name = line
        line = lines.readline().strip('\n').strip()
        self.name = line
        self.i18n_name = QCoreApplication.translate("GrassAlgorithm", line)
        if " - " not in self.name:
            self.name = self.grass7Name + " - " + self.name
            self.i18n_name = self.grass7Name + " - " + self.i18n_name
        line = lines.readline().strip('\n').strip()
        self.group = line
        self.i18n_group = QCoreApplication.translate("GrassAlgorithm", line)
        hasRasterOutput = False
        hasVectorInput = False
        vectorOutputs = 0
        line = lines.readline().strip('\n').strip()
        while line != '':
            try:
                line = line.strip('\n').strip()
                if line.startswith('Parameter'):
                    parameter = getParameterFromString(line)
                    self.addParameter(parameter)
                    if isinstance(parameter, ParameterVector):
                        hasVectorInput = True
                    if isinstance(parameter, ParameterMultipleInput) \
                       and parameter.datatype < 3:
                        hasVectorInput = True
                elif line.startswith('*Parameter'):
                    param = getParameterFromString(line[1:])
                    param.isAdvanced = True
                    self.addParameter(param)
                else:
                    output = getOutputFromString(line)
                    self.addOutput(output)
                    if isinstance(output, OutputRaster):
                        hasRasterOutput = True
                    elif isinstance(output, OutputVector):
                        vectorOutputs += 1
                line = lines.readline().strip('\n').strip()
            except Exception as e:
                ProcessingLog.addToLog(
                    ProcessingLog.LOG_ERROR,
                    self.tr('Could not open GRASS GIS 7 algorithm: %s\n%s' % (self.descriptionFile, line)))
                raise e
        lines.close()

        self.addParameter(ParameterExtent(
            self.GRASS_REGION_EXTENT_PARAMETER,
            self.tr('GRASS GIS 7 region extent'))
        )
        if hasRasterOutput:
            self.addParameter(ParameterNumber(
                self.GRASS_REGION_CELLSIZE_PARAMETER,
                self.tr('GRASS GIS 7 region cellsize (leave 0 for default)'),
                0, None, 0.0))
        if hasVectorInput:
            param = ParameterNumber(self.GRASS_SNAP_TOLERANCE_PARAMETER,
                                    'v.in.ogr snap tolerance (-1 = no snap)',
                                    -1, None, -1.0)
            param.isAdvanced = True
            self.addParameter(param)
            param = ParameterNumber(self.GRASS_MIN_AREA_PARAMETER,
                                    'v.in.ogr min area', 0, None, 0.0001)
            param.isAdvanced = True
            self.addParameter(param)
        if vectorOutputs == 1:
            param = ParameterSelection(self.GRASS_OUTPUT_TYPE_PARAMETER,
                                       'v.out.ogr output type',
                                       self.OUTPUT_TYPES)
            param.isAdvanced = True
            self.addParameter(param)
Exemplo n.º 34
0
 def testSetValueOnlyValidNumbers(self):
     parameter = ParameterNumber("myName", "myDescription")
     self.assertFalse(parameter.setValue("not a number"))
     self.assertEqual(parameter.value, None)
Exemplo n.º 35
0
    def defineCharacteristics(self):
        self.METHODS = [self.tr('Linear'),
                        self.tr('Clough-Toucher (cubic)')
                        ]

        class ParameterInterpolationData(Parameter):
            default_metadata = {
                'widget_wrapper': 'processing.algs.qgis.ui.InterpolationDataWidget.InterpolationDataWidgetWrapper'
            }

            def __init__(self, name='', description=''):
                Parameter.__init__(self, name, description)

            def setValue(self, value):
                if value is None:
                    if not self.optional:
                        return False
                    self.value = None
                    return True

                if value == '':
                    if not self.optional:
                        return False

                if isinstance(value, str):
                    self.value = value if value != '' else None
                else:
                    self.value = ParameterInterpolationData.dataToString(value)
                return True

            def getValueAsCommandLineParameter(self):
                return '"{}"'.format(self.value)

            def getAsScriptCode(self):
                param_type = ''
                param_type += 'interpolation data '
                return '##' + self.name + '=' + param_type

            @classmethod
            def fromScriptCode(self, line):
                isOptional, name, definition = _splitParameterOptions(line)
                descName = _createDescriptiveName(name)
                parent = definition.lower().strip()[len('interpolation data') + 1:]
                return ParameterInterpolationData(name, descName, parent)

            @staticmethod
            def dataToString(data):
                s = ''
                for c in data:
                    s += '{}, {}, {:d}, {:d};'.format(c[0],
                                                      c[1],
                                                      c[2],
                                                      c[3])
                return s[:-1]

        self.addParameter(ParameterInterpolationData(self.INTERPOLATION_DATA,
                                                     self.tr('Input layer(s)')))
        self.addParameter(ParameterSelection(self.METHOD,
                                             self.tr('Interpolation method'),
                                             self.METHODS,
                                             0))
        self.addParameter(ParameterNumber(self.COLUMNS,
                                          self.tr('Number of columns'),
                                          0, 10000000, 300))
        self.addParameter(ParameterNumber(self.ROWS,
                                          self.tr('Number of rows'),
                                          0, 10000000, 300))
        self.addParameter(ParameterNumber(self.CELLSIZE_X,
                                          self.tr('Cell size X'),
                                          0.0, 999999.000000, 0.0))
        self.addParameter(ParameterNumber(self.CELLSIZE_Y,
                                          self.tr('Cell size Y'),
                                          0.0, 999999.000000, 0.0))
        self.addParameter(ParameterExtent(self.EXTENT,
                                          self.tr('Extent'),
                                          optional=False))
        self.addOutput(OutputRaster(self.OUTPUT_LAYER,
                                    self.tr('Interpolated')))
        self.addOutput(OutputVector(self.TRIANULATION_FILE,
                                    self.tr('Triangulation'),
                                    ))  # datatype=dataobjects.TYPE_VECTOR_LINE))
Exemplo n.º 36
0
 def addParametersCoresGUI(self):
     self.addParameter(
         ParameterNumber(LAStoolsAlgorithm.CORES, "number of cores", 1, 32,
                         4))
Exemplo n.º 37
0
    def initAlgorithm(self, config=None):
        self.addParameter(ParameterRaster(self.INPUT, self.tr('Input layer')))
        self.addParameter(
            ParameterNumber(self.BINS, self.tr('Number of bins'), 2, None, 10))

        self.addOutput(OutputHTML(self.PLOT, self.tr('Histogram')))
Exemplo n.º 38
0
    def defineCharacteristicsFromFile(self):
        with open(self.descriptionFile) as lines:
            line = lines.readline().strip("\n").strip()
            self.grass7Name = line
            line = lines.readline().strip("\n").strip()
            self.name = line
            self.i18n_name = QCoreApplication.translate("GrassAlgorithm", line)
            if " - " not in self.name:
                self.name = self.grass7Name + " - " + self.name
                self.i18n_name = self.grass7Name + " - " + self.i18n_name
            line = lines.readline().strip("\n").strip()
            self.group = line
            self.i18n_group = QCoreApplication.translate("GrassAlgorithm", line)
            hasRasterOutput = False
            hasVectorInput = False
            vectorOutputs = 0
            line = lines.readline().strip("\n").strip()
            while line != "":
                try:
                    line = line.strip("\n").strip()
                    if line.startswith("Hardcoded"):
                        self.hardcodedStrings.append(line[len("Hardcoded|") :])
                    parameter = getParameterFromString(line)
                    if parameter is not None:
                        self.addParameter(parameter)
                        if isinstance(parameter, ParameterVector):
                            hasVectorInput = True
                        if isinstance(parameter, ParameterMultipleInput) and parameter.datatype < 3:
                            hasVectorInput = True
                    else:
                        output = getOutputFromString(line)
                        self.addOutput(output)
                        if isinstance(output, OutputRaster):
                            hasRasterOutput = True
                        elif isinstance(output, OutputVector):
                            vectorOutputs += 1
                        if isinstance(output, OutputHTML):
                            self.addOutput(OutputFile("rawoutput", output.description + " (raw output)", "txt"))
                    line = lines.readline().strip("\n").strip()
                except Exception as e:
                    ProcessingLog.addToLog(
                        ProcessingLog.LOG_ERROR,
                        self.tr("Could not open GRASS GIS 7 algorithm: %s\n%s" % (self.descriptionFile, line)),
                    )
                    raise e

        self.addParameter(ParameterExtent(self.GRASS_REGION_EXTENT_PARAMETER, self.tr("GRASS GIS 7 region extent")))
        if hasRasterOutput:
            self.addParameter(
                ParameterNumber(
                    self.GRASS_REGION_CELLSIZE_PARAMETER,
                    self.tr("GRASS GIS 7 region cellsize (leave 0 for default)"),
                    0,
                    None,
                    0.0,
                )
            )
        if hasVectorInput:
            param = ParameterNumber(
                self.GRASS_SNAP_TOLERANCE_PARAMETER, "v.in.ogr snap tolerance (-1 = no snap)", -1, None, -1.0
            )
            param.isAdvanced = True
            self.addParameter(param)
            param = ParameterNumber(self.GRASS_MIN_AREA_PARAMETER, "v.in.ogr min area", 0, None, 0.0001)
            param.isAdvanced = True
            self.addParameter(param)
        if vectorOutputs == 1:
            param = ParameterSelection(self.GRASS_OUTPUT_TYPE_PARAMETER, "v.out.ogr output type", self.OUTPUT_TYPES)
            param.isAdvanced = True
            self.addParameter(param)
Exemplo n.º 39
0
 def addParametersStepGUI(self):
     self.addParameter(
         ParameterNumber(LAStoolsAlgorithm.STEP, "step size / pixel size",
                         0, None, 1.0))
Exemplo n.º 40
0
Arquivo: warp.py Projeto: rskelly/QGIS
    def __init__(self):
        super().__init__()
        self.addParameter(
            ParameterRaster(self.INPUT, self.tr('Input layer'), False))
        self.addParameter(
            ParameterCrs(self.SOURCE_SRS,
                         self.tr('Source SRS'),
                         '',
                         optional=True))
        self.addParameter(
            ParameterCrs(self.DEST_SRS, self.tr('Destination SRS'),
                         'EPSG:4326'))
        self.addParameter(
            ParameterString(
                self.NO_DATA,
                self.
                tr("Nodata value, leave blank to take the nodata value from input"
                   ),
                '',
                optional=True))
        self.addParameter(
            ParameterNumber(
                self.TR,
                self.
                tr('Output file resolution in target georeferenced units (leave 0 for no change)'
                   ), 0.0, None, 0.0))
        self.addParameter(
            ParameterSelection(self.METHOD, self.tr('Resampling method'),
                               self.METHOD_OPTIONS))
        self.addParameter(
            ParameterBoolean(
                self.USE_RASTER_EXTENT,
                self.tr('Set georeferenced extents of output file'), False))
        self.addParameter(
            ParameterExtent(self.RASTER_EXTENT,
                            self.tr('Raster extent'),
                            optional=True))
        self.addParameter(
            ParameterCrs(
                self.EXTENT_CRS,
                self.
                tr('CRS of the raster extent, leave blank for using Destination SRS'
                   ),
                optional=True))
        self.addParameter(
            ParameterString(
                self.OPTIONS,
                self.tr('Additional creation options'),
                optional=True,
                metadata={
                    'widget_wrapper':
                    'processing.algs.gdal.ui.RasterOptionsWidget.RasterOptionsWidgetWrapper'
                }))
        self.addParameter(
            ParameterBoolean(
                self.MULTITHREADING,
                self.tr('Use multithreaded warping implementation'), False))
        self.addParameter(
            ParameterSelection(self.RTYPE, self.tr('Output raster type'),
                               self.TYPE, 5))

        self.addOutput(OutputRaster(self.OUTPUT, self.tr('Reprojected')))
Exemplo n.º 41
0
    def defineCharacteristics(self):
        """
        Algorithme variable and parameters parameters
        """
        CholeAlgorithm.defineCharacteristics(self)

        # The name/group that the user will see in the toolbox
        self.group = 'generate ascii grid'
        self.i18n_group = self.tr('generate ascii grid')
        self.name = 'from csv'
        self.i18n_name = self.tr('from csv')

        # === INPUT PARAMETERS ===
        self.addParameter(
            ParameterTable(name=self.INPUT_FILE_CSV,
                           description=self.tr('Input file csv')))

        self.addParameter(
            ParameterString(name=self.FIELDS,
                            description=self.tr('Fields selection'),
                            default=''))

        self.addParameter(
            ParameterNumber(name=self.N_COLS,
                            description=self.tr('Columns count'),
                            minValue=0,
                            default=100))

        self.addParameter(
            ParameterNumber(name=self.N_ROWS,
                            description=self.tr('Rows count'),
                            minValue=0,
                            default=100))

        self.addParameter(
            ParameterNumber(
                name=self.XLL_CORNER,
                description=self.tr('X bottom left corner coordinate'),
                default=0.0))

        self.addParameter(
            ParameterNumber(
                name=self.YLL_CORNER,
                description=self.tr('Y bottom left corner coordinate'),
                default=0.0))

        self.addParameter(
            ParameterNumber(name=self.CELL_SIZE,
                            description=self.tr('Cell size'),
                            default=1.0))

        self.addParameter(
            ParameterNumber(name=self.NODATA_VALUE,
                            description=self.tr('Value if no-data'),
                            default=-1))

        self.addOutput(
            OutputFile(name=self.SAVE_PROPERTIES,
                       description=self.tr('Properties file'),
                       ext='properties'))

        # === OUTPUT PARAMETERS ===
        self.addOutput(
            ASCOutputRaster(name=self.OUTPUT_ASC,
                            description=self.tr('Ouput Raster ascii')))