Exemplo n.º 1
0
    def getConsoleCommands(self):
        arguments = ['-l']
        arguments.append(
            os.path.basename(os.path.splitext(
                unicode(self.getParameterValue(self.INPUT)))[0]))

        fieldName = self.getParameterValue(self.Z_FIELD)
        if fieldName is not None and fieldName != '':
            arguments.append('-zfield')
            arguments.append(fieldName)

        params = 'average'
        params += ':radius1=%s' % self.getParameterValue(self.RADIUS_1)
        params += ':radius2=%s' % self.getParameterValue(self.RADIUS_2)
        params += ':angle=%s' % self.getParameterValue(self.ANGLE)
        params += ':min_points=%s' % self.getParameterValue(self.MIN_POINTS)
        params += ':nodata=%s' % self.getParameterValue(self.NODATA)

        arguments.append('-a')
        arguments.append(params)
        arguments.append('-ot')
        arguments.append(self.TYPE[self.getParameterValue(self.RTYPE)])

        out = self.getOutputValue(self.OUTPUT)
        arguments.append('-of')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(out))

        arguments.append(unicode(self.getParameterValue(self.INPUT)))
        arguments.append(unicode(self.getOutputValue(self.OUTPUT)))

        return ['gdal_grid', GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 2
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        ogrLayer, layerName = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, executing)
        sql = self.parameterAsString(parameters, self.SQL, context)
        options = self.parameterAsString(parameters, self.OPTIONS, context)
        outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        output, outputFormat = GdalUtils.ogrConnectionStringAndFormat(outFile, context)

        if not sql:
            raise QgsProcessingException(
                self.tr('Empty SQL. Please enter valid SQL expression and try again.'))

        arguments = []
        arguments.append(output)
        arguments.append(ogrLayer)
        arguments.append('-sql')
        arguments.append(sql)

        dialect = self.dialects[self.parameterAsEnum(parameters, self.DIALECT, context)][1]
        if dialect:
            arguments.append('-dialect')
            arguments.append(dialect)

        if options:
            arguments.append(options)

        if outputFormat:
            arguments.append('-f {}'.format(outputFormat))

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 3
0
    def getConsoleCommands(self):
        arguments = ['aspect']
        arguments.append(str(self.getParameterValue(self.INPUT)))
        output = str(self.getOutputValue(self.OUTPUT))
        arguments.append(output)

        arguments.append('-of')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(output))

        arguments.append('-b')
        arguments.append(str(self.getParameterValue(self.BAND)))

        if self.getParameterValue(self.COMPUTE_EDGES):
            arguments.append('-compute_edges')

        if self.getParameterValue(self.ZEVENBERGEN):
            arguments.append('-alg')
            arguments.append('ZevenbergenThorne')

        if self.getParameterValue(self.TRIG_ANGLE):
            arguments.append('-trigonometric')

        if self.getParameterValue(self.ZERO_FLAT):
            arguments.append('-zero_for_flat')

        return ['gdaldem', GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 4
0
    def getConsoleCommands(self, parameters, context, feedback):
        arguments = ['aspect']
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        arguments.append(inLayer.source())

        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        arguments.append(out)

        arguments.append('-of')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(out))

        arguments.append('-b')
        arguments.append(str(self.parameterAsInt(parameters, self.BAND, context)))

        if self.parameterAsBool(parameters, self.COMPUTE_EDGES, context):
            arguments.append('-compute_edges')

        if self.parameterAsBool(parameters, self.ZEVENBERGEN, context):
            arguments.append('-alg')
            arguments.append('ZevenbergenThorne')

        if self.parameterAsBool(parameters, self.TRIG_ANGLE, context):
            arguments.append('-trigonometric')

        if self.parameterAsBool(parameters, self.ZERO_FLAT, context):
            arguments.append('-zero_for_flat')

        return ['gdaldem', GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 5
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        arguments = []
        arguments.append('-resolution')
        arguments.append(self.RESOLUTION_OPTIONS[self.parameterAsEnum(parameters, self.RESOLUTION, context)])
        if self.parameterAsBool(parameters, buildvrt.SEPARATE, context):
            arguments.append('-separate')
        if self.parameterAsBool(parameters, buildvrt.PROJ_DIFFERENCE, context):
            arguments.append('-allow_projection_difference')
        if self.parameterAsBool(parameters, buildvrt.ADD_ALPHA, context):
            arguments.append('-addalpha')
        crs = self.parameterAsCrs(parameters, self.ASSIGN_CRS, context)
        if crs.isValid():
            arguments.append('-a_srs')
            arguments.append(GdalUtils.gdal_crs_string(crs))
        arguments.append('-r')
        arguments.append(self.RESAMPLING_OPTIONS[self.parameterAsEnum(parameters, self.RESAMPLING, context)])

        if self.SRC_NODATA in parameters and parameters[self.SRC_NODATA] not in (None, ''):
            nodata = self.parameterAsString(parameters, self.SRC_NODATA, context)
            arguments.append('-srcnodata "{}"'.format(nodata))

        # Always write input files to a text file in case there are many of them and the
        # length of the command will be longer then allowed in command prompt
        list_file = GdalUtils.writeLayerParameterToTextFile(filename='buildvrtInputFiles.txt', alg=self, parameters=parameters, parameter_name=self.INPUT, context=context, executing=executing, quote=False)
        arguments.append('-input_file_list')
        arguments.append(list_file)

        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        self.setOutputValue(self.OUTPUT, out)
        arguments.append(out)

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 6
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        inLayer, inLayerName = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, executing)
        maskLayer, maskLayerName = self.getOgrCompatibleSource(self.MASK, parameters, context, feedback, executing)
        options = self.parameterAsString(parameters, self.OPTIONS, context)
        outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        self.setOutputValue(self.OUTPUT, outFile)

        output, outputFormat = GdalUtils.ogrConnectionStringAndFormat(outFile, context)

        arguments = []
        arguments.append('-clipsrc')
        arguments.append(maskLayer)
        arguments.append('-clipsrclayer')
        arguments.append(maskLayerName)

        arguments.append(output)
        arguments.append(inLayer)
        arguments.append(inLayerName)

        if options:
            arguments.append(options)

        if outputFormat:
            arguments.append('-f {}'.format(outputFormat))

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 7
0
    def getConsoleCommands(self):
        out = self.getOutputValue(self.OUTPUT)
        noData = self.getParameterValue(self.NO_DATA)
        opts = self.getParameterValue(self.OPTIONS)
        projwin = self.getParameterValue(self.PROJWIN)

        if noData is not None:
            noData = str(noData)

        arguments = []
        arguments.append('-of')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(out))
        arguments.append('-ot')
        arguments.append(self.TYPE[self.getParameterValue(self.RTYPE)])
        if noData and len(noData) > 0:
            arguments.append('-a_nodata')
            arguments.append(noData)

        regionCoords = projwin.split(',')
        arguments.append('-projwin')
        arguments.append(regionCoords[0])
        arguments.append(regionCoords[3])
        arguments.append(regionCoords[1])
        arguments.append(regionCoords[2])

        if opts:
            arguments.append('-co')
            arguments.append(opts)

        arguments.append(self.getParameterValue(self.INPUT))
        arguments.append(out)

        return ['gdal_translate', GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 8
0
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        clipExtent = self.getParameterValue(self.CLIP_EXTENT)

        output = self.getOutputFromName(self.OUTPUT_LAYER)
        outFile = output.value

        output = ogrConnectionString(outFile)
        options = str(self.getParameterValue(self.OPTIONS))

        arguments = []
        regionCoords = clipExtent.split(',')
        arguments.append('-spat')
        arguments.append(regionCoords[0])
        arguments.append(regionCoords[2])
        arguments.append(regionCoords[1])
        arguments.append(regionCoords[3])
        arguments.append('-clipsrc spat_extent')

        if len(options) > 0:
            arguments.append(options)

        arguments.append(output)
        arguments.append(ogrLayer)
        arguments.append(ogrLayerName(inLayer))

        commands = []
        if isWindows():
            commands = ['cmd.exe', '/C ', 'ogr2ogr.exe',
                        GdalUtils.escapeAndJoin(arguments)]
        else:
            commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]

        return commands
Exemplo n.º 9
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        if inLayer is None:
            raise QgsProcessingException(self.invalidRasterError(parameters, self.INPUT))

        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        arguments = []

        bands = self.parameterAsInts(parameters, self.BANDS, context)
        for band in bands:
            arguments.append('-b {}'.format(band))

        data_type = self.parameterAsEnum(parameters, self.DATA_TYPE, context)
        if data_type:
            arguments.append('-ot ' + self.TYPES[data_type])

        arguments.append('-of')
        arguments.append(QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))

        options = self.parameterAsString(parameters, self.OPTIONS, context)
        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        arguments.append(inLayer.source())
        arguments.append(out)

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 10
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        ogrLayer, layerName = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, executing)

        arguments = ['-l']
        arguments.append(layerName)

        fieldName = self.parameterAsString(parameters, self.Z_FIELD, context)
        if fieldName:
            arguments.append('-zfield')
            arguments.append(fieldName)

        params = 'nearest'
        params += ':radius1={}'.format(self.parameterAsDouble(parameters, self.RADIUS_1, context))
        params += ':radius2={}'.format(self.parameterAsDouble(parameters, self.RADIUS_2, context))
        params += ':angle={}'.format(self.parameterAsDouble(parameters, self.ANGLE, context))
        params += ':nodata={}'.format(self.parameterAsDouble(parameters, self.NODATA, context))

        arguments.append('-a')
        arguments.append(params)
        arguments.append('-ot')
        arguments.append(self.TYPES[self.parameterAsEnum(parameters, self.DATA_TYPE, context)])

        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        self.setOutputValue(self.OUTPUT, out)
        arguments.append('-of')
        arguments.append(QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))

        options = self.parameterAsString(parameters, self.OPTIONS, context)
        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        arguments.append(ogrLayer)
        arguments.append(out)

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 11
0
    def processAlgorithm(self, progress):
        output = self.getOutputValue(self.OUTPUT)

        arguments = []
        arguments.append('-st')
        arguments.append(str(self.getParameterValue(self.THRESHOLD)))

        arguments.append('-' +
                self.PIXEL_CONNECTIONS[self.getParameterValue(
                        self.CONNECTIONS)])

        arguments.append('-of')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(output))

        arguments.append(self.getParameterValue(self.INPUT))
        arguments.append(output)

        commands = []
        if isWindows():
            commands = ['cmd.exe', '/C ', 'gdal_sieve.bat',
                        GdalUtils.escapeAndJoin(arguments)]
        else:
            commands = ['gdal_sieve.py', GdalUtils.escapeAndJoin(arguments)]

        GdalUtils.runGdal(commands, progress)
Exemplo n.º 12
0
 def getOgrCompatibleSource(self, parameter_name, parameters, context, feedback):
     """
     Interprets a parameter as an OGR compatible source and layer name
     """
     input_layer = self.parameterAsVectorLayer(parameters, parameter_name, context)
     ogr_data_path = None
     ogr_layer_name = None
     if input_layer is None:
         # parameter is not a vector layer - try to convert to a source compatible with OGR
         # and extract selection if required
         ogr_data_path = self.parameterAsCompatibleSourceLayerPath(parameters, parameter_name, context,
                                                                   QgsVectorFileWriter.supportedFormatExtensions(),
                                                                   feedback=feedback)
         ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
     elif input_layer.dataProvider().name() == 'ogr':
         # parameter is a vector layer, with OGR data provider
         # so extract selection if required
         ogr_data_path = self.parameterAsCompatibleSourceLayerPath(parameters, parameter_name, context,
                                                                   QgsVectorFileWriter.supportedFormatExtensions(),
                                                                   feedback=feedback)
         ogr_layer_name = GdalUtils.ogrLayerName(input_layer.dataProvider().dataSourceUri())
     else:
         # vector layer, but not OGR - get OGR compatible path
         # TODO - handle "selected features only" mode!!
         ogr_data_path = GdalUtils.ogrConnectionString(input_layer.dataProvider().dataSourceUri(), context)[1:-1]
         ogr_layer_name = GdalUtils.ogrLayerName(input_layer.dataProvider().dataSourceUri())
     return ogr_data_path, ogr_layer_name
Exemplo n.º 13
0
    def getConsoleCommands(self):
        output = self.getOutputValue(self.OUTPUT_VECTOR)
        interval = str(self.getParameterValue(self.INTERVAL))
        fieldName = str(self.getParameterValue(self.FIELD_NAME))
        extra = self.getParameterValue(self.EXTRA)
        if extra is not None:
            extra = str(extra)

        arguments = []
        if len(fieldName) > 0:
            arguments.append('-a')
            arguments.append(fieldName)
        arguments.append('-i')
        arguments.append(interval)

        driver = GdalUtils.getVectorDriverFromFileName(output)
        arguments.append('-f')
        arguments.append(driver)

        if extra and len(extra) > 0:
            arguments.append(extra)

        arguments.append(self.getParameterValue(self.INPUT_RASTER))
        arguments.append(output)

        return ['gdal_contour', GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 14
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        arguments = ['aspect']
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        if inLayer is None:
            raise QgsProcessingException(self.invalidRasterError(parameters, self.INPUT))
        arguments.append(inLayer.source())

        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        arguments.append(out)
        self.setOutputValue(self.OUTPUT, out)

        arguments.append('-of')
        arguments.append(QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))

        arguments.append('-b')
        arguments.append(str(self.parameterAsInt(parameters, self.BAND, context)))

        if self.parameterAsBoolean(parameters, self.TRIG_ANGLE, context):
            arguments.append('-trigonometric')

        if self.parameterAsBoolean(parameters, self.ZERO_FLAT, context):
            arguments.append('-zero_for_flat')

        if self.parameterAsBoolean(parameters, self.COMPUTE_EDGES, context):
            arguments.append('-compute_edges')

        if self.parameterAsBoolean(parameters, self.ZEVENBERGEN, context):
            arguments.append('-alg')
            arguments.append('ZevenbergenThorne')

        options = self.parameterAsString(parameters, self.OPTIONS, context)
        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 15
0
    def getConsoleCommands(self):
        output = self.getOutputValue(self.OUTPUT)

        arguments = []
        arguments.append('-st')
        arguments.append(unicode(self.getParameterValue(self.THRESHOLD)))

        arguments.append('-' +
            self.PIXEL_CONNECTIONS[self.getParameterValue(
                self.CONNECTIONS)])

        arguments.append('-of')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(output))

        arguments.append(self.getParameterValue(self.INPUT))
        arguments.append(output)

        commands = []
        if isWindows():
            commands = ['cmd.exe', '/C ', 'gdal_sieve.bat',
                        GdalUtils.escapeAndJoin(arguments)]
        else:
            commands = ['gdal_sieve.py', GdalUtils.escapeAndJoin(arguments)]

        return commands
Exemplo n.º 16
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        arguments = []
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        arguments.append(inLayer.source())

        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        arguments.append(out)

        arguments.append('-of')
        arguments.append(QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))

        arguments.append('-b')
        arguments.append(str(self.parameterAsInt(parameters, self.BAND, context)))

        if self.parameterAsBool(parameters, self.RGBA, context):
            arguments.append('-rgba')

        commands = []
        if isWindows():
            commands = ['cmd.exe', '/C ', 'pct2rgb.bat',
                        GdalUtils.escapeAndJoin(arguments)]
        else:
            commands = ['pct2rgb.py', GdalUtils.escapeAndJoin(arguments)]

        return commands
Exemplo n.º 17
0
    def getConsoleCommands(self):
        arguments = ["aspect"]
        arguments.append(unicode(self.getParameterValue(self.INPUT)))
        output = unicode(self.getOutputValue(self.OUTPUT))
        arguments.append(output)

        arguments.append("-of")
        arguments.append(GdalUtils.getFormatShortNameFromFilename(output))

        arguments.append("-b")
        arguments.append(str(self.getParameterValue(self.BAND)))

        if self.getParameterValue(self.COMPUTE_EDGES):
            arguments.append("-compute_edges")

        if self.getParameterValue(self.ZEVENBERGEN):
            arguments.append("-alg")
            arguments.append("ZevenbergenThorne")

        if self.getParameterValue(self.TRIG_ANGLE):
            arguments.append("-trigonometric")

        if self.getParameterValue(self.ZERO_FLAT):
            arguments.append("-zero_for_flat")

        return ["gdaldem", GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 18
0
    def getConsoleCommands(self, parameters):
        arguments = ['slope']
        arguments.append(str(self.getParameterValue(self.INPUT)))
        output = str(self.getOutputValue(self.OUTPUT))
        arguments.append(output)

        arguments.append('-of')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(output))

        arguments.append('-b')
        arguments.append(str(self.getParameterValue(self.BAND)))
        arguments.append('-s')
        arguments.append(str(self.getParameterValue(self.SCALE)))

        if self.getParameterValue(self.COMPUTE_EDGES):
            arguments.append('-compute_edges')

        if self.getParameterValue(self.ZEVENBERGEN):
            arguments.append('-alg')
            arguments.append('ZevenbergenThorne')

        if self.getParameterValue(self.AS_PERCENT):
            arguments.append('-p')

        return ['gdaldem', GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 19
0
    def processAlgorithm(self, progress):
        arguments = ['-l']
        arguments.append(
            os.path.basename(os.path.splitext(
                unicode(self.getParameterValue(self.INPUT)))[0]))

        fieldName = self.getParameterValue(self.Z_FIELD)
        if fieldName is not None and fieldName != '':
            arguments.append('-zfield')
            arguments.append(fieldName)

        params = 'nearest'
        params += ':radius1=%s' % self.getParameterValue(self.RADIUS_1)
        params += ':radius2=%s' % self.getParameterValue(self.RADIUS_2)
        params += ':angle=%s' % self.getParameterValue(self.ANGLE)
        params += ':nodata=%s' % self.getParameterValue(self.NODATA)

        arguments.append('-a')
        arguments.append(params)
        arguments.append('-ot')
        arguments.append(self.TYPE[self.getParameterValue(self.RTYPE)])
        arguments.append(unicode(self.getParameterValue(self.INPUT)))
        arguments.append(unicode(self.getOutputValue(self.OUTPUT)))

        GdalUtils.runGdal(['gdal_grid',
                          GdalUtils.escapeAndJoin(arguments)], progress)
    def processAlgorithm(self, progress):
        inLayer = self.getParameterValue(self.INPUT)
        conn = self.ogrConnectionString(inLayer)

        output = self.getOutputFromName(self.OUTPUT)
        outFile = output.value

        arguments = ['-s_srs']
        if self.getParameterValue(self.GRID) == 0:
            # Jose Alberto Goncalves
            arguments.append('+proj=tmerc +lat_0=39.66666666666666 '
                             '+lon_0=-8.131906111111112 +k=1 +x_0=200180.598 +y_0=299913.01 +ellps=intl +nadgrids=' + os.path.dirname(__file__) + '/grids/pt73_e89.gsb +wktext +units=m +no_defs')
        else:
            # Direccao Geral do Territorio
            arguments.append('+proj=tmerc +lat_0=39.66666666666666 +lon_0=-8.131906111111112 +k=1 +x_0=200180.598 +y_0=299913.01 +ellps=intl +nadgrids=' + os.path.dirname(__file__) + '/grids/D73_ETRS89_geo.gsb +wktext +units=m +no_defs')
        arguments.append('-t_srs')
        arguments.append('EPSG:3763')
        arguments.append('-f')
        arguments.append('ESRI Shapefile')

        arguments.append(outFile)
        arguments.append(conn)

        commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]
        GdalUtils.runGdal(commands, progress)
Exemplo n.º 21
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        arguments = []
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        if inLayer is None:
            raise QgsProcessingException(self.invalidRasterError(parameters, self.INPUT))

        arguments.append(inLayer.source())

        outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        output, outFormat = GdalUtils.ogrConnectionStringAndFormat(outFile, context)
        arguments.append(output)

        if self.parameterAsBool(parameters, self.EIGHT_CONNECTEDNESS, context):
            arguments.append('-8')

        arguments.append('-b')
        arguments.append(str(self.parameterAsInt(parameters, self.BAND, context)))

        if outFormat:
            arguments.append('-f {}'.format(outFormat))

        arguments.append(GdalUtils.ogrLayerName(output))
        arguments.append(self.parameterAsString(parameters, self.FIELD, context))

        commands = []
        if isWindows():
            commands = ['cmd.exe', '/C ', self.commandName() + '.bat',
                        GdalUtils.escapeAndJoin(arguments)]
        else:
            commands = [self.commandName() + '.py',
                        GdalUtils.escapeAndJoin(arguments)]

        return commands
Exemplo n.º 22
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        ogrLayer, layerName = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, executing)
        source = self.parameterAsSource(parameters, self.INPUT, context)
        if source is None:
            raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))

        extent = self.parameterAsExtent(parameters, self.EXTENT, context, source.sourceCrs())
        options = self.parameterAsString(parameters, self.OPTIONS, context)
        outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        self.setOutputValue(self.OUTPUT, outFile)

        output, outputFormat = GdalUtils.ogrConnectionStringAndFormat(outFile, context)

        arguments = []
        arguments.append('-spat')
        arguments.append(str(extent.xMinimum()))
        arguments.append(str(extent.yMaximum()))
        arguments.append(str(extent.xMaximum()))
        arguments.append(str(extent.yMinimum()))
        arguments.append('-clipsrc spat_extent')

        arguments.append(output)
        arguments.append(ogrLayer)
        arguments.append(layerName)

        if options:
            arguments.append(options)

        if outputFormat:
            arguments.append('-f {}'.format(outputFormat))

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 23
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        if inLayer is None:
            raise QgsProcessingException(self.invalidRasterError(parameters, self.INPUT))

        arguments = []
        arguments.append(inLayer.source())

        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        arguments.append('-of')
        arguments.append(QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))
        arguments.append('-o')
        arguments.append(out)

        arguments.append('-near')
        arguments.append(str(self.parameterAsInt(parameters, self.NEAR, context)))

        if self.parameterAsBool(parameters, self.WHITE, context):
            arguments.append('-white')

        options = self.parameterAsString(parameters, self.OPTIONS, context)
        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 24
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        spectral = self.parameterAsRasterLayer(parameters, self.SPECTRAL, context)
        if spectral is None:
            raise QgsProcessingException(self.invalidRasterError(parameters, self.SPECTRAL))

        panchromatic = self.parameterAsRasterLayer(parameters, self.PANCHROMATIC, context)
        if panchromatic is None:
            raise QgsProcessingException(self.invalidRasterError(parameters, self.PANCHROMATIC))

        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        self.setOutputValue(self.OUTPUT, out)

        arguments = []
        arguments.append(panchromatic.source())
        arguments.append(spectral.source())
        arguments.append(out)

        arguments.append('-r')
        arguments.append(self.methods[self.parameterAsEnum(parameters, self.RESAMPLING, context)][1])
        arguments.append('-of')
        arguments.append(QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))

        options = self.parameterAsString(parameters, self.OPTIONS, context)
        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        if isWindows():
            commands = ['python3', '-m', self.commandName()]
        else:
            commands = [self.commandName() + '.py']

        commands.append(GdalUtils.escapeAndJoin(arguments))

        return commands
Exemplo n.º 25
0
    def processAlgorithm(self, progress):
        out = self.getOutputValue(self.OUTPUT)
        noData = str(self.getParameterValue(self.NO_DATA))
        projwin = str(self.getParameterValue(self.PROJWIN))
        extra = str(self.getParameterValue(self.EXTRA))

        arguments = []
        arguments.append('-of')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(out))
        if len(noData) > 0:
            arguments.append('-a_nodata')
            arguments.append(noData)

        regionCoords = projwin.split(',')
        arguments.append('-projwin')
        arguments.append(regionCoords[0])
        arguments.append(regionCoords[3])
        arguments.append(regionCoords[1])
        arguments.append(regionCoords[2])

        if len(extra) > 0:
            arguments.append(extra)

        arguments.append(self.getParameterValue(self.INPUT))
        arguments.append(out)

        GdalUtils.runGdal(['gdal_translate',
                          GdalUtils.escapeAndJoin(arguments)], progress)
Exemplo n.º 26
0
    def processAlgorithm(self, progress):
        arguments = ['slope']
        arguments.append(unicode(self.getParameterValue(self.INPUT)))
        output = unicode(self.getOutputValue(self.OUTPUT))
        arguments.append(output)

        arguments.append('-of')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(output))

        arguments.append('-b')
        arguments.append(str(self.getParameterValue(self.BAND)))
        arguments.append('-s')
        arguments.append(str(self.getParameterValue(self.SCALE)))

        if self.getParameterValue(self.COMPUTE_EDGES):
            arguments.append('-compute_edges')

        if self.getParameterValue(self.ZEVENBERGEN):
            arguments.append('-alg')
            arguments.append('ZevenbergenThorne')

        if self.getParameterValue(self.AS_PERCENT):
            arguments.append('-p')

        GdalUtils.runGdal(['gdaldem',
                          GdalUtils.escapeAndJoin(arguments)], progress)
Exemplo n.º 27
0
    def processAlgorithm(self, progress):
        arguments = ['-l']
        arguments.append(
                os.path.basename(os.path.splitext(
                        unicode(self.getParameterValue(self.INPUT)))[0]))

        fieldName = self.getParameterValue(self.Z_FIELD)
        if fieldName is not None and fieldName != '':
            arguments.append('-zfield')
            arguments.append(fieldName)

        params = 'invdist'
        params += ':power=%s' % self.getParameterValue(self.POWER)
        params += ':smothing=%s' % self.getParameterValue(self.SMOTHING)
        params += ':radius1=%s' % self.getParameterValue(self.RADIUS_1)
        params += ':radius2=%s' % self.getParameterValue(self.RADIUS_2)
        params += ':angle=%s' % self.getParameterValue(self.ANGLE)
        params += ':max_points=%s' % self.getParameterValue(self.MAX_POINTS)
        params += ':min_points=%s' % self.getParameterValue(self.MIN_POINTS)
        params += ':nodata=%s' % self.getParameterValue(self.NODATA)

        arguments.append('-a')
        arguments.append(params)

        arguments.append(unicode(self.getParameterValue(self.INPUT)))
        arguments.append(unicode(self.getOutputValue(self.OUTPUT)))

        GdalUtils.runGdal(['gdal_grid',
                          GdalUtils.escapeAndJoin(arguments)], progress)
Exemplo n.º 28
0
    def getConsoleCommands(self):
        output = self.getOutputValue(self.OUTPUT)

        arguments = []
        arguments.append("-md")
        arguments.append(str(self.getParameterValue(self.DISTANCE)))

        if self.getParameterValue(self.ITERATIONS) != 0:
            arguments.append("-si")
            arguments.append(str(self.getParameterValue(self.ITERATIONS)))

        arguments.append("-b")
        arguments.append(str(self.getParameterValue(self.BAND)))

        mask = self.getParameterValue(self.MASK)
        if mask is not None:
            arguments.append("-mask")
            arguments.append(mask)

        if self.getParameterValue(self.NO_DEFAULT_MASK):
            arguments.append("-nomask")

        arguments.append("-of")
        arguments.append(GdalUtils.getFormatShortNameFromFilename(output))

        arguments.append(self.getParameterValue(self.INPUT))
        arguments.append(output)

        commands = []
        if isWindows():
            commands = ["cmd.exe", "/C ", "gdal_fillnodata.bat", GdalUtils.escapeAndJoin(arguments)]
        else:
            commands = ["gdal_fillnodata.py", GdalUtils.escapeAndJoin(arguments)]

        return commands
    def processAlgorithm(self, progress):
        inLayer = self.getParameterValue(self.INPUT)
        conn = self.ogrConnectionString(inLayer)[1:-1]

        output = self.getOutputFromName(self.OUTPUT)
        outFile = output.value

        if self.getParameterValue(self.TRANSF) == 0:
            # Direct transformation
            arguments = ['-s_srs']
            if self.getParameterValue(self.CRS) == 0:
                # GOSGB 1936/British National Grid
                if self.getParameterValue(self.GRID) == 0:
                    # OSTN02_NTv2
                    arguments.append('+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +nadgrids=' + os.path.dirname(__file__) + '/grids/OSTN02_NTv2.gsb +wktext +units=m +no_defs')
            arguments.append('-t_srs')
            arguments.append('EPSG:4258')

            arguments.append('-f')
            arguments.append('ESRI Shapefile')

            arguments.append(outFile)
            arguments.append(conn)
            arguments.append(self.ogrLayerName(inLayer))

        else:
            # Inverse transformation
            arguments = ['-s_srs']
            arguments.append('EPSG:4258')
            arguments.append('-t_srs')
            if self.getParameterValue(self.CRS) == 0:
                # OSGB 1936/British National Grid
                if self.getParameterValue(self.GRID) == 0:
                    # OSTN02_NTv2
                    arguments.append('+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +nadgrids=' + os.path.dirname(__file__) + '/grids/OSTN02_NTv2.gsb +wktext +units=m +no_defs')
            arguments.append('-f')
            arguments.append('\"Geojson\"')
            arguments.append('/vsistdout/')
            arguments.append(conn)
            arguments.append(self.ogrLayerName(inLayer))
            arguments.append('-lco') 
            arguments.append('ENCODING=UTF-8')
            arguments.append('|')
            arguments.append('ogr2ogr')
            arguments.append('-f')               
            arguments.append('ESRI Shapefile') 
            arguments.append('-a_srs') 
            arguments.append('EPSG:27700') 
            arguments.append(outFile)    
            arguments.append('/vsistdin/')

        arguments.append('-lco') 
        arguments.append('ENCODING=UTF-8')

        if os.path.isfile(os.path.dirname(__file__) + '/grids/OSTN02_NTv2.gsb') is False:
           import urllib
           urllib.urlretrieve ("https://github.com/NaturalGIS/ntv2_transformations_grids_and_sample_data/raw/master/uk/OSTN02_NTv2.gsb", os.path.dirname(__file__) + "/grids/OSTN02_NTv2.gsb")

        commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]
        GdalUtils.runGdal(commands, progress)
Exemplo n.º 30
0
    def processAlgorithm(self, progress):
        arguments = ['hillshade']
        arguments.append(unicode(self.getParameterValue(self.INPUT)))
        arguments.append(unicode(self.getOutputValue(self.OUTPUT)))

        arguments.append('-b')
        arguments.append(str(self.getParameterValue(self.BAND)))
        arguments.append('-z')
        arguments.append(str(self.getParameterValue(self.Z_FACTOR)))
        arguments.append('-s')
        arguments.append(str(self.getParameterValue(self.SCALE)))
        arguments.append('-az')
        arguments.append(str(self.getParameterValue(self.AZIMUTH)))
        arguments.append('-alt')
        arguments.append(str(self.getParameterValue(self.ALTITUDE)))

        if self.getParameterValue(self.COMPUTE_EDGES):
            arguments.append('-compute_edges')

        if self.getParameterValue(self.ZEVENBERGEN):
            arguments.append('-alg')
            arguments.append('ZevenbergenThorne')

        GdalUtils.runGdal(['gdaldem',
                          GdalUtils.escapeAndJoin(arguments)], progress)
Exemplo n.º 31
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        connection = self.DB_CONNECTIONS[self.getParameterValue(self.DATABASE)]
        uri = uri_from_name(connection)
        if executing:
            # to get credentials input when needed
            uri = GeoDB(uri=uri).uri

        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = GdalUtils.ogrConnectionString(inLayer, context)[1:-1]
        shapeEncoding = self.getParameterValue(self.SHAPE_ENCODING)
        schema = str(self.getParameterValue(self.SCHEMA))
        table = str(self.getParameterValue(self.TABLE))
        pk = str(self.getParameterValue(self.PK))
        pkstring = "-lco FID=" + pk
        primary_key = self.getParameterValue(self.PRIMARY_KEY)
        where = str(self.getParameterValue(self.WHERE))
        wherestring = '-where "' + where + '"'
        gt = str(self.getParameterValue(self.GT))
        overwrite = self.getParameterValue(self.OVERWRITE)
        append = self.getParameterValue(self.APPEND)
        addfields = self.getParameterValue(self.ADDFIELDS)
        launder = self.getParameterValue(self.LAUNDER)
        launderstring = "-lco LAUNDER=NO"
        skipfailures = self.getParameterValue(self.SKIPFAILURES)
        precision = self.getParameterValue(self.PRECISION)
        options = str(self.getParameterValue(self.OPTIONS))

        arguments = []
        arguments.append('-progress')
        arguments.append('--config PG_USE_COPY YES')
        if len(shapeEncoding) > 0:
            arguments.append('--config')
            arguments.append('SHAPE_ENCODING')
            arguments.append('"' + shapeEncoding + '"')
        arguments.append('-f')
        arguments.append('PostgreSQL')
        arguments.append('PG:"')
        for token in uri.connectionInfo(executing).split(' '):
            arguments.append(token)
        arguments.append('active_schema={}'.format(schema or 'public'))
        arguments.append('"')
        arguments.append(ogrLayer)
        arguments.append('-nlt NONE')
        arguments.append(GdalUtils.ogrLayerName(inLayer))
        if launder:
            arguments.append(launderstring)
        if append:
            arguments.append('-append')
        if addfields:
            arguments.append('-addfields')
        if overwrite:
            arguments.append('-overwrite')
        if len(pk) > 0:
            arguments.append(pkstring)
        elif primary_key is not None:
            arguments.append("-lco FID=" + primary_key)
        if len(table) == 0:
            table = GdalUtils.ogrLayerName(inLayer).lower()
        if schema:
            table = '{}.{}'.format(schema, table)
        arguments.append('-nln')
        arguments.append(table)
        if skipfailures:
            arguments.append('-skipfailures')
        if where:
            arguments.append(wherestring)
        if len(gt) > 0:
            arguments.append('-gt')
            arguments.append(gt)
        if not precision:
            arguments.append('-lco PRECISION=NO')
        if len(options) > 0:
            arguments.append(options)

        commands = []
        if isWindows():
            commands = [
                'cmd.exe', '/C ', 'ogr2ogr.exe',
                GdalUtils.escapeAndJoin(arguments)
            ]
        else:
            commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]

        return commands
Exemplo n.º 32
0
    def getConsoleCommands(self):
        noData = self.getParameterValue(self.NO_DATA)
        if noData is not None:
            noData = str(noData)
        srccrs = self.getParameterValue(self.SOURCE_SRS)
        dstcrs = self.getParameterValue(self.DEST_SRS)
        jpegcompression = str(self.getParameterValue(self.JPEGCOMPRESSION))
        predictor = str(self.getParameterValue(self.PREDICTOR))
        zlevel = str(self.getParameterValue(self.ZLEVEL))
        tiled = str(self.getParameterValue(self.TILED))
        compress = self.COMPRESSTYPE[self.getParameterValue(self.COMPRESS)]
        bigtiff = self.BIGTIFFTYPE[self.getParameterValue(self.BIGTIFF)]
        tfw = str(self.getParameterValue(self.TFW))
        rastext = self.getParameterValue(self.RAST_EXT)
        rastext_crs = self.getParameterValue(self.EXT_CRS)

        arguments = []
        arguments.append('-ot')
        arguments.append(self.TYPE[self.getParameterValue(self.RTYPE)])
        if srccrs:
            arguments.append('-s_srs')
            arguments.append(srccrs)
        if dstcrs:
            arguments.append('-t_srs')
            arguments.append(dstcrs)
        if noData:
            arguments.append('-dstnodata')
            arguments.append(noData)
        arguments.append('-r')
        arguments.append(
            self.METHOD_OPTIONS[self.getParameterValue(self.METHOD)])
        arguments.append('-of')
        out = self.getOutputValue(self.OUTPUT)
        arguments.append(GdalUtils.getFormatShortNameFromFilename(out))
        if self.getParameterValue(self.TR) != 0:
            arguments.append('-tr')
            arguments.append(str(self.getParameterValue(self.TR)))
            arguments.append(str(self.getParameterValue(self.TR)))
        extra = self.getParameterValue(self.EXTRA)
        if extra is not None:
            extra = str(extra)
        if rastext:
            regionCoords = rastext.split(',')
            if len(regionCoords) >= 4:
                arguments.append('-te')
                arguments.append(regionCoords[0])
                arguments.append(regionCoords[2])
                arguments.append(regionCoords[1])
                arguments.append(regionCoords[3])

                if GdalUtils.version() >= 2000000:
                    if rastext_crs:
                        arguments.append('-te_srs')
                        arguments.append(rastext_crs)

        if extra and len(extra) > 0:
            arguments.append(extra)
        if GdalUtils.getFormatShortNameFromFilename(out) == "GTiff":
            arguments.append("-co COMPRESS=" + compress)
            if compress == 'JPEG':
                arguments.append("-co JPEG_QUALITY=" + jpegcompression)
            elif (compress == 'LZW') or (compress == 'DEFLATE'):
                arguments.append("-co PREDICTOR=" + predictor)
            if compress == 'DEFLATE':
                arguments.append("-co ZLEVEL=" + zlevel)
            if tiled == "True":
                arguments.append("-co TILED=YES")
            if tfw == "True":
                arguments.append("-co TFW=YES")
            if len(bigtiff) > 0:
                arguments.append("-co BIGTIFF=" + bigtiff)

            arguments.append("-wo OPTIMIZE_SIZE=TRUE")

        arguments.append(self.getParameterValue(self.INPUT))
        arguments.append(out)

        return ['gdalwarp', GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 33
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        arguments = [
            '-ps',
            str(self.parameterAsInt(parameters, self.TILE_SIZE_X, context)),
            str(self.parameterAsInt(parameters, self.TILE_SIZE_Y,
                                    context)), '-overlap',
            str(self.parameterAsInt(parameters, self.OVERLAP, context)),
            '-levels',
            str(self.parameterAsInt(parameters, self.LEVELS, context))
        ]

        crs = self.parameterAsCrs(parameters, self.SOURCE_CRS, context)
        if crs.isValid():
            arguments.append('-s_srs')
            arguments.append(GdalUtils.gdal_crs_string(crs))

        arguments.append('-r')
        arguments.append(self.methods[self.parameterAsEnum(
            parameters, self.RESAMPLING, context)][1])

        arguments.append('-ot')
        arguments.append(self.TYPES[self.parameterAsEnum(
            parameters, self.DATA_TYPE, context)])

        options = self.parameterAsString(parameters, self.OPTIONS, context)
        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        if self.EXTRA in parameters and parameters[self.EXTRA] not in (None,
                                                                       ''):
            extra = self.parameterAsString(parameters, self.EXTRA, context)
            arguments.append(extra)

        if self.parameterAsBoolean(parameters, self.DIR_FOR_ROW, context):
            arguments.append('-useDirForEachRow')

        if self.parameterAsBoolean(parameters, self.ONLY_PYRAMIDS, context):
            arguments.append('-pyramidOnly')

        csvFile = self.parameterAsFileOutput(parameters, self.OUTPUT_CSV,
                                             context)
        if csvFile:
            arguments.append('-csv')
            arguments.append(csvFile)
            delimiter = self.parameterAsString(parameters, self.DELIMITER,
                                               context)
            if delimiter:
                arguments.append('-csvDelim')
                arguments.append(delimiter)

        arguments.append('-targetDir')
        arguments.append(
            self.parameterAsString(parameters, self.OUTPUT, context))

        layers = [
            l.source()
            for l in self.parameterAsLayerList(parameters, self.INPUT, context)
        ]
        arguments.extend(layers)

        return [
            self.commandName() + ('.bat' if isWindows() else '.py'),
            GdalUtils.escapeAndJoin(arguments)
        ]
Exemplo n.º 34
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        arguments = []

        arguments.append('-ps')
        arguments.append(
            str(self.parameterAsInt(parameters, self.TILE_SIZE_X, context)))
        arguments.append(
            str(self.parameterAsInt(parameters, self.TILE_SIZE_Y, context)))

        arguments.append('-overlap')
        arguments.append(
            str(self.parameterAsInt(parameters, self.OVERLAP, context)))

        arguments.append('-levels')
        arguments.append(
            str(self.parameterAsInt(parameters, self.LEVELS, context)))

        crs = self.parameterAsCrs(parameters, self.SOURCE_CRS, context)
        if crs.isValid():
            arguments.append('-s_srs')
            arguments.append(crs.authid())

        arguments.append('-r')
        arguments.append(self.methods[self.parameterAsEnum(
            parameters, self.RESAMPLING, context)][1])

        arguments.append('-ot')
        arguments.append(self.TYPES[self.parameterAsEnum(
            parameters, self.DATA_TYPE, context)])

        options = self.parameterAsString(parameters, self.OPTIONS, context)
        if options:
            arguments.append('-co')
            arguments.append(options)

        if self.parameterAsBool(parameters, self.DIR_FOR_ROW, context):
            arguments.append('-pyramidOnly')

        if self.parameterAsBool(parameters, self.ONLY_PYRAMIDS, context):
            arguments.append('-useDirForEachRow')

        csvFile = self.parameterAsFileOutput(parameters, self.OUTPUT_CSV,
                                             context)
        if csvFile:
            arguments.append('-csv')
            arguments.append(csvFile)
            delimiter = self.parameterAsString(parameters, self.DELIMITER,
                                               context)
            if delimiter:
                arguments.append('-csvDelim')
                arguments.append('"{}"'.format(delimiter))

        arguments.append('-targetDir')
        arguments.append(
            self.parameterAsString(parameters, self.OUTPUT, context))

        layers = [
            l.source()
            for l in self.parameterAsLayerList(parameters, self.INPUT, context)
        ]
        arguments.extend(layers)

        commands = []
        if isWindows():
            commands = [
                'cmd.exe', '/C ', 'gdal_retile.bat',
                GdalUtils.escapeAndJoin(arguments)
            ]
        else:
            commands = ['gdal_retile.py', GdalUtils.escapeAndJoin(arguments)]

        return commands
Exemplo n.º 35
0
    def __init__(self):
        super().__init__()
        # 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.setFlags(param.flags()
                           | QgsProcessingParameterDefinition.FlagAdvanced)
            self.addParameter(param)

        self.addOutput(
            OutputDirectory(
                self.TARGETDIR,
                self.tr('The directory where the tile result is created')))
Exemplo n.º 36
0
    def getConsoleCommands(self, parameters):

        arguments = []

        if self.getParameterValue(self.RTYPE):
            arguments.append('-ot')
            arguments.append(self.TYPE[self.getParameterValue(self.RTYPE)])

        arguments.append('-of')
        arguments.append(
            list(
                GdalUtils.getSupportedRasters().keys())[self.getParameterValue(
                    self.FORMAT)])

        if self.getParameterValue(self.PIXELSIZE):
            pixelSize = self.getParameterValue(self.PIXELSIZE)
            if re.match(r'\d+ \d+', pixelSize):
                xsize, ysize = pixelSize.split(' ')
                arguments.append('-ps')
                arguments.append(xsize)
                arguments.append(ysize)

        if self.getParameterValue(self.ONLYPYRAMIDS):
            arguments.append('-pyramidOnly')

        if self.getParameterValue(self.USEDIRFOREACHROW):
            arguments.append('-useDirForEachRow')

        ssrs = str(self.getParameterValue(self.S_SRS))
        if len(ssrs) > 0:
            arguments.append('-s_srs')
            arguments.append(ssrs)

        if self.getParameterValue(self.PYRAMIDLEVELS):
            arguments.append('-levels')
            arguments.append(str(self.getParameterValue(self.PYRAMIDLEVELS)))

        arguments.append('-r')
        arguments.append(self.ALGO[self.getParameterValue(self.ALGORITHM)])

        # Handle CSV
        if self.getParameterValue(self.CSVFILE):
            arguments.append('-csv')
            arguments.append(self.getParameterValue(self.CSVFILE))

        if self.getParameterValue(self.CSVFILE) and self.getParameterValue(
                self.CSVDELIM):
            arguments.append('-csvDelim')
            arguments.append(self.getParameterValue(self.CSVDELIM))

        # Handle Shp
        if self.getParameterValue(self.TILEINDEX):
            arguments.append('-tileIndex')
            arguments.append(self.getParameterValue(self.TILEINDEX))

        if self.getParameterValue(self.TILEINDEX) and self.getParameterValue(
                self.TILEINDEXFIELD):
            arguments.append('-tileIndexField')
            arguments.append(self.getParameterValue(self.TILEINDEXFIELD))

        arguments.append('-targetDir')
        arguments.append(self.getOutputValue(self.TARGETDIR))

        arguments.extend(self.getParameterValue(self.INPUT).split(';'))

        commands = []
        if isWindows():
            commands = [
                'cmd.exe', '/C ', 'gdal_retile.bat',
                GdalUtils.escapeAndJoin(arguments)
            ]
        else:
            commands = ['gdal_retile.py', GdalUtils.escapeAndJoin(arguments)]

        return commands
Exemplo n.º 37
0
 def getSupportedOutputRasterExtensions():
     # We use the same extensions than GDAL because:
     # - GRASS is also using GDAL for raster imports.
     # - Chances that GRASS is compiled with another version of
     # GDAL than QGIS are very limited!
     return GdalUtils.getSupportedOutputRasterExtensions()
Exemplo n.º 38
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        connection = self.parameterAsString(parameters, self.DATABASE, context)
        uri = uri_from_name(connection)
        if executing:
            # to get credentials input when needed
            uri = GeoDB(uri=uri).uri

        ogrLayer, layername = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, executing)
        shapeEncoding = self.parameterAsString(parameters, self.SHAPE_ENCODING, context)
        ssrs = self.parameterAsCrs(parameters, self.S_SRS, context).authid()
        tsrs = self.parameterAsCrs(parameters, self.T_SRS, context).authid()
        asrs = self.parameterAsCrs(parameters, self.A_SRS, context).authid()
        table = self.parameterAsString(parameters, self.TABLE, context)
        schema = self.parameterAsString(parameters, self.SCHEMA, context)
        pk = self.parameterAsString(parameters, self.PK, context)
        pkstring = "-lco FID=" + pk
        primary_key = self.parameterAsString(parameters, self.PRIMARY_KEY, context)
        geocolumn = self.parameterAsString(parameters, self.GEOCOLUMN, context)
        geocolumnstring = "-lco GEOMETRY_NAME=" + geocolumn
        dim = self.DIMLIST[self.parameterAsEnum(parameters, self.DIM, context)]
        dimstring = "-lco DIM=" + dim
        simplify = self.parameterAsString(parameters, self.SIMPLIFY, context)
        segmentize = self.parameterAsString(parameters, self.SEGMENTIZE, context)
        spat = self.parameterAsExtent(parameters, self.SPAT, context)
        clip = self.parameterAsBool(parameters, self.CLIP, context)
        where = self.parameterAsString(parameters, self.WHERE, context)
        wherestring = '-where "' + where + '"'
        gt = self.parameterAsString(parameters, self.GT, context)
        overwrite = self.parameterAsBool(parameters, self.OVERWRITE, context)
        append = self.parameterAsBool(parameters, self.APPEND, context)
        addfields = self.parameterAsBool(parameters, self.ADDFIELDS, context)
        launder = self.parameterAsBool(parameters, self.LAUNDER, context)
        launderstring = "-lco LAUNDER=NO"
        index = self.parameterAsBool(parameters, self.INDEX, context)
        indexstring = "-lco SPATIAL_INDEX=OFF"
        skipfailures = self.parameterAsBool(parameters, self.SKIPFAILURES, context)
        promotetomulti = self.parameterAsBool(parameters, self.PROMOTETOMULTI, context)
        precision = self.parameterAsBool(parameters, self.PRECISION, context)
        options = self.parameterAsString(parameters, self.OPTIONS, context)

        arguments = []
        arguments.append('-progress')
        arguments.append('--config PG_USE_COPY YES')
        if shapeEncoding:
            arguments.append('--config')
            arguments.append('SHAPE_ENCODING')
            arguments.append('"' + shapeEncoding + '"')
        arguments.append('-f')
        arguments.append('PostgreSQL')
        arguments.append('PG:"')
        for token in uri.connectionInfo(executing).split(' '):
            arguments.append(token)
        arguments.append('active_schema={}'.format(schema or 'public'))
        arguments.append('"')
        arguments.append(dimstring)
        arguments.append(ogrLayer)
        arguments.append(layername)
        if index:
            arguments.append(indexstring)
        if launder:
            arguments.append(launderstring)
        if append:
            arguments.append('-append')
        if addfields:
            arguments.append('-addfields')
        if overwrite:
            arguments.append('-overwrite')
        if len(self.GEOMTYPE[self.parameterAsEnum(parameters, self.GTYPE, context)]) > 0:
            arguments.append('-nlt')
            arguments.append(self.GEOMTYPE[self.parameterAsEnum(parameters, self.GTYPE, context)])
        if len(geocolumn) > 0:
            arguments.append(geocolumnstring)
        if len(pk) > 0:
            arguments.append(pkstring)
        elif primary_key is not None:
            arguments.append("-lco FID=" + primary_key)
        if len(table) == 0:
            table = layername.lower()
        if schema:
            table = '{}.{}'.format(schema, table)
        arguments.append('-nln')
        arguments.append(table)
        if len(ssrs) > 0:
            arguments.append('-s_srs')
            arguments.append(ssrs)
        if len(tsrs) > 0:
            arguments.append('-t_srs')
            arguments.append(tsrs)
        if len(asrs) > 0:
            arguments.append('-a_srs')
            arguments.append(asrs)
        if not spat.isNull():
            arguments.append('-spat')
            arguments.append(spat.xMinimum())
            arguments.append(spat.yMinimum())
            arguments.append(spat.xMaximum())
            arguments.append(spat.yMaximum())
            if clip:
                arguments.append('-clipsrc spat_extent')
        if skipfailures:
            arguments.append('-skipfailures')
        if where:
            arguments.append(wherestring)
        if len(simplify) > 0:
            arguments.append('-simplify')
            arguments.append(simplify)
        if len(segmentize) > 0:
            arguments.append('-segmentize')
            arguments.append(segmentize)
        if len(gt) > 0:
            arguments.append('-gt')
            arguments.append(gt)
        if promotetomulti:
            arguments.append('-nlt PROMOTE_TO_MULTI')
        if precision is False:
            arguments.append('-lco PRECISION=NO')
        if len(options) > 0:
            arguments.append(options)

        commands = []
        if isWindows():
            commands = ['cmd.exe', '/C ', 'ogr2ogr.exe',
                        GdalUtils.escapeAndJoin(arguments)]
        else:
            commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]

        return commands
Exemplo n.º 39
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        distance = self.parameterAsDouble(parameters, self.MAX_DISTANCE,
                                          context)
        replaceValue = self.parameterAsDouble(parameters, self.REPLACE,
                                              context)
        nodata = self.parameterAsDouble(parameters, self.NODATA, context)
        options = self.parameterAsString(parameters, self.OPTIONS, context)
        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        arguments = []
        arguments.append('-srcband')
        arguments.append(
            str(self.parameterAsInt(parameters, self.BAND, context)))

        arguments.append('-distunits')
        arguments.append(self.distanceUnits[self.parameterAsEnum(
            parameters, self.UNITS, context)][1])

        values = self.parameterAsString(parameters, self.VALUES, context)
        if values:
            arguments.append('-values')
            arguments.append(values)

        if distance:
            arguments.append('-maxdist')
            arguments.append(str(distance))

        if nodata:
            arguments.append('-nodata')
            arguments.append(str(nodata))

        if replaceValue:
            arguments.append('-fixed-buf-val')
            arguments.append(str(replaceValue))

        arguments.append('-ot')
        arguments.append(self.TYPES[self.parameterAsEnum(
            parameters, self.DATA_TYPE, context)])

        arguments.append('-of')
        arguments.append(
            QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))

        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        arguments.append(inLayer.source())
        arguments.append(out)

        commands = []
        if isWindows():
            commands = [
                'cmd.exe', '/C ', 'gdal_proximity.bat',
                GdalUtils.escapeAndJoin(arguments)
            ]
        else:
            commands = [
                'gdal_proximity.py',
                GdalUtils.escapeAndJoin(arguments)
            ]

        return commands
Exemplo n.º 40
0
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT)
        noData = self.getParameterValue(self.NO_DATA)
        rastext = str(self.getParameterValue(self.RAST_EXT))
        opts = self.getParameterValue(self.OPTIONS)
        out = self.getOutputValue(self.OUTPUT)

        ogrLayer = ogrConnectionString(inLayer)[1:-1]

        if noData is not None:
            noData = str(noData)

        arguments = []
        arguments.append('-a')
        arguments.append(str(self.getParameterValue(self.FIELD)))

        arguments.append('-ot')
        arguments.append(self.TYPE[self.getParameterValue(self.RTYPE)])
        dimType = self.getParameterValue(self.DIMENSIONS)
        arguments.append('-of')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(out))

        regionCoords = rastext.split(',')
        try:
            rastext = []
            rastext.append('-te')
            rastext.append(regionCoords[0])
            rastext.append(regionCoords[2])
            rastext.append(regionCoords[1])
            rastext.append(regionCoords[3])
        except IndexError:
            rastext = []
        if rastext:
            arguments.extend(rastext)

        if dimType == 0:
            # size in pixels
            arguments.append('-ts')
            arguments.append(str(self.getParameterValue(self.WIDTH)))
            arguments.append(str(self.getParameterValue(self.HEIGHT)))
        else:
            # resolution in map units per pixel
            arguments.append('-tr')
            arguments.append(str(self.getParameterValue(self.WIDTH)))
            arguments.append(str(self.getParameterValue(self.HEIGHT)))

        if noData and len(noData) > 0:
            arguments.append('-a_nodata')
            arguments.append(noData)

        if opts:
            arguments.append('-co')
            arguments.append(opts)

        arguments.append('-l')

        print(ogrLayerName(inLayer))
        arguments.append(ogrLayerName(inLayer))
        arguments.append(ogrLayer)

        arguments.append(out)
        return ['gdal_rasterize', GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 41
0
    def processAlgorithm(self, parameters, context, feedback):
        expression = self.parameterAsString(parameters, self.EXPRESSION,
                                            context)
        layers = self.parameterAsLayerList(parameters, self.LAYERS, context)

        layersDict = {}
        if layers:
            layersDict = {
                os.path.basename(lyr.source().split(".")[0]): lyr
                for lyr in layers
            }

        crs = self.parameterAsCrs(parameters, self.CRS, context)
        if not layers and not crs.isValid():
            raise QgsProcessingException(
                self.tr("No reference layer selected nor CRS provided"))

        if not crs.isValid() and layers:
            crs = list(layersDict.values())[0].crs()

        bbox = self.parameterAsExtent(parameters, self.EXTENT, context)
        if not layers and bbox.isNull():
            raise QgsProcessingException(
                self.tr("No reference layer selected nor extent box provided"))

        if not bbox.isNull():
            bboxCrs = self.parameterAsExtentCrs(parameters, self.EXTENT,
                                                context)
            if bboxCrs != crs:
                transform = QgsCoordinateTransform(bboxCrs, crs,
                                                   context.project())
                bbox = transform.transformBoundingBox(bbox)

        if bbox.isNull() and layers:
            bbox = QgsProcessingUtils.combineLayerExtents(layers, crs)

        cellsize = self.parameterAsDouble(parameters, self.CELLSIZE, context)
        if not layers and cellsize == 0:
            raise QgsProcessingException(
                self.tr(
                    "No reference layer selected nor cellsize value provided"))

        def _cellsize(layer):
            ext = layer.extent()
            if layer.crs() != crs:
                transform = QgsCoordinateTransform(layer.crs(), crs,
                                                   context.project())
                ext = transform.transformBoundingBox(ext)
            return (ext.xMaximum() - ext.xMinimum()) / layer.width()

        if cellsize == 0:
            cellsize = min([_cellsize(lyr) for lyr in layersDict.values()])

        for lyr in QgsProcessingUtils.compatibleRasterLayers(
                context.project()):
            name = lyr.name()
            if (name + "@") in expression:
                layersDict[name] = lyr

        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                ref = '{:s}@{:d}'.format(name, n + 1)
                if ref in expression:
                    entry = QgsRasterCalculatorEntry()
                    entry.ref = ref
                    entry.raster = lyr
                    entry.bandNumber = n + 1
                    entries.append(entry)

        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        width = math.floor((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = math.floor((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)
        calc = QgsRasterCalculator(expression, output, driverName, bbox, crs,
                                   width, height, entries)

        res = calc.processCalculation(feedback)
        if res == QgsRasterCalculator.ParserError:
            raise QgsProcessingException(self.tr("Error parsing formula"))

        return {self.OUTPUT: output}
Exemplo n.º 42
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        out = self.getOutputValue(self.OUTPUT)
        extra = self.getParameterValue(self.EXTRA)
        if extra is not None:
            extra = str(extra)
        #debug = self.getParameterValue(self.DEBUG)
        formula = self.getParameterValue(self.FORMULA)
        noData = self.getParameterValue(self.NO_DATA)
        if noData is not None:
            noData = str(noData)

        arguments = []
        arguments.append('--calc')
        arguments.append('"' + formula + '"')
        arguments.append('--format')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(out))
        arguments.append('--type')
        arguments.append(self.TYPE[self.getParameterValue(self.RTYPE)])
        if noData and len(noData) > 0:
            arguments.append('--NoDataValue')
            arguments.append(noData)
        if extra and len(extra) > 0:
            arguments.append(extra)
        #if debug:
        #    arguments.append('--debug')
        arguments.append('-A')
        arguments.append(self.getParameterValue(self.INPUT_A))
        if self.getParameterValue(self.BAND_A):
            arguments.append('--A_band ' + self.getParameterValue(self.BAND_A))
        if self.getParameterValue(self.INPUT_B):
            arguments.append('-B')
            arguments.append(self.getParameterValue(self.INPUT_B))
            if self.getParameterValue(self.BAND_B):
                arguments.append('--B_band ' +
                                 self.getParameterValue(self.BAND_B))
        if self.getParameterValue(self.INPUT_C):
            arguments.append('-C')
            arguments.append(self.getParameterValue(self.INPUT_C))
            if self.getParameterValue(self.BAND_C):
                arguments.append('--C_band ' +
                                 self.getParameterValue(self.BAND_C))
        if self.getParameterValue(self.INPUT_D):
            arguments.append('-D')
            arguments.append(self.getParameterValue(self.INPUT_D))
            if self.getParameterValue(self.BAND_D):
                arguments.append('--D_band ' +
                                 self.getParameterValue(self.BAND_D))
        if self.getParameterValue(self.INPUT_E):
            arguments.append('-E')
            arguments.append(self.getParameterValue(self.INPUT_E))
            if self.getParameterValue(self.BAND_E):
                arguments.append('--E_band ' +
                                 self.getParameterValue(self.BAND_E))
        if self.getParameterValue(self.INPUT_F):
            arguments.append('-F')
            arguments.append(self.getParameterValue(self.INPUT_F))
            if self.getParameterValue(self.BAND_F):
                arguments.append('--F_band ' +
                                 self.getParameterValue(self.BAND_F))
        arguments.append('--outfile')
        arguments.append(out)

        if isWindows():
            return ['gdal_calc', GdalUtils.escapeAndJoin(arguments)]
        else:
            return ['gdal_calc.py', GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 43
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        arguments = ['hillshade']
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        if inLayer is None:
            raise QgsProcessingException(
                self.invalidRasterError(parameters, self.INPUT))

        arguments.append(inLayer.source())

        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        self.setOutputValue(self.OUTPUT, out)
        arguments.append(out)

        arguments.append('-of')
        arguments.append(
            QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))

        arguments.append('-b')
        arguments.append(
            str(self.parameterAsInt(parameters, self.BAND, context)))
        arguments.append('-z')
        arguments.append(
            str(self.parameterAsDouble(parameters, self.Z_FACTOR, context)))
        arguments.append('-s')
        arguments.append(
            str(self.parameterAsDouble(parameters, self.SCALE, context)))

        multidirectional = self.parameterAsBool(parameters,
                                                self.MULTIDIRECTIONAL, context)
        # azimuth and multidirectional are mutually exclusive
        if not multidirectional:
            arguments.append('-az')
            arguments.append(
                str(self.parameterAsDouble(parameters, self.AZIMUTH, context)))

        arguments.append('-alt')
        arguments.append(
            str(self.parameterAsDouble(parameters, self.ALTITUDE, context)))

        if self.parameterAsBool(parameters, self.COMPUTE_EDGES, context):
            arguments.append('-compute_edges')

        if self.parameterAsBool(parameters, self.ZEVENBERGEN, context):
            arguments.append('-alg')
            arguments.append('ZevenbergenThorne')

        if self.parameterAsBool(parameters, self.COMBINED, context):
            arguments.append('-combined')

        if multidirectional:
            arguments.append('-multidirectional')

        options = self.parameterAsString(parameters, self.OPTIONS, context)
        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 44
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        extra = self.parameterAsString(parameters, self.EXTRA, context)
        # if extra is not None:
        #     extra = str(extra)
        #debug = self.getParameterValue(parameters, self.DEBUG)
        formula = self.parameterAsString(parameters, self.FORMULA, context)
        if self.NO_DATA in parameters and parameters[self.NO_DATA] is not None:
            noData = self.parameterAsDouble(parameters, self.NO_DATA, context)
        else:
            noData = None

        arguments = []
        arguments.append('--calc "{}"'.format(formula))
        arguments.append('--format')
        arguments.append(GdalUtils.getFormatShortNameFromFilename(out))
        arguments.append('--type')
        arguments.append(self.TYPE[self.parameterAsEnum(parameters, self.RTYPE, context)])
        if noData is not None:
            arguments.append('--NoDataValue')
            arguments.append(noData)
        if extra and len(extra) > 0:
            arguments.append(extra)
        #if debug:
        #    arguments.append('--debug')
        layer = self.parameterAsRasterLayer(parameters, self.INPUT_A, context)
        if layer is None:
            raise QgsProcessingException(self.invalidRasterError(parameters, self.INPUT_A))
        arguments.append('-A')
        arguments.append(layer.source())
        if self.parameterAsString(parameters, self.BAND_A, context):
            arguments.append('--A_band ' + self.parameterAsString(parameters, self.BAND_A, context))

        if self.INPUT_B in parameters and parameters[self.INPUT_B] is not None:
            layer = self.parameterAsRasterLayer(parameters, self.INPUT_B, context)
            if layer is None:
                raise QgsProcessingException(self.invalidRasterError(parameters, self.INPUT_B))
            arguments.append('-B')
            arguments.append(layer.source())
            if self.parameterAsString(parameters, self.BAND_B, context):
                arguments.append('--B_band ' + self.parameterAsString(parameters, self.BAND_B, context))

        if self.INPUT_C in parameters and parameters[self.INPUT_C] is not None:
            layer = self.parameterAsRasterLayer(parameters, self.INPUT_C, context)
            if layer is None:
                raise QgsProcessingException(self.invalidRasterError(parameters, self.INPUT_C))
            arguments.append('-C')
            arguments.append(layer.source())
            if self.parameterAsString(parameters, self.BAND_C, context):
                arguments.append('--C_band ' + self.parameterAsString(parameters, self.BAND_C, context))

        if self.INPUT_D in parameters and parameters[self.INPUT_D] is not None:
            layer = self.parameterAsRasterLayer(parameters, self.INPUT_D, context)
            if layer is None:
                raise QgsProcessingException(self.invalidRasterError(parameters, self.INPUT_D))
            arguments.append('-D')
            arguments.append(layer.source())
            if self.parameterAsString(parameters, self.BAND_D, context):
                arguments.append('--D_band ' + self.parameterAsString(parameters, self.BAND_D, context))

        if self.INPUT_E in parameters and parameters[self.INPUT_E] is not None:
            layer = self.parameterAsRasterLayer(parameters, self.INPUT_E, context)
            if layer is None:
                raise QgsProcessingException(self.invalidRasterError(parameters, self.INPUT_E))
            arguments.append('-E')
            arguments.append(layer.source())
            if self.parameterAsString(parameters, self.BAND_E, context):
                arguments.append('--E_band ' + self.parameterAsString(parameters, self.BAND_E, context))

        if self.INPUT_F in parameters and parameters[self.INPUT_F] is not None:
            layer = self.parameterAsRasterLayer(parameters, self.INPUT_F, context)
            if layer is None:
                raise QgsProcessingException(self.invalidRasterError(parameters, self.INPUT_F))
            arguments.append('-F')
            arguments.append(layer.source())
            if self.parameterAsString(parameters, self.BAND_F, context):
                arguments.append('--F_band ' + self.parameterAsString(parameters, self.BAND_F, context))

        options = self.parameterAsString(parameters, self.OPTIONS, context)
        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        arguments.append('--outfile')
        arguments.append(out)

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 45
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        fields = self.parameterAsSource(parameters, self.INPUT,
                                        context).fields()
        ogrLayer, layerName = self.getOgrCompatibleSource(
            self.INPUT, parameters, context, feedback, executing)
        geometry = self.parameterAsString(parameters, self.GEOMETRY, context)
        fieldName = self.parameterAsString(parameters, self.FIELD, context)

        options = self.parameterAsString(parameters, self.OPTIONS, context)
        outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        output, outputFormat = GdalUtils.ogrConnectionStringAndFormat(
            outFile, context)

        other_fields = []
        for f in fields:
            if f.name() == geometry:
                continue

            other_fields.append(f.name())

        if other_fields:
            other_fields = ', {}'.format(','.join(other_fields))
        else:
            other_fields = ''

        arguments = []
        arguments.append(output)
        arguments.append(ogrLayer)
        arguments.append('-dialect')
        arguments.append('sqlite')
        arguments.append('-sql')

        tokens = []
        if self.parameterAsBool(parameters, self.COUNT_FEATURES, context):
            tokens.append("COUNT({}) AS count".format(geometry))

        if self.parameterAsBool(parameters, self.COMPUTE_AREA, context):
            tokens.append(
                "SUM(ST_Area({0})) AS area, ST_Perimeter(ST_Union({0})) AS perimeter"
                .format(geometry))

        statsField = self.parameterAsString(parameters, self.FIELD, context)
        if statsField and self.parameterAsBool(
                parameters, self.COMPUTE_STATISTICS, context):
            tokens.append(
                "SUM({0}) AS sum, MIN({0}) AS min, MAX({0}) AS max, AVG({0}) AS avg"
                .format(statsField))

        params = ','.join(tokens)
        if params:
            if self.parameterAsBool(parameters, self.KEEP_ATTRIBUTES, context):
                sql = "SELECT ST_Union({}) AS {}{}, {} FROM {} GROUP BY {}".format(
                    geometry, geometry, other_fields, params, layerName,
                    fieldName)
            else:
                sql = "SELECT ST_Union({}) AS {}, {}, {} FROM {} GROUP BY {}".format(
                    geometry, geometry, fieldName, params, layerName,
                    fieldName)
        else:
            if self.parameterAsBool(parameters, self.KEEP_ATTRIBUTES, context):
                sql = "SELECT ST_Union({}) AS {}{} FROM {} GROUP BY {}".format(
                    geometry, geometry, other_fields, layerName, fieldName)
            else:
                sql = "SELECT ST_Union({}) AS {}, {} FROM {} GROUP BY {}".format(
                    geometry, geometry, fieldName, layerName, fieldName)

        arguments.append(sql)

        if self.parameterAsBool(parameters, self.EXPLODE_COLLECTIONS, context):
            arguments.append('-explodecollections')

        if options:
            arguments.append(options)

        if outputFormat:
            arguments.append('-f {}'.format(outputFormat))

        return ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 46
0
    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        ogrLayer, layerName = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, executing)

        arguments = ['-l']
        arguments.append(layerName)

        fieldName = self.parameterAsString(parameters, self.FIELD, context)
        if fieldName:
            arguments.append('-a')
            arguments.append(fieldName)
        else:
            arguments.append('-burn')
            arguments.append(self.parameterAsDouble(parameters, self.BURN, context))

        units = self.parameterAsEnum(parameters, self.UNITS, context)
        if units == 0:
            arguments.append('-ts')
        else:
            arguments.append('-tr')
        arguments.append(self.parameterAsDouble(parameters, self.WIDTH, context))
        arguments.append(self.parameterAsDouble(parameters, self.HEIGHT, context))

        initValue = self.parameterAsDouble(parameters, self.INIT, context)
        if initValue:
            arguments.append('-init')
            arguments.append(initValue)

        if self.parameterAsBool(parameters, self.INVERT, context):
            arguments.append('-i')

        if self.parameterAsBool(parameters, self.ALL_TOUCH, context):
            arguments.append('-at')

        nodata = self.parameterAsDouble(parameters, self.NODATA, context)
        if nodata:
            arguments.append('-a_nodata')
            arguments.append(nodata)

        extent = self.parameterAsExtent(parameters, self.EXTENT, context)
        if not extent.isNull():
            arguments.append('-te')
            arguments.append(extent.xMinimum())
            arguments.append(extent.yMinimum())
            arguments.append(extent.xMaximum())
            arguments.append(extent.yMaximum())

        arguments.append('-ot')
        arguments.append(self.TYPES[self.parameterAsEnum(parameters, self.DATA_TYPE, context)])

        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        arguments.append('-of')
        arguments.append(QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))
        options = self.parameterAsString(parameters, self.OPTIONS, context)

        if options:
            arguments.append('-co')
            arguments.append(options)

        arguments.append(ogrLayer)
        arguments.append(out)

        return ['gdal_rasterize', GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 47
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        arguments = []

        arguments.append('-p')
        arguments.append(self.profiles[self.parameterAsEnum(
            parameters, self.PROFILE, context)][1])

        zoom = self.parameterAsString(parameters, self.ZOOM, context)
        if zoom:
            arguments.append('-z')
            arguments.append(str(zoom))

        arguments.append('-w')
        arguments.append(self.viewers[self.parameterAsEnum(
            parameters, self.VIEWER, context)][1])

        title = self.parameterAsString(parameters, self.TITLE, context)
        if title:
            arguments.append('-t')
            arguments.append(title)

        copying = self.parameterAsString(parameters, self.COPYRIGHT, context)
        if copying:
            arguments.append('-c')
            arguments.append(copying)

        arguments.append('-r')
        arguments.append(self.methods[self.parameterAsEnum(
            parameters, self.RESAMPLING, context)][1])

        crs = self.parameterAsCrs(parameters, self.SOURCE_CRS, context)
        if crs.isValid():
            arguments.append('-s')
            arguments.append(GdalUtils.gdal_crs_string(crs))

        if self.NODATA in parameters and parameters[self.NODATA] is not None:
            nodata = self.parameterAsDouble(parameters, self.NODATA, context)
            arguments.append('-a')
            arguments.append(str(nodata))

        url = self.parameterAsString(parameters, self.URL, context)
        if url:
            arguments.append('-u')
            arguments.append(url)

        key = self.parameterAsString(parameters, self.GOOGLE_KEY, context)
        if key:
            arguments.append('-g')
            arguments.append(key)

        key = self.parameterAsString(parameters, self.BING_KEY, context)
        if key:
            arguments.append('-b')
            arguments.append(key)

        if self.parameterAsBool(parameters, self.RESUME, context):
            arguments.append('-e')

        if self.parameterAsBool(parameters, self.KML, context):
            arguments.append('-k')

        if self.parameterAsBool(parameters, self.NO_KML, context):
            arguments.append('-n')

        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        if inLayer is None:
            raise QgsProcessingException(
                self.invalidRasterError(parameters, self.INPUT))

        arguments.append(inLayer.source())
        arguments.append(
            self.parameterAsString(parameters, self.OUTPUT, context))

        commands = []
        if isWindows():
            commands = [
                'cmd.exe', '/C ',
                self.commandName() + '.bat',
                GdalUtils.escapeAndJoin(arguments)
            ]
        else:
            commands = [
                self.commandName() + '.py',
                GdalUtils.escapeAndJoin(arguments)
            ]

        return commands
Exemplo n.º 48
0
    def processAlgorithm(self, parameters, context, feedback):
        expression = self.parameterAsString(parameters, self.EXPRESSION,
                                            context)
        layers = self.parameterAsLayerList(parameters, self.LAYERS, context)

        layersDict = {}
        if layers:
            layersDict = {lyr.source(): lyr for lyr in layers}

        crs = self.parameterAsCrs(parameters, self.CRS, context)
        if crs is None or not crs.isValid():
            if not layers:
                raise QgsProcessingException(
                    self.tr("No reference layer selected nor CRS provided"))
            else:
                crs = list(layersDict.values())[0].crs()

        bbox = self.parameterAsExtent(parameters, self.EXTENT, context)
        if bbox.isNull() and not layers:
            raise QgsProcessingException(
                self.tr("No reference layer selected nor extent box provided"))

        if not bbox.isNull():
            bboxCrs = self.parameterAsExtentCrs(parameters, self.EXTENT,
                                                context)
            if bboxCrs != crs:
                transform = QgsCoordinateTransform(bboxCrs, crs,
                                                   context.project())
                bbox = transform.transformBoundingBox(bbox)

        if bbox.isNull() and layers:
            bbox = QgsProcessingUtils.combineLayerExtents(layers, crs)

        cellsize = self.parameterAsDouble(parameters, self.CELLSIZE, context)
        if cellsize == 0 and not layers:
            raise QgsProcessingException(
                self.tr(
                    "No reference layer selected nor cellsize value provided"))

        def _cellsize(layer):
            ext = layer.extent()
            if layer.crs() != crs:
                transform = QgsCoordinateTransform(layer.crs(), crs,
                                                   context.project())
                ext = transform.transformBoundingBox(ext)
            return (ext.xMaximum() - ext.xMinimum()) / layer.width()

        if cellsize == 0:
            cellsize = min([_cellsize(lyr) for lyr in layersDict.values()])

        # check for layers available in the model
        layersDictCopy = layersDict.copy(
        )  # need a shallow copy because next calls invalidate iterator
        for lyr in layersDictCopy.values():
            expression = self.mappedNameToLayer(lyr, expression, layersDict,
                                                context)

        # check for layers available in the project
        for lyr in QgsProcessingUtils.compatibleRasterLayers(
                context.project()):
            expression = self.mappedNameToLayer(lyr, expression, layersDict,
                                                context)

        # create the list of layers to be passed as inputs to RasterCalculaltor
        # at this phase expression has been modified to match available layers
        # in the current scope
        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                ref = '{:s}@{:d}'.format(name, n + 1)

                if ref in expression:
                    entry = QgsRasterCalculatorEntry()
                    entry.ref = ref
                    entry.raster = lyr
                    entry.bandNumber = n + 1
                    entries.append(entry)

        # Append any missing entry from the current project
        for entry in QgsRasterCalculatorEntry.rasterEntries():
            if not [e for e in entries if e.ref == entry.ref]:
                entries.append(entry)

        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        width = round((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = round((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)

        calc = QgsRasterCalculator(expression, output, driverName, bbox, crs,
                                   width, height, entries)

        res = calc.processCalculation(feedback)
        if res == QgsRasterCalculator.ParserError:
            raise QgsProcessingException(self.tr("Error parsing formula"))

        return {self.OUTPUT: output}
Exemplo n.º 49
0
    def getConsoleCommands(self):

        arguments = []

        if self.getParameterValue(self.PROFILE):
            arguments.append('-p')
            arguments.append(self.PROFILES[self.getParameterValue(self.PROFILE)])

        if self.getParameterValue(self.RESAMPLING):
            arguments.append('-r')
            arguments.append(self.RESAMPLINGS[self.getParameterValue(self.RESAMPLING)])

        ssrs = str(self.getParameterValue(self.S_SRS))
        if len(ssrs) > 0:
            arguments.append('-s')
            arguments.append(ssrs)

        if self.getParameterValue(self.ZOOM):
            arguments.append('-z')
            arguments.append(str(self.getParameterValue(self.ZOOM)))

        if self.getParameterValue(self.RESUME):
            arguments.append('-e')

        if self.getParameterValue(self.NODATA):
            arguments.append('-a')
            arguments.append(str(self.getParameterValue(self.NODATA)))

        # KML arguments
        if self.getParameterValue(self.FORCEKML):
            arguments.append('-k')

        if self.getParameterValue(self.NOKML):
            arguments.append('-n')

        if self.getParameterValue(self.URL):
            arguments.append('-u')
            arguments.append(str(self.getParameterValue(self.URL)))

        # Web viewer arguments
        if self.getParameterValue(self.WEBVIEWER):
            arguments.append('-w')
            arguments.append(self.WEBVIEWERS[self.getParameterValue(self.WEBVIEWER)])

        parameters = {self.TITLE: '-t', self.COPYRIGHT: '-c',
                      self.GOOGLEKEY: '-g', self.BINGKEY: '-b'}
        for arg, parameter in list(parameters.items()):
            if self.getParameterValue(arg):
                arguments.append(parameter)
                arguments.append(self.getParameterValue(arg))

        arguments.append(self.getParameterValue(self.INPUT))
        arguments.append(self.getOutputValue(self.OUTPUTDIR))

        commands = []
        if isWindows():
            commands = ['cmd.exe', '/C ', 'gdal2tiles.bat',
                        GdalUtils.escapeAndJoin(arguments)]
        else:
            commands = ['gdal2tiles.py',
                        GdalUtils.escapeAndJoin(arguments)]

        return commands
Exemplo n.º 50
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        if inLayer is None:
            raise QgsProcessingException(
                self.invalidRasterError(parameters, self.INPUT))

        distance = self.parameterAsDouble(parameters, self.MAX_DISTANCE,
                                          context)
        replaceValue = self.parameterAsDouble(parameters, self.REPLACE,
                                              context)
        if self.NODATA in parameters and parameters[self.NODATA] is not None:
            nodata = self.parameterAsDouble(parameters, self.NODATA, context)
        else:
            nodata = None
        options = self.parameterAsString(parameters, self.OPTIONS, context)
        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        self.setOutputValue(self.OUTPUT, out)

        arguments = []
        arguments.append('-srcband')
        arguments.append(
            str(self.parameterAsInt(parameters, self.BAND, context)))

        arguments.append('-distunits')
        arguments.append(self.distanceUnits[self.parameterAsEnum(
            parameters, self.UNITS, context)][1])

        values = self.parameterAsString(parameters, self.VALUES, context)
        if values:
            arguments.append('-values')
            arguments.append(values)

        if distance:
            arguments.append('-maxdist')
            arguments.append(str(distance))

        if nodata is not None:
            arguments.append('-nodata')
            arguments.append(str(nodata))

        if replaceValue:
            arguments.append('-fixed-buf-val')
            arguments.append(str(replaceValue))

        arguments.append('-ot')
        arguments.append(self.TYPES[self.parameterAsEnum(
            parameters, self.DATA_TYPE, context)])

        arguments.append('-of')
        arguments.append(
            QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))

        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        arguments.append(inLayer.source())
        arguments.append(out)

        if isWindows():
            commands = ["python3", "-m", self.commandName()]
        else:
            commands = [self.commandName() + '.py']

        commands.append(GdalUtils.escapeAndJoin(arguments))

        return commands
Exemplo n.º 51
0
    def getConsoleCommands(self, parameters, context, feedback):
        connection = self.getParameterValue(self.DATABASE)
        uri = uri_from_name(connection)
        if self.processing:
            # to get credentials input when needed
            uri = GeoDB(uri=uri).uri

        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = GdalUtils.ogrConnectionString(inLayer, context)[1:-1]
        shapeEncoding = self.getParameterValue(self.SHAPE_ENCODING)
        ssrs = self.getParameterValue(self.S_SRS)
        tsrs = self.getParameterValue(self.T_SRS)
        asrs = self.getParameterValue(self.A_SRS)
        schema = self.getParameterValue(self.SCHEMA)
        table = self.getParameterValue(self.TABLE)
        pk = self.getParameterValue(self.PK)
        primary_key = self.getParameterValue(self.PRIMARY_KEY)
        geocolumn = self.getParameterValue(self.GEOCOLUMN)
        dim = self.DIMLIST[self.getParameterValue(self.DIM)]
        simplify = self.getParameterValue(self.SIMPLIFY)
        segmentize = self.getParameterValue(self.SEGMENTIZE)
        spat = self.getParameterValue(self.SPAT)
        if not spat:
            spat = QgsProcessingUtils.combineLayerExtents([inLayer])
        clip = self.getParameterValue(self.CLIP)
        where = self.getParameterValue(self.WHERE)
        gt = self.getParameterValue(self.GT)
        overwrite = self.getParameterValue(self.OVERWRITE)
        append = self.getParameterValue(self.APPEND)
        addfields = self.getParameterValue(self.ADDFIELDS)
        launder = self.getParameterValue(self.LAUNDER)
        index = self.getParameterValue(self.INDEX)
        skipfailures = self.getParameterValue(self.SKIPFAILURES)
        promotetomulti = self.getParameterValue(self.PROMOTETOMULTI)
        precision = self.getParameterValue(self.PRECISION)
        options = self.getParameterValue(self.OPTIONS)

        arguments = []
        arguments.append('-progress')
        arguments.append('--config PG_USE_COPY YES')
        if shapeEncoding:
            arguments.append('--config')
            arguments.append('SHAPE_ENCODING')
            arguments.append('"' + shapeEncoding + '"')
        arguments.append('-f')
        arguments.append('PostgreSQL')
        arguments.append('PG:"')
        for token in uri.connectionInfo(self.processing).split(' '):
            arguments.append(token)
        arguments.append('active_schema={}'.format(schema or 'public'))
        arguments.append('"')
        arguments.append("-lco DIM=" + dim)
        arguments.append(ogrLayer)
        arguments.append(GdalUtils.ogrLayerName(inLayer))
        if index:
            arguments.append("-lco SPATIAL_INDEX=OFF")
        if launder:
            arguments.append("-lco LAUNDER=NO")
        if append:
            arguments.append('-append')
        if addfields:
            arguments.append('-addfields')
        if overwrite:
            arguments.append('-overwrite')
        if len(self.GEOMTYPE[self.getParameterValue(self.GTYPE)]) > 0:
            arguments.append('-nlt')
            arguments.append(self.GEOMTYPE[self.getParameterValue(self.GTYPE)])
        if geocolumn:
            arguments.append("-lco GEOMETRY_NAME=" + geocolumn)
        if pk:
            arguments.append("-lco FID=" + pk)
        elif primary_key is not None:
            arguments.append("-lco FID=" + primary_key)
        if not table:
            table = GdalUtils.ogrLayerName(inLayer).lower()
        if schema:
            table = '{}.{}'.format(schema, table)
        arguments.append('-nln')
        arguments.append(table)
        if ssrs:
            arguments.append('-s_srs')
            arguments.append(ssrs)
        if tsrs:
            arguments.append('-t_srs')
            arguments.append(tsrs)
        if asrs:
            arguments.append('-a_srs')
            arguments.append(asrs)
        if spat:
            regionCoords = spat.split(',')
            arguments.append('-spat')
            arguments.append(regionCoords[0])
            arguments.append(regionCoords[2])
            arguments.append(regionCoords[1])
            arguments.append(regionCoords[3])
            if clip:
                arguments.append('-clipsrc spat_extent')
        if skipfailures:
            arguments.append('-skipfailures')
        if where:
            arguments.append('-where "' + where + '"')
        if simplify:
            arguments.append('-simplify')
            arguments.append(simplify)
        if segmentize:
            arguments.append('-segmentize')
            arguments.append(segmentize)
        if gt:
            arguments.append('-gt')
            arguments.append(gt)
        if promotetomulti:
            arguments.append('-nlt PROMOTE_TO_MULTI')
        if precision is False:
            arguments.append('-lco PRECISION=NO')
        if options:
            arguments.append(options)

        commands = []
        if isWindows():
            commands = ['cmd.exe', '/C ', 'ogr2ogr.exe',
                        GdalUtils.escapeAndJoin(arguments)]
        else:
            commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]

        return commands
Exemplo n.º 52
0
    def getOgrCompatibleSource(self, parameter_name, parameters, context,
                               feedback, executing):
        """
        Interprets a parameter as an OGR compatible source and layer name
        :param executing:
        """
        if not executing and parameter_name in parameters and isinstance(
                parameters[parameter_name],
                QgsProcessingFeatureSourceDefinition):
            # if not executing, then we throw away all 'selected features only' settings
            # since these have no meaning for command line gdal use, and we don't want to force
            # an export of selected features only to a temporary file just to show the command!
            parameters = {parameter_name: parameters[parameter_name].source}

        input_layer = self.parameterAsVectorLayer(parameters, parameter_name,
                                                  context)
        ogr_data_path = None
        ogr_layer_name = None
        if input_layer is None or input_layer.dataProvider().name(
        ) == 'memory':
            if executing:
                # parameter is not a vector layer - try to convert to a source compatible with OGR
                # and extract selection if required
                ogr_data_path = self.parameterAsCompatibleSourceLayerPath(
                    parameters,
                    parameter_name,
                    context,
                    QgsVectorFileWriter.supportedFormatExtensions(),
                    feedback=feedback)
                ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
            else:
                #not executing - don't waste time converting incompatible sources, just return dummy strings
                #for the command preview (since the source isn't compatible with OGR, it has no meaning anyway and can't
                #be run directly in the command line)
                ogr_data_path = 'path_to_data_file'
                ogr_layer_name = 'layer_name'
        elif input_layer.dataProvider().name() == 'ogr':
            if executing and isinstance(
                    parameters[parameter_name],
                    QgsProcessingFeatureSourceDefinition
            ) and parameters[parameter_name].selectedFeaturesOnly:
                # parameter is a vector layer, with OGR data provider
                # so extract selection if required
                ogr_data_path = self.parameterAsCompatibleSourceLayerPath(
                    parameters,
                    parameter_name,
                    context,
                    QgsVectorFileWriter.supportedFormatExtensions(),
                    feedback=feedback)
                parts = QgsProviderRegistry.instance().decodeUri(
                    'ogr', ogr_data_path)
                ogr_data_path = parts['path']
                if 'layerName' in parts and parts['layerName']:
                    ogr_layer_name = parts['layerName']
                else:
                    ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
            else:
                #either not using the selection, or
                #not executing - don't worry about 'selected features only' handling. It has no meaning
                #for the command line preview since it has no meaning outside of a QGIS session!
                ogr_data_path = GdalUtils.ogrConnectionStringAndFormatFromLayer(
                    input_layer)[0]
                ogr_layer_name = GdalUtils.ogrLayerName(
                    input_layer.dataProvider().dataSourceUri())
        else:
            # vector layer, but not OGR - get OGR compatible path
            # TODO - handle "selected features only" mode!!
            ogr_data_path = GdalUtils.ogrConnectionStringFromLayer(input_layer)
            ogr_layer_name = GdalUtils.ogrLayerName(
                input_layer.dataProvider().dataSourceUri())
        return ogr_data_path, ogr_layer_name
Exemplo n.º 53
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        source = self.parameterAsSource(parameters, self.INPUT, context)
        if source is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT))
        fields = source.fields()
        ogrLayer, layerName = self.getOgrCompatibleSource(
            self.INPUT, parameters, context, feedback, executing)
        geometry = self.parameterAsString(parameters, self.GEOMETRY, context)
        distance = self.parameterAsDouble(parameters, self.DISTANCE, context)
        fieldName = self.parameterAsString(parameters, self.FIELD, context)
        dissolve = self.parameterAsBool(parameters, self.DISSOLVE, context)
        options = self.parameterAsString(parameters, self.OPTIONS, context)
        outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        output, outputFormat = GdalUtils.ogrConnectionStringAndFormat(
            outFile, context)

        other_fields = []
        for f in fields:
            if f.name() == geometry:
                continue
            other_fields.append(f.name())

        if other_fields:
            other_fields = ', {}'.format(','.join(other_fields))
        else:
            other_fields = ''

        arguments = []
        arguments.append(output)
        arguments.append(ogrLayer)
        arguments.append('-dialect')
        arguments.append('sqlite')
        arguments.append('-sql')

        if dissolve or fieldName:
            sql = "SELECT ST_Union(ST_Buffer({}, {})) AS {}{} FROM '{}'".format(
                geometry, distance, geometry, other_fields, layerName)
        else:
            sql = "SELECT ST_Buffer({}, {}) AS {}{} FROM '{}'".format(
                geometry, distance, geometry, other_fields, layerName)

        if fieldName:
            sql = '{} GROUP BY {}'.format(sql, fieldName)

        arguments.append(sql)

        if self.parameterAsBool(parameters, self.EXPLODE_COLLECTIONS, context):
            arguments.append('-explodecollections')

        if options:
            arguments.append(options)

        if outputFormat:
            arguments.append('-f {}'.format(outputFormat))

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 54
0
    def processAlgorithm(self, progress):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = self.ogrConnectionString(inLayer)[1:-1]
        ssrs = unicode(self.getParameterValue(self.S_SRS))
        tsrs = unicode(self.getParameterValue(self.T_SRS))
        asrs = unicode(self.getParameterValue(self.A_SRS))
        host = unicode(self.getParameterValue(self.HOST))
        port = unicode(self.getParameterValue(self.PORT))
        user = unicode(self.getParameterValue(self.USER))
        dbname = unicode(self.getParameterValue(self.DBNAME))
        password = unicode(self.getParameterValue(self.PASSWORD))
        schema = unicode(self.getParameterValue(self.SCHEMA))
        schemastring = "-lco SCHEMA=" + schema
        table = unicode(self.getParameterValue(self.TABLE))
        pk = unicode(self.getParameterValue(self.PK))
        pkstring = "-lco FID=" + pk
        primary_key = self.getParameterValue(self.PRIMARY_KEY)
        geocolumn = unicode(self.getParameterValue(self.GEOCOLUMN))
        geocolumnstring = "-lco GEOMETRY_NAME=" + geocolumn
        dim = self.DIMLIST[self.getParameterValue(self.DIM)]
        dimstring = "-lco DIM=" + dim
        simplify = unicode(self.getParameterValue(self.SIMPLIFY))
        segmentize = unicode(self.getParameterValue(self.SEGMENTIZE))
        spat = self.getParameterValue(self.SPAT)
        ogrspat = self.ogrConnectionString(spat)
        clip = self.getParameterValue(self.CLIP)
        where = unicode(self.getParameterValue(self.WHERE))
        wherestring = "-where '" + where + "'"
        gt = unicode(self.getParameterValue(self.GT))
        overwrite = self.getParameterValue(self.OVERWRITE)
        append = self.getParameterValue(self.APPEND)
        addfields = self.getParameterValue(self.ADDFIELDS)
        launder = self.getParameterValue(self.LAUNDER)
        launderstring = "-lco LAUNDER=NO"
        index = self.getParameterValue(self.INDEX)
        indexstring = "-lco SPATIAL_INDEX=OFF"
        skipfailures = self.getParameterValue(self.SKIPFAILURES)
        promotetomulti = self.getParameterValue(self.PROMOTETOMULTI)
        precision = self.getParameterValue(self.PRECISION)
        options = unicode(self.getParameterValue(self.OPTIONS))

        arguments = []
        arguments.append('-progress')
        arguments.append('--config PG_USE_COPY YES')
        arguments.append('-f')
        arguments.append('PostgreSQL')
        arguments.append('PG:"host=' + host)
        arguments.append('port=' + port)
        if len(dbname) > 0:
            arguments.append('dbname=' + dbname)
        if len(password) > 0:
            arguments.append('password='******'user='******'"')
        arguments.append(dimstring)
        arguments.append(ogrLayer)
        arguments.append(self.ogrLayerName(inLayer))
        if index:
            arguments.append(indexstring)
        if launder:
            arguments.append(launderstring)
        if append:
            arguments.append('-append')
        if addfields:
            arguments.append('-addfields')
        if overwrite:
            arguments.append('-overwrite')
        if len(self.GEOMTYPE[self.getParameterValue(self.GTYPE)]) > 0:
            arguments.append('-nlt')
            arguments.append(self.GEOMTYPE[self.getParameterValue(self.GTYPE)])
        if len(schema) > 0:
            arguments.append(schemastring)
        if len(geocolumn) > 0:
            arguments.append(geocolumnstring)
        if len(pk) > 0:
            arguments.append(pkstring)
        elif primary_key is not None:
            arguments.append("-lco FID=" + primary_key)
        if len(table) > 0:
            arguments.append('-nln')
            arguments.append(table)
        if len(ssrs) > 0:
            arguments.append('-s_srs')
            arguments.append(ssrs)
        if len(tsrs) > 0:
            arguments.append('-t_srs')
            arguments.append(tsrs)
        if len(asrs) > 0:
            arguments.append('-a_srs')
            arguments.append(asrs)
        if len(spat) > 0:
            regionCoords = ogrspat.split(',')
            arguments.append('-spat')
            arguments.append(regionCoords[0])
            arguments.append(regionCoords[2])
            arguments.append(regionCoords[1])
            arguments.append(regionCoords[3])
            if clip:
                arguments.append('-clipsrc spat_extent')
        if skipfailures:
            arguments.append('-skipfailures')
        if where:
            arguments.append(wherestring)
        if len(simplify) > 0:
            arguments.append('-simplify')
            arguments.append(simplify)
        if len(segmentize) > 0:
            arguments.append('-segmentize')
            arguments.append(segmentize)
        if len(gt) > 0:
            arguments.append('-gt')
            arguments.append(gt)
        if promotetomulti:
            arguments.append('-nlt PROMOTE_TO_MULTI')
        if precision is False:
            arguments.append('-lco PRECISION=NO')
        if len(options) > 0:
            arguments.append(options)

        commands = []
        if isWindows():
            commands = [
                'cmd.exe', '/C ', 'ogr2ogr.exe',
                GdalUtils.escapeAndJoin(arguments)
            ]
        else:
            commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]

        GdalUtils.runGdal(commands, progress)
Exemplo n.º 55
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        if inLayer is None:
            raise QgsProcessingException(
                self.invalidRasterError(parameters, self.INPUT))

        maskLayer, maskLayerName = self.getOgrCompatibleSource(
            self.MASK, parameters, context, feedback, executing)

        if self.NODATA in parameters and parameters[self.NODATA] is not None:
            nodata = self.parameterAsDouble(parameters, self.NODATA, context)
        else:
            nodata = None
        options = self.parameterAsString(parameters, self.OPTIONS, context)
        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        arguments = []

        data_type = self.parameterAsEnum(parameters, self.DATA_TYPE, context)
        if data_type:
            arguments.append('-ot ' + self.TYPES[data_type])

        arguments.append('-of')
        arguments.append(
            QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))

        if self.parameterAsBool(parameters, self.KEEP_RESOLUTION, context):
            arguments.append('-tr')
            arguments.append(str(inLayer.rasterUnitsPerPixelX()))
            arguments.append(str(-inLayer.rasterUnitsPerPixelY()))
            arguments.append('-tap')

        arguments.append('-cutline')
        arguments.append(maskLayer)

        if self.parameterAsBool(parameters, self.CROP_TO_CUTLINE, context):
            arguments.append('-crop_to_cutline')

        if self.parameterAsBool(parameters, self.ALPHA_BAND, context):
            arguments.append('-dstalpha')

        if nodata is not None:
            arguments.append('-dstnodata {}'.format(nodata))

        extent = self.parameterAsExtent(parameters, self.TARGET_EXTENT,
                                        context)
        if not extent.isNull():
            arguments.append('-te')
            arguments.append(extent.xMinimum())
            arguments.append(extent.yMinimum())
            arguments.append(extent.xMaximum())
            arguments.append(extent.yMaximum())

            extentCrs = self.parameterAsCrs(parameters, self.TARGET_EXTENT_CRS,
                                            context)
            if extentCrs:
                arguments.append('-te_srs')
                arguments.append(extentCrs.authid())

        if self.parameterAsBool(parameters, self.MULTITHREADING, context):
            arguments.append('-multi')

        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        arguments.append(inLayer.source())
        arguments.append(out)

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
Exemplo n.º 56
0
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        geometry = self.getParameterValue(self.GEOMETRY)
        field = self.getParameterValue(self.FIELD)
        multi = self.getParameterValue(self.MULTI)
        fields = self.getParameterValue(self.FIELDS)
        count = self.getParameterValue(self.COUNT)
        area = self.getParameterValue(self.AREA)
        stats = self.getParameterValue(self.STATS)
        statsatt = self.getParameterValue(self.STATSATT)
        options = self.getParameterValue(self.OPTIONS)

        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        layername = ogrLayerName(inLayer)

        output = self.getOutputFromName(self.OUTPUT_LAYER)
        outFile = output.value

        output = ogrConnectionString(outFile)

        arguments = []
        arguments.append(output)
        arguments.append(ogrLayer)
        arguments.append('-dialect')
        arguments.append('sqlite')
        arguments.append('-sql')

        sql = "SELECT ST_Union({})".format(geometry)

        sqlOpts = ''
        if fields:
            sqlOpts += ',*'
        else:
            sqlOpts += ',{}'.format(field)

        if count:
            sqlOpts += ", COUNT({}) AS count".format(geometry)

        if stats:
            sqlOpts += ", SUM({0}) AS sum_diss, MIN({0}) AS min_diss, MAX({0}) AS max_diss, AVG({0}) AS avg_diss".format(
                statsatt)

        if area:
            sqlOpts += ", SUM(ST_Area({0})) AS area_diss, ST_Perimeter(ST_Union({0})) AS peri_diss".format(
                geometry)

        sql = '{}{} FROM {} GROUP BY {}'.format(sql, sqlOpts, layername, field)

        arguments.append(sql)

        if not multi:
            arguments.append('-explodecollections')

        if options is not None and len(options.strip()) > 0:
            arguments.append(options)

        commands = []
        if isWindows():
            commands = [
                'cmd.exe', '/C ', 'ogr2ogr.exe',
                GdalUtils.escapeAndJoin(arguments)
            ]
        else:
            commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]

        return commands
Exemplo n.º 57
0
Arquivo: warp.py Projeto: kermeat/QGIS
    def defineCharacteristics(self):
        self.name, self.i18n_name = self.trAlgorithm('Warp (reproject)')
        self.group, self.i18n_group = self.trAlgorithm('[GDAL] Projections')
        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'), ''))
        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(
            ParameterExtent(self.RAST_EXT, self.tr('Raster extent')))

        if GdalUtils.version() >= 2000000:
            self.addParameter(
                ParameterCrs(self.EXT_CRS, self.tr('CRS of the raster 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('Reprojected')))
    def processAlgorithm(self, progress):
        inLayerA = self.getParameterValue(self.INPUT_LAYER_A)
        ogrLayerA = ogrConnectionString(inLayerA)[1:-1]
        layernameA = ogrLayerName(inLayerA)
        fieldsA = unicode(self.getParameterValue(self.FIELDS_A))
        fieldA = unicode(self.getParameterValue(self.FIELD_A))
        inLayerB = self.getParameterValue(self.INPUT_LAYER_B)
        ogrLayerB = ogrConnectionString(inLayerB)[1:-1]
        layernameB = ogrLayerName(inLayerB)
        fieldB = unicode(self.getParameterValue(self.FIELD_B))
        dsUriA = QgsDataSourceURI(self.getParameterValue(self.INPUT_LAYER_A))
        geomColumnA = dsUriA.geometryColumn()
        dsUriB = QgsDataSourceURI(self.getParameterValue(self.INPUT_LAYER_B))
        geomColumnB = dsUriB.geometryColumn()
        layerB = dataobjects.getObjectFromUri(
            self.getParameterValue(self.INPUT_LAYER_B))
        layerA = dataobjects.getObjectFromUri(
            self.getParameterValue(self.INPUT_LAYER_A))
        geomTypeB = layerB.geometryType()
        wkbTypeB = layerB.wkbType()
        sridB = layerB.crs().postgisSrid()
        sridA = layerA.crs().postgisSrid()
        schema = unicode(self.getParameterValue(self.SCHEMA))
        table = unicode(self.getParameterValue(self.TABLE))
        single = self.getParameterValue(self.SINGLE)

        if len(fieldsA) > 0:
            fieldstringA = fieldsA.replace(",", ", g1.")
            fieldstringA = ", g1." + fieldstringA
        else:
            fieldstringA = ""

        type = "POINT"

        if single:
            multistring = "-nlt " + type
            caststring = type
            st_function = "ST_Dump"
            castgeom = ".geom"
        else:
            multistring = "-nlt MULTI" + type
            caststring = "MULTI" + type
            st_function = "ST_Multi"
            castgeom = ""

        sqlstring = "-sql \"SELECT (" + st_function + "(g1." + geomColumnA + "))" + castgeom + "::geometry(" + caststring + "," + str(
            sridA
        ) + ") AS geom, g2." + fieldB + " AS " + fieldA + fieldstringA + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2  WHERE ST_Intersects(g2." + geomColumnB + ",g1." + geomColumnA + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"

        options = unicode(self.getParameterValue(self.OPTIONS))

        arguments = []
        arguments.append('-f')
        arguments.append('PostgreSQL')
        arguments.append(ogrLayerA)
        arguments.append(ogrLayerA)
        arguments.append(sqlstring)
        arguments.append('-overwrite')

        if len(options) > 0:
            arguments.append(options)
        print geomTypeB
        commands = []
        if isWindows():
            commands = [
                'cmd.exe', '/C ', 'ogr2ogr.exe',
                GdalUtils.escapeAndJoin(arguments)
            ]
        else:
            commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]

        GdalUtils.runGdal(commands, progress)

        output = self.getOutputValue(self.OUTPUT)
        f = open(output, 'w')
        f.write('<pre>')
        for s in GdalUtils.getConsoleOutput()[1:]:
            f.write(unicode(s))
        f.write('</pre>')
        f.close()
Exemplo n.º 59
0
    def getConsoleCommands(self,
                           parameters,
                           context,
                           feedback,
                           executing=True):
        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        arguments = []
        if self.parameterAsBool(parameters, self.PCT, context):
            arguments.append('-pct')

        if self.parameterAsBool(parameters, self.SEPARATE, context):
            arguments.append('-separate')

        if self.NODATA_INPUT in parameters and parameters[
                self.NODATA_INPUT] is not None:
            nodata_input = self.parameterAsInt(parameters, self.NODATA_INPUT,
                                               context)
            arguments.append('-n')
            arguments.append(str(nodata_input))

        if self.NODATA_OUTPUT in parameters and parameters[
                self.NODATA_OUTPUT] is not None:
            nodata_output = self.parameterAsInt(parameters, self.NODATA_OUTPUT,
                                                context)
            arguments.append('-a_nodata')
            arguments.append(str(nodata_output))

        arguments.append('-ot')
        arguments.append(self.TYPES[self.parameterAsEnum(
            parameters, self.DATA_TYPE, context)])

        arguments.append('-of')
        arguments.append(
            QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))

        options = self.parameterAsString(parameters, self.OPTIONS, context)
        if options:
            arguments.extend(GdalUtils.parseCreationOptions(options))

        arguments.append('-o')
        arguments.append(out)

        # Always write input files to a text file in case there are many of them and the
        # length of the command will be longer then allowed in command prompt
        list_file = GdalUtils.writeLayerParameterToTextFile(
            filename='mergeInputFiles.txt',
            alg=self,
            parameters=parameters,
            parameter_name=self.INPUT,
            context=context,
            quote=True,
            executing=executing)
        arguments.append('--optfile')
        arguments.append(list_file)

        commands = []
        if isWindows():
            commands = [
                'cmd.exe', '/C ',
                self.commandName() + '.bat',
                GdalUtils.escapeAndJoin(arguments)
            ]
        else:
            commands = [
                self.commandName() + '.py',
                GdalUtils.escapeAndJoin(arguments)
            ]

        return commands
Exemplo n.º 60
0
Arquivo: warp.py Projeto: exlimit/QGIS
    def getConsoleCommands(self, parameters, context, feedback):
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        srccrs = self.parameterAsCrs(parameters, self.SOURCE_SRS, context).authid()
        dstcrs = self.parameterAsCrs(parameters, self.DEST_SRS, context).authid()
        useRasterExtent = self.parameterAsBool(parameters, self.USE_RASTER_EXTENT, context)
        rasterExtent = self.parameterAsExtent(parameters, self.RASTER_EXTENT, context)
        if rasterExtent.isNull():
            rasterExtent = QgsProcessingUtils.combineLayerExtents([inLayer])
        extentCrs = self.parameterAsCrs(parameters, self.EXTENT_CRS, context).authid()
        opts = self.parameterAsEnum(parameters, self.OPTIONS, context)
        noData = self.parameterAsString(parameters, self.NO_DATA, context)
        multithreading = self.parameterAsBool(parameters, self.MULTITHREADING, context)

        if noData is not None:
            noData = str(noData)

        arguments = []
        arguments.append('-ot')
        arguments.append(self.TYPE[self.parameterAsEnum(parameters, self.RTYPE, context)])
        if srccrs:
            arguments.append('-s_srs')
            arguments.append(srccrs)
        if dstcrs:
            arguments.append('-t_srs')
            arguments.append(dstcrs)
        if noData:
            arguments.append('-dstnodata')
            arguments.append(noData)

        arguments.append('-r')
        arguments.append(
            self.METHOD_OPTIONS[self.parameterAsEnum(parameters, self.METHOD, context)])

        arguments.append('-of')
        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        arguments.append(GdalUtils.getFormatShortNameFromFilename(out))

        if self.parameterAsDouble(parameters, self.TR, context) != 0:
            arguments.append('-tr')
            arguments.append(str(self.parameterAsDouble(parameters, self.TR, context)))
            arguments.append(str(self.parameterAsDouble(parameters, self.TR, context)))

        if useRasterExtent:
            arguments.append('-te')
            arguments.append(rasterExtent.xMinimum())
            arguments.append(rasterExtent.yMinimum())
            arguments.append(rasterExtent.xMaximum())
            arguments.append(rasterExtent.yMaximum())

            if extentCrs:
                arguments.append('-te_srs')
                arguments.append(extentCrs)

        if opts:
            arguments.append('-co')
            arguments.append(opts)

        if multithreading:
            arguments.append('-multi')

        if GdalUtils.version() in [2010000, 2010100]:
            arguments.append("--config GDALWARP_IGNORE_BAD_CUTLINE YES")

        arguments.append(inLayer.source())
        arguments.append(out)

        return ['gdalwarp', GdalUtils.escapeAndJoin(arguments)]