コード例 #1
0
ファイル: ogr2ogrclip.py プロジェクト: peterisb/QGIS
    def getConsoleCommands(self, parameters):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        clipLayer = self.getParameterValue(self.CLIP_LAYER)
        ogrClipLayer = ogrConnectionString(clipLayer)[1:-1]

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

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

        arguments = []
        arguments.append('-clipsrc')
        arguments.append(ogrClipLayer)
        arguments.append("-clipsrclayer")
        arguments.append(ogrLayerName(clipLayer))

        if options is not None and len(options.strip()) > 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
    def processAlgorithm(self, progress):
        inLayer = self.getParameterValue(self.INPUT)
        conn = 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:
                # Gauss-Krüger zone 3
                if self.getParameterValue(self.GRID) == 0:
                    # BETA2007
                    arguments.append('+proj=tmerc +lat_0=0 +lon_0=9 +k=1 +x_0=3500000 +y_0=0 +ellps=bessel +nadgrids=' + os.path.dirname(__file__) + '/grids/BETA2007.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(ogrLayerName(inLayer))
            
        else:
            # Inverse transformation
            arguments = ['-s_srs']
            arguments.append('EPSG:4258')
            arguments.append('-t_srs')
            if self.getParameterValue(self.CRS) == 0:
                # Gauss-Krüger zone 3
                if self.getParameterValue(self.GRID) == 0:
                    # BETA2007
                    arguments.append('+proj=tmerc +lat_0=0 +lon_0=9 +k=1 +x_0=3500000 +y_0=0 +ellps=bessel +nadgrids=' + os.path.dirname(__file__) + '/grids/BETA2007.gsb +wktext +units=m +no_defs')
                arguments.append('-f')
                arguments.append('\"Geojson\"')
                arguments.append('/vsistdout/')
                arguments.append(conn)
                arguments.append(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:31467') 
                arguments.append(outFile)    
                arguments.append('/vsistdin/')
        
        arguments.append('-lco') 
        arguments.append('ENCODING=UTF-8')

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

        commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]
        GdalUtils.runGdal(commands, progress)
コード例 #3
0
    def processAlgorithm(self, progress):

        doTransf = self.transfList()

        inLayer = self.getParameterValue(self.INPUT)
        conn = ogrConnectionString(inLayer)[1:-1]

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

        if self.getParameterValue(self.TRANSF) == 0:
            # Direct transformation
            arguments = ['-s_srs']
            arguments.append(str(doTransf[self.getParameterValue(self.CRS)][self.getParameterValue(self.GRID)])[2:-2])
            arguments.append('-t_srs')
            arguments.append('EPSG:3763')
            arguments.append('-f')
            arguments.append('ESRI Shapefile')
            arguments.append('-lco') 
            arguments.append('ENCODING=UTF-8')
            arguments.append(outFile)
            arguments.append(conn)
            arguments.append(ogrLayerName(inLayer))
        else:
            # Inverse transformation
            arguments = ['-s_srs']
            arguments.append('EPSG:3763')
            arguments.append('-t_srs')
            arguments.append(str(doTransf[self.getParameterValue(self.CRS)][self.getParameterValue(self.GRID)])[2:-2])
            arguments.append('-f')
            arguments.append('\"Geojson\"')
            arguments.append('/vsistdout/')
            arguments.append(conn)
            arguments.append(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(str(doTransf[self.getParameterValue(self.CRS)][2])[2:-2])
            arguments.append(outFile)
            arguments.append('/vsistdin/')

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

        if os.path.isfile(os.path.dirname(__file__) + '/grids/pt73_e89.gsb') is False:
           import urllib
           urllib.urlretrieve ("https://github.com/NaturalGIS/ntv2_transformations_grids_and_sample_data/raw/master/pt/pt73_e89.gsb", os.path.dirname(__file__) + "/grids/pt73_e89.gsb")
           urllib.urlretrieve ("https://github.com/NaturalGIS/ntv2_transformations_grids_and_sample_data/raw/master/pt/ptED_e89.gsb", os.path.dirname(__file__) + "/grids/ptED_e89.gsb")
           urllib.urlretrieve ("https://github.com/NaturalGIS/ntv2_transformations_grids_and_sample_data/raw/master/pt/ptLB_e89.gsb", os.path.dirname(__file__) + "/grids/ptLB_e89.gsb")
           urllib.urlretrieve ("https://github.com/NaturalGIS/ntv2_transformations_grids_and_sample_data/raw/master/pt/ptLX_e89.gsb", os.path.dirname(__file__) + "/grids/ptLX_e89.gsb")
           urllib.urlretrieve ("https://github.com/NaturalGIS/ntv2_transformations_grids_and_sample_data/raw/master/pt/D73_ETRS89_geo.gsb", os.path.dirname(__file__) + "/grids/D73_ETRS89_geo.gsb")
           urllib.urlretrieve ("https://github.com/NaturalGIS/ntv2_transformations_grids_and_sample_data/raw/master/pt/DLX_ETRS89_geo.gsb", os.path.dirname(__file__) + "/grids/DLX_ETRS89_geo.gsb")

        commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)]
        GdalUtils.runGdal(commands, progress)
コード例 #4
0
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        layername = "'" + ogrLayerName(inLayer) + "'"
        geometry = unicode(self.getParameterValue(self.GEOMETRY))
        field = unicode(self.getParameterValue(self.FIELD))
        statsatt = unicode(self.getParameterValue(self.STATSATT))
        stats = self.getParameterValue(self.STATS)
        area = self.getParameterValue(self.AREA)
        multi = self.getParameterValue(self.MULTI)
        count = self.getParameterValue(self.COUNT)
        fields = self.getParameterValue(self.FIELDS)
        querystart = '-dialect sqlite -sql "SELECT ST_Union(' + geometry + ')'
        queryend = ' FROM ' + layername + ' GROUP BY ' + field + '"'
        if fields:
            queryfields = ",*"
        else:
            queryfields = "," + field
        if count:
            querycount = ", COUNT(" + geometry + ") AS count"
        else:
            querycount = ""
        if stats:
            querystats = ", SUM(" + statsatt + ") AS sum_diss, MIN(" + statsatt + ") AS min_diss, MAX(" + statsatt + ") AS max_diss, AVG(" + statsatt + ") AS avg_diss"
        else:
            querystats = ""
        if area:
            queryarea = ", SUM(ST_area(" + geometry + ")) AS area_diss, ST_perimeter(ST_union(" + geometry + ")) AS peri_diss"
        else:
            queryarea = ""

        query = querystart + queryfields + querycount + querystats + queryarea + queryend
        output = self.getOutputFromName(self.OUTPUT_LAYER)
        outFile = output.value

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

        arguments = []
        arguments.append(output)
        arguments.append(ogrLayer)
        arguments.append(ogrLayerName(inLayer))
        arguments.append(query)

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

        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
コード例 #5
0
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        operation = self.getParameterValue(self.OPERATION)
        geometry = self.getParameterValue(self.GEOMETRY)
        distance = self.getParameterValue(self.RADIUS)
        leftright = self.getParameterValue(self.LEFTRIGHT)
        dissolveall = self.getParameterValue(self.DISSOLVEALL)
        field = self.getParameterValue(self.FIELD)
        multi = self.getParameterValue(self.MULTI)
        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)

        layername = ogrLayerName(inLayer)

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

        if dissolveall or field is not None:
            if operation == 0:
                sql = "SELECT ST_Union(ST_SingleSidedBuffer({}, {}, {})), * FROM '{}'".format(geometry, distance, leftright, layername)
            else:
                sql = "SELECT ST_Union(ST_OffsetCurve({}, {})) * FROM '{}'".format(geometry, distance, layername)
        else:
            if operation == 0:
                sql = "SELECT ST_SingleSidedBuffer({},{},{}), * FROM '{}'".format(geometry, distance, leftright, layername)
            else:
                sql = "SELECT ST_OffsetCurve({}, {}), * FROM '{}'".format(geometry, distance, layername)

        if field is not None:
            sql = '"{} GROUP BY {}"'.format(sql, field)

        arguments.append(sql)

        if field is not None and multi:
            arguments.append('-explodecollections')

        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
コード例 #6
0
    def processAlgorithm(self, progress):
        inLayerA = self.getParameterValue(self.INPUT_LAYER_A)
        ogrLayerA = ogrConnectionString(inLayerA)[1:-1]
        layernameA = ogrLayerName(inLayerA)
        inLayerB = self.getParameterValue(self.INPUT_LAYER_B)
        ogrLayerB = ogrConnectionString(inLayerB)[1:-1]
        layernameB = ogrLayerName(inLayerB)
        fieldA = unicode(self.getParameterValue(self.FIELD_A))
        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()
        layerA = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER_A))
        geomTypeA = layerA.geometryType()
        wkbTypeA = layerA.wkbType()
        sridA = layerA.crs().postgisSrid()
        layerB = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER_B))
        geomTypeB = layerB.geometryType()
        wkbTypeB = layerB.wkbType()
        sridB = layerB.crs().postgisSrid()
        multi = self.getParameterValue(self.MULTI)
        schema = unicode(self.getParameterValue(self.SCHEMA))
        table = unicode(self.getParameterValue(self.TABLE))
        if multi:
           sqlstring = "-sql \"WITH temp_table AS (SELECT ST_Union(" + geomColumnB + ") AS geom FROM " + layernameB + ") SELECT ST_ShortestLine(g1." + geomColumnA + ",g2.geom) AS geom, ST_Distance(g1." + geomColumnA + ",g2.geom) AS distance, g1." + fieldA + " AS id_from FROM " + layernameA + " AS g1, temp_table AS g2\" -nln " + schema + "." + table + " -lco FID=gid -lco GEOMETRY_NAME=geom -nlt LINESTRING --config PG_USE_COPY YES -a_srs EPSG:" + str(sridA) + ""
        else:
           sqlstring = "-sql \"SELECT ST_ShortestLine(g1." + geomColumnA + ",g2." + geomColumnB + ") AS geom, ST_Distance(g1." + geomColumnA + ",g2." + geomColumnB + ") AS distance, g1." + fieldA + " AS id_from, g2." + fieldB + " AS id_to FROM " + layernameA + " AS g1, " + layernameB + " AS g2\" -nln " + schema + "." + table + " -lco FID=gid -lco GEOMETRY_NAME=geom -nlt LINESTRING --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 table   
        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()        
コード例 #7
0
    def processAlgorithm(self, progress):
        inLayerA = self.getParameterValue(self.INPUT_LAYER_A)
        ogrLayerA = ogrConnectionString(inLayerA)[1:-1]
        layernameA = ogrLayerName(inLayerA)
        inLayerB = self.getParameterValue(self.INPUT_LAYER_B)
        ogrLayerB = ogrConnectionString(inLayerB)[1:-1]
        layernameB = ogrLayerName(inLayerB)
        fieldsA = unicode(self.getParameterValue(self.FIELDS_A))
        dsUriA = QgsDataSourceURI(self.getParameterValue(self.INPUT_LAYER_A))
        geomColumnA = dsUriA.geometryColumn()
        dsUriB = QgsDataSourceURI(self.getParameterValue(self.INPUT_LAYER_B))
        geomColumnB = dsUriB.geometryColumn()
        schema = unicode(self.getParameterValue(self.SCHEMA))
        table = unicode(self.getParameterValue(self.TABLE))
        single = self.getParameterValue(self.SINGLE)
        if len(fieldsA) > 0:
           fieldstring = fieldsA.replace(",", ", g1.")
           fieldstring = ", g1." + fieldstring               
        else:
           fieldstring = ""        

        if single:
           sqlstring = "-sql \"SELECT (ST_Dump(ST_Difference(g1." + geomColumnA + ",ST_Union(g2." + geomColumnB + ")))).geom::geometry(Polygon) AS geom" + fieldstring + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 GROUP BY g1." + geomColumnA + fieldstring + "\""" -nln " + schema + "." + table + " -lco FID=gid -nlt POLYGON -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
        else:
           sqlstring = "-sql \"SELECT (ST_Multi(ST_CollectionExtract(ST_Difference(g1." + geomColumnA + ",ST_Union(g2." + geomColumnB + ")),3)))::geometry(MultiPolygon) AS geom" + fieldstring + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 GROUP BY g1." + geomColumnA + fieldstring + "\""" -nln " + schema + "." + table + " -lco FID=gid -nlt MULTIPOLYGON -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)
        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()          
コード例 #8
0
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        layername = "'" + ogrLayerName(inLayer) + "'"
        geometry = unicode(self.getParameterValue(self.GEOMETRY))
        distance = unicode(self.getParameterValue(self.DISTANCE))
        dissolveall = self.getParameterValue(self.DISSOLVEALL)
        field = unicode(self.getParameterValue(self.FIELD))
        multi = self.getParameterValue(self.MULTI)

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

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

        arguments = []
        arguments.append(output)
        arguments.append(ogrLayer)
        arguments.append(ogrLayerName(inLayer))
        if dissolveall or field != 'None':
            arguments.append('-dialect sqlite -sql "SELECT ST_Union(ST_Buffer(')
        else:
            arguments.append('-dialect sqlite -sql "SELECT ST_Buffer(')
        arguments.append(geometry)
        arguments.append(',')
        arguments.append(distance)
        if dissolveall or field != 'None':
            arguments.append(')),*')
        else:
            arguments.append('),*')
        arguments.append('FROM')
        arguments.append(layername)
        if field != 'None':
            arguments.append('GROUP')
            arguments.append('BY')
            arguments.append(field)
        arguments.append('"')
        if field != 'None' and multi:
            arguments.append('-explodecollections')

        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
コード例 #9
0
ファイル: onesidebuffer.py プロジェクト: qgis/QGIS
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        geometry = self.getParameterValue(self.GEOMETRY)
        distance = self.getParameterValue(self.RADIUS)
        leftright = self.getParameterValue(self.LEFTRIGHT)
        dissolveall = self.getParameterValue(self.DISSOLVEALL)
        field = self.getParameterValue(self.FIELD)
        multi = self.getParameterValue(self.MULTI)
        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)

        layername = ogrLayerName(inLayer)

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

        if dissolveall or field is not None:
            sql = "SELECT ST_Union(ST_SingleSidedBuffer({}, {}, {})), * FROM '{}'".format(
                geometry, distance, leftright, layername
            )
        else:
            sql = "SELECT ST_SingleSidedBuffer({},{},{}), * FROM '{}'".format(geometry, distance, leftright, layername)

        if field is not None:
            sql = '"{} GROUP BY {}"'.format(sql, field)

        arguments.append(sql)

        if field is not None and 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
コード例 #10
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
コード例 #11
0
ファイル: rasterize.py プロジェクト: Naisha634/QGIS
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        noData = unicode(self.getParameterValue(self.NO_DATA))
        jpegcompression = unicode(self.getParameterValue(self.JPEGCOMPRESSION))
        predictor = unicode(self.getParameterValue(self.PREDICTOR))
        zlevel = unicode(self.getParameterValue(self.ZLEVEL))
        tiled = unicode(self.getParameterValue(self.TILED))
        compress = self.COMPRESSTYPE[self.getParameterValue(self.COMPRESS)]
        bigtiff = self.BIGTIFFTYPE[self.getParameterValue(self.BIGTIFF)]
        tfw = unicode(self.getParameterValue(self.TFW))
        out = self.getOutputValue(self.OUTPUT)
        extra = unicode(self.getParameterValue(self.EXTRA))

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

        arguments.append('-ot')
        arguments.append(self.TYPE[self.getParameterValue(self.RTYPE)])
        dimType = self.getParameterValue(self.DIMENSIONS)
        if dimType == 0:
            # size in pixels
            arguments.append('-ts')
            arguments.append(unicode(self.getParameterValue(self.WIDTH)))
            arguments.append(unicode(self.getParameterValue(self.HEIGHT)))
        else:
            # resolution in map units per pixel
            arguments.append('-tr')
            arguments.append(unicode(self.getParameterValue(self.WIDTH)))
            arguments.append(unicode(self.getParameterValue(self.HEIGHT)))

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

        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)
        if len(extra) > 0:
            arguments.append(extra)
        arguments.append('-l')

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

        arguments.append(unicode(self.getOutputValue(self.OUTPUT)))
        return ['gdal_rasterize', GdalUtils.escapeAndJoin(arguments)]
コード例 #12
0
    def test_ogrLayerName(self):
        tmpdir = os.path.join(tmpBaseFolder, 'ogrLayerName')
        os.mkdir(tmpdir)

        def linkTestfile(f, t):
            os.link(os.path.join(dataFolder, f), os.path.join(tmpdir, t))

        linkTestfile('geom_data.csv', 'a.csv')
        name = vector.ogrLayerName(tmpdir)
        self.assertEqual(name, 'a')

        linkTestfile('wkt_data.csv', 'b.csv')
        name = vector.ogrLayerName(tmpdir + '|layerid=0')
        self.assertEqual(name, 'a')
        name = vector.ogrLayerName(tmpdir + '|layerid=1')
        self.assertEqual(name, 'b')

        name = vector.ogrLayerName(tmpdir + '|layerid=2')
        self.assertEqual(name, 'invalid-layerid')

        name = vector.ogrLayerName(tmpdir + '|layername=f')
        self.assertEqual(name, 'f') # layername takes precedence

        name = vector.ogrLayerName(tmpdir + '|layerid=0|layername=f2')
        self.assertEqual(name, 'f2') # layername takes precedence

        name = vector.ogrLayerName(tmpdir + '|layername=f2|layerid=0')
        self.assertEqual(name, 'f2') # layername takes precedence
コード例 #13
0
    def processAlgorithm(self, progress):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        layername = ogrLayerName(inLayer)
        fields = unicode(self.getParameterValue(self.FIELDS))
        dsUri = QgsDataSourceURI(self.getParameterValue(self.INPUT_LAYER))
        geomColumn = dsUri.geometryColumn()
        layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))
        geomType = layer.geometryType()
        wkbType = layer.wkbType()
        srid = layer.crs().postgisSrid()
        schema = unicode(self.getParameterValue(self.SCHEMA))
        table = unicode(self.getParameterValue(self.TABLE))
        if len(fields) > 0:
           fieldstring = "," + fields
        else:
           fieldstring = ""

        if wkbType == 3:
           layertype = "POLYGON"              
           sqlstring = "-sql \"SELECT (ST_Dump(ST_MakeValid(g1." + geomColumn + "))).geom::geometry(" + layertype + "," + str(srid) + ") AS geom" + fieldstring + " FROM " + layername + " AS g1\" -nlt " + layertype + " -nln " + schema + "." + table + " -lco FID=gid -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
        else:
            layertype = "MULTIPOLYGON"            
            sqlstring = "-sql \"SELECT (ST_MakeValid(g1." + geomColumn + "))::geometry(" + layertype + "," + str(srid) + ") AS geom" + fieldstring + " FROM " + layername + " AS g1\" -nlt " + layertype + " -nln " + schema + "." + table + " -lco FID=gid -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"

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

        arguments = []
        arguments.append('-f')
        arguments.append('PostgreSQL')
        arguments.append(ogrLayer)
        arguments.append(ogrLayer)
        arguments.append(sqlstring)
        arguments.append('-overwrite')
                
        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)

        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()          
コード例 #14
0
ファイル: ToolsTest.py プロジェクト: kalxas/QGIS
    def testOgrLayerNameExtraction(self):
        outdir = tempfile.mkdtemp()
        self.cleanup_paths.append(outdir)

        def _copyFile(dst):
            shutil.copyfile(
                os.path.join(testDataPath, 'custom', 'grass7', 'weighted.csv'),
                dst)

        # OGR provider - single layer
        _copyFile(os.path.join(outdir, 'a.csv'))
        name = vector.ogrLayerName(outdir)
        self.assertEqual(name, 'a')

        # OGR provider - multiple layers
        _copyFile(os.path.join(outdir, 'b.csv'))
        name = vector.ogrLayerName(outdir + '|layerid=0')
        self.assertEqual(name, 'a')
        name = vector.ogrLayerName(outdir + '|layerid=1')
        self.assertEqual(name, 'b')

        name = vector.ogrLayerName(outdir + '|layerid=2')
        self.assertIsNone(name)

        # OGR provider - layername takes precedence
        name = vector.ogrLayerName(outdir + '|layername=f')
        self.assertEqual(name, 'f')

        name = vector.ogrLayerName(outdir + '|layerid=0|layername=f')
        self.assertEqual(name, 'f')

        name = vector.ogrLayerName(outdir + '|layername=f|layerid=0')
        self.assertEqual(name, 'f')

        # SQLiite provider
        name = vector.ogrLayerName(
            'dbname=\'/tmp/x.sqlite\' table="t" (geometry) sql=')
        self.assertEqual(name, 't')

        # PostgreSQL provider
        name = vector.ogrLayerName(
            'port=5493 sslmode=disable key=\'edge_id\' srid=0 type=LineString table="city_data"."edge" (geom) sql='
        )
        self.assertEqual(name, 'city_data.edge')
コード例 #15
0
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        layername = "'" + ogrLayerName(inLayer) + "'"
        distance = str(self.getParameterValue(self.DISTANCE))
        geometry = str(self.getParameterValue(self.GEOMETRY))

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

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

        arguments = []
        arguments.append(output)
        arguments.append(ogrLayer)
        arguments.append(ogrLayerName(inLayer))

        arguments.append('-dialect sqlite -sql "SELECT ST_Line_Interpolate_Point(')
        arguments.append(geometry)
        arguments.append(',')
        arguments.append(distance)
        arguments.append('),*')
        arguments.append('FROM')
        arguments.append(layername)
        arguments.append('"')

        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
コード例 #16
0
ファイル: ToolsTest.py プロジェクト: wonder-sk/QGIS
    def test_ogrLayerName(self):
        tmpdir = os.path.join(tmpBaseFolder, 'ogrLayerName')
        os.mkdir(tmpdir)

        def linkTestfile(f, t):
            os.link(os.path.join(dataFolder, f), os.path.join(tmpdir, t))

        # URI from OGR provider
        linkTestfile('geom_data.csv', 'a.csv')
        name = vector.ogrLayerName(tmpdir)
        self.assertEqual(name, 'a')

        # URI from OGR provider
        linkTestfile('wkt_data.csv', 'b.csv')
        name = vector.ogrLayerName(tmpdir + '|layerid=0')
        self.assertEqual(name, 'a')
        name = vector.ogrLayerName(tmpdir + '|layerid=1')
        self.assertEqual(name, 'b')

        # URI from OGR provider
        name = vector.ogrLayerName(tmpdir + '|layerid=2')
        self.assertEqual(name, 'invalid-layerid')

        # URI from OGR provider
        name = vector.ogrLayerName(tmpdir + '|layername=f')
        self.assertEqual(name, 'f') # layername takes precedence

        # URI from OGR provider
        name = vector.ogrLayerName(tmpdir + '|layerid=0|layername=f2')
        self.assertEqual(name, 'f2') # layername takes precedence

        # URI from OGR provider
        name = vector.ogrLayerName(tmpdir + '|layername=f2|layerid=0')
        self.assertEqual(name, 'f2') # layername takes precedence

        # URI from Sqlite provider
        name = vector.ogrLayerName('dbname=\'/tmp/x.sqlite\' table="t" (geometry) sql=')
        self.assertEqual(name, 't')

        # URI from PostgreSQL provider
        name = vector.ogrLayerName('port=5493 sslmode=disable key=\'edge_id\' srid=0 type=LineString table="city_data"."edge" (geom) sql=')
        self.assertEqual(name, 'city_data.edge')
コード例 #17
0
ファイル: offsetcurve.py プロジェクト: wongjimsan/QGIS
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        geometry = self.getParameterValue(self.GEOMETRY)
        distance = self.getParameterValue(self.RADIUS)
        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)

        layername = ogrLayerName(inLayer)

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

        sql = "SELECT ST_OffsetCurve({}, {}), * FROM '{}'".format(geometry, distance, layername)

        arguments.append(sql)

        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
コード例 #18
0
ファイル: rasterize_over.py プロジェクト: HeatherHillers/QGIS
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        inRasterLayer = self.getParameterValue(self.INPUT_RASTER)
        ogrRasterLayer = ogrConnectionString(inRasterLayer)[1:-1]

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

        arguments.append('-l')
        arguments.append(ogrLayerName(inLayer))
        arguments.append(ogrLayer)
        arguments.append(ogrRasterLayer)

        return ['gdal_rasterize', GdalUtils.escapeAndJoin(arguments)]
コード例 #19
0
ファイル: rasterize_over.py プロジェクト: ndavid/QGIS
    def getConsoleCommands(self, parameters):
        context = dataobjects.createContext()
        inLayer = QgsProcessingUtils.mapLayerFromString(self.getParameterValue(self.INPUT), context)
        inRasterLayer = QgsProcessingUtils.mapLayerFromString(self.getParameterValue(self.INPUT_RASTER), context)

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

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

        arguments.append('-l')
        arguments.append(ogrLayerName(inLayer))
        arguments.append(ogrLayer)
        arguments.append(ogrRasterLayer)

        return ['gdal_rasterize', GdalUtils.escapeAndJoin(arguments)]
コード例 #20
0
ファイル: ogr2ogr.py プロジェクト: ndavid/QGIS
    def getConsoleCommands(self, parameters):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]

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

        formatIdx = self.getParameterValue(self.FORMAT)
        outFormat = FORMATS[formatIdx]
        ext = EXTS[formatIdx]
        if not outFile.endswith(ext):
            outFile += ext
            output.value = outFile

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

        if outFormat == 'SQLite' and os.path.isfile(output):
            os.remove(output)

        arguments = []
        arguments.append('-f')
        arguments.append(outFormat)

        if options is not None and len(options.strip()) > 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
コード例 #21
0
    def getConsoleCommands(self):
        connection = self.DB_CONNECTIONS[self.getParameterValue(self.DATABASE)]
        settings = QSettings()
        mySettings = '/PostgreSQL/connections/' + connection
        dbname = settings.value(mySettings + '/database')
        user = settings.value(mySettings + '/username')
        host = settings.value(mySettings + '/host')
        port = settings.value(mySettings + '/port')
        password = settings.value(mySettings + '/password')
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        schema = unicode(self.getParameterValue(self.SCHEMA))
        table = unicode(self.getParameterValue(self.TABLE))
        pk = unicode(self.getParameterValue(self.PK))
        pkstring = "-lco FID=" + pk
        primary_key = self.getParameterValue(self.PRIMARY_KEY)
        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"
        skipfailures = self.getParameterValue(self.SKIPFAILURES)
        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=')
        arguments.append(host)
        arguments.append('port=')
        arguments.append(port)
        if len(dbname) > 0:
            arguments.append('dbname=' + dbname)
        if len(password) > 0:
            arguments.append('password=' + password)
        if len(schema) > 0:
            arguments.append('active_schema=' + schema)
        else:
            arguments.append('active_schema=public')
        arguments.append('user=' + user + '"')
        arguments.append(ogrLayer)
        arguments.append('-nlt NONE')
        arguments.append(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:
            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
コード例 #22
0
    def getConsoleCommands(self, parameters):
        connection = self.DB_CONNECTIONS[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 = ogrConnectionString(inLayer)[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(self.processing).split(' '):
            arguments.append(token)
        arguments.append('active_schema={}'.format(schema or 'public'))
        arguments.append('"')
        arguments.append(ogrLayer)
        arguments.append('-nlt NONE')
        arguments.append(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 = 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
コード例 #23
0
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        shapeEncoding = self.getParameterValue(self.SHAPE_ENCODING)
        ssrs = str(self.getParameterValue(self.S_SRS))
        tsrs = str(self.getParameterValue(self.T_SRS))
        asrs = str(self.getParameterValue(self.A_SRS))
        table = str(self.getParameterValue(self.TABLE))
        pk = str(self.getParameterValue(self.PK))
        pkstring = "-lco FID=" + pk
        primary_key = self.getParameterValue(self.PRIMARY_KEY)
        geocolumn = str(self.getParameterValue(self.GEOCOLUMN))
        geocolumnstring = "-lco GEOMETRY_NAME=" + geocolumn
        dim = self.DIMLIST[self.getParameterValue(self.DIM)]
        dimstring = "-lco DIM=" + dim
        simplify = str(self.getParameterValue(self.SIMPLIFY))
        segmentize = str(self.getParameterValue(self.SEGMENTIZE))
        spat = self.getParameterValue(self.SPAT)
        clip = self.getParameterValue(self.CLIP)
        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"
        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 = 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:"')
        arguments.append(self.getConnectionString())
        arguments.append('"')
        arguments.append(dimstring)
        arguments.append(ogrLayer)
        arguments.append(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(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 = ogrLayerName(inLayer).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 len(spat) > 0:
            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(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
コード例 #24
0
    def processAlgorithm(self, progress):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        layername = ogrLayerName(inLayer)
        dsUri = QgsDataSourceURI(self.getParameterValue(self.INPUT_LAYER))
        geomColumn = dsUri.geometryColumn()
        layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))
        geomType = layer.geometryType()
        wkbType = layer.wkbType()
        srid = layer.crs().postgisSrid()
        field = unicode(self.getParameterValue(self.FIELD))
        statsatt = unicode(self.getParameterValue(self.STATSATT))
        stats = self.getParameterValue(self.STATS)
        area = self.getParameterValue(self.AREA)
        single = self.getParameterValue(self.SINGLE)
        count = self.getParameterValue(self.COUNT)
        schema = unicode(self.getParameterValue(self.SCHEMA))
        table = unicode(self.getParameterValue(self.TABLE))
        dissolveall = self.getParameterValue(self.DISSOLVEALL)
        options = unicode(self.getParameterValue(self.OPTIONS))

        if single:
           layertype = "POLYGON"              
        else:
           layertype = "MULTIPOLYGON"

        if dissolveall:
           fieldstring = ""
        else:
           fieldstring = "," + field

        if single:
            querystart = '-sql "SELECT (ST_Dump(ST_Union(' + geomColumn + '))).geom::geometry(POLYGON,' + str(srid) + ')' + fieldstring
        else:
            querystart = '-sql "SELECT (ST_Multi(ST_Union(' + geomColumn + ')))::geometry(MULTIPOLYGON,' + str(srid) + ')' + fieldstring

        if dissolveall:
            queryend = ' FROM ' + layername + '"' + " -nln " + schema + "." + table + " -nlt " + layertype + " -lco FID=gid -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
        else:
            queryend = ' FROM ' + layername + ' GROUP BY ' + field + '"' + " -nln " + schema + "." + table + " -nlt " + layertype + " -lco FID=gid -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"

        #if fields:
        #   queryfields = ",*"
        #else:
        #   queryfields = "," + field
        if count:
           querycount = ", COUNT(" + geomColumn + ") AS count"
        else:
           querycount = ""
        if stats:
           querystats = ", SUM(" + statsatt + ") AS sum_dissolved, MIN(" + statsatt + ") AS min_dissolved, MAX(" + statsatt + ") AS max_dissolved, AVG(" + statsatt + ") AS avg_dissolved"
        else:
           querystats = ""
        if area:
           queryarea = ", SUM(ST_area(" + geomColumn + ")) AS area_dissolved, ST_perimeter(ST_union(" + geomColumn + ")) AS perimeter_dissolved"
        else:
           queryarea = ""
        query = querystart + querystats + queryarea + querycount +  queryend
        #query = querystart + queryfields + querycount + querystats + queryarea + queryend
        arguments = []
        arguments.append('-f')
        arguments.append('PostgreSQL')
        arguments.append(ogrLayer)
        arguments.append(ogrLayer)
        arguments.append(query)
        arguments.append('-overwrite')
                
        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)

        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()          
コード例 #25
0
ファイル: ogr2ogrtopostgislist.py プロジェクト: spono/QGIS
    def getConsoleCommands(self):
        connection = self.DB_CONNECTIONS[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 = ogrConnectionString(inLayer)[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)
        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(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 = 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
コード例 #26
0
    def processAlgorithm(self, progress):
        inLayer = self.getParameterValue(self.INPUT_LAYER)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        layername = ogrLayerName(inLayer)
        dsUri = QgsDataSourceURI(self.getParameterValue(self.INPUT_LAYER))
        geomColumn = dsUri.geometryColumn()
        layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))
        geomType = layer.geometryType()
        wkbType = layer.wkbType()
        srid = layer.crs().postgisSrid()
        fields = unicode(self.getParameterValue(self.FIELDS))
        dissfield = unicode(self.getParameterValue(self.DISSFIELD))
        schema = unicode(self.getParameterValue(self.SCHEMA))
        table = unicode(self.getParameterValue(self.TABLE))
        options = unicode(self.getParameterValue(self.OPTIONS))
        distance = unicode(self.getParameterValue(self.DISTANCE))
        dissolveall = self.getParameterValue(self.DISSOLVEALL)
        single = self.getParameterValue(self.SINGLE)

        if len(fields) > 0:
           fieldstring = fields + ","
        else:
           fieldstring = ""

        if dissolveall:
             if single:
                query = '-sql "SELECT (ST_Dump(ST_Multi(ST_Union(ST_Buffer(' + geomColumn + ',' + distance + '))))).geom::geometry(POLYGON,' + str(srid) + ') AS geom FROM ' + layername + '" -nln ' + schema + '.' + table + ' -nlt POLYGON -lco FID=gid -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES'
             else:
                query = '-sql "SELECT (ST_Multi(ST_Union(ST_Buffer(' + geomColumn + ',' + distance + '))))::geometry(MULTIPOLYGON,' + str(srid) + ') AS geom FROM ' + layername + '" -nln ' + schema + '.' + table + ' -nlt MULTIPOLYGON -lco FID=gid -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES'
        else:
           if dissfield != 'None':
             if single:
                query = '-sql "SELECT ' + dissfield + ',(ST_Dump(ST_Union(ST_Buffer(' + geomColumn + ',' + distance + ')))).geom::geometry(POLYGON,' + str(srid) + ') AS geom FROM ' + layername + ' GROUP BY ' + dissfield + '" -nln ' + schema + '.' + table + ' -nlt POLYGON -lco FID=gid -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES'       
             else:
                query = '-sql "SELECT ' + dissfield + ',(ST_Multi(ST_Union(ST_Buffer(' + geomColumn + ',' + distance + '))))::geometry(MULTIPOLYGON,' + str(srid) + ') AS geom FROM ' + layername + ' GROUP BY ' + dissfield + '" -nln ' + schema + '.' + table + ' -nlt MULTIPOLYGON -lco FID=gid -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES'
           else:
             if single:
                query = '-sql "SELECT ' + fieldstring + '(ST_Dump(ST_Multi(ST_Buffer(' + geomColumn + ',' + distance + ')))).geom::geometry(POLYGON,' + str(srid) + ') AS geom FROM ' + layername + '" -nln ' + schema + '.' + table + ' -nlt POLYGON -lco FID=gid -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES'
             else:
                query = '-sql "SELECT ' + fieldstring + '(ST_Multi(ST_Buffer(' + geomColumn + ',' + distance + ')))::geometry(MULTIPOLYGON,' + str(srid) + ') AS geom FROM ' + layername + '" -nln ' + schema + '.' + table + ' -nlt MULTIPOLYGON -lco FID=gid -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES'

        print dissfield 
        arguments = []
        arguments.append('-f')
        arguments.append('PostgreSQL')
        arguments.append(ogrLayer)
        arguments.append(ogrLayer)
        arguments.append(query)
        arguments.append('-overwrite')
                
        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)

        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()          
コード例 #27
0
    def processAlgorithm(self, progress):
        inLayerA = self.getParameterValue(self.INPUT_LAYER_A)
        ogrLayerA = ogrConnectionString(inLayerA)[1:-1]
        layernameA = ogrLayerName(inLayerA)
        inLayerB = self.getParameterValue(self.INPUT_LAYER_B)
        ogrLayerB = ogrConnectionString(inLayerB)[1:-1]
        layernameB = ogrLayerName(inLayerB)
        fieldsB = unicode(self.getParameterValue(self.FIELDS_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))
        geomTypeB = layerB.geometryType()
        wkbTypeB = layerB.wkbType()
        sridB = layerB.crs().postgisSrid()
        schema = unicode(self.getParameterValue(self.SCHEMA))
        table = unicode(self.getParameterValue(self.TABLE))
        single = self.getParameterValue(self.SINGLE)
        keep = self.getParameterValue(self.KEEP)
        keepc = self.getParameterValue(self.KEEPC)
        
        if len(fieldsB) > 0:
           fieldstringB = fieldsB.replace(",", ", g2.")
           fieldstringB = ", g2." + fieldstringB
        else:
           fieldstringB = ""          

        if geomTypeB == 0:
           type = "POINT"
        elif geomTypeB == 1:
           type = "LINESTRING"
        else:
           type = "POLYGON"

        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 = ""           
           
        if geomTypeB == 0:        
           if keep:
              sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Intersects(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
           else:
              sqlstring = "-sql \"WITH temp_table AS (SELECT ST_Union(" + geomColumnA + ") AS geom FROM " + layernameA + ") SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM temp_table AS g1, " + layernameB + " AS g2 WHERE ST_Contains(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES -a_srs EPSG:" + str(sridB) + ""
        elif geomTypeB == 1:
           if keepc:
              if keep:
                 sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Contains(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
              else:
                 sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_ContainsProperly(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
           else:
              if keep:
                 sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Intersects(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
              else:
                 sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Intersects(g1." + geomColumnA + ",g2." + geomColumnB + ") is true AND ST_Touches(g1." + geomColumnA + ",g2." + geomColumnB + ") is false\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
        else:
           if keepc:
              if keep:
                 sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Contains(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
              else:
                 sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_ContainsProperly(g1." + geomColumnA + ",g2." + geomColumnB + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
           else:
              if keep:
                 sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Intersects(g1." + geomColumnA + ",g2." + geomColumnB + ") is true OR ST_Contains(g2." + geomColumnB + ",g1." + geomColumnA + ") is true\" -nln " + schema + "." + table + " -lco FID=gid " + multistring + " -lco GEOMETRY_NAME=geom --config PG_USE_COPY YES"
              else:
                 sqlstring = "-sql \"SELECT (" + st_function + "(g2." + geomColumnB + "))" + castgeom + "::geometry(" + caststring + "," + str(sridB) + ") AS geom" + fieldstringB + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 WHERE ST_Contains(g1." + geomColumnA + ",g2." + geomColumnB + ") is true OR ST_Overlaps(g1." + geomColumnA + ",g2." + geomColumnB + ") is true OR ST_Contains(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()          
コード例 #28
0
ファイル: ogr2ogrdissolve.py プロジェクト: timlinux/QGIS
    def getConsoleCommands(self, parameters):
        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
コード例 #29
0
ファイル: rasterize.py プロジェクト: borysiasty/QGIS
    def getConsoleCommands(self):
        inLayer = self.getParameterValue(self.INPUT)
        ogrLayer = ogrConnectionString(inLayer)[1:-1]
        noData = self.getParameterValue(self.NO_DATA)
        if noData is not None:
            noData = str(noData)
        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))
        out = self.getOutputValue(self.OUTPUT)
        extra = self.getParameterValue(self.EXTRA)
        if extra is not None:
            extra = str(extra)
        rastext = str(self.getParameterValue(self.RAST_EXT))

        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 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)
        if extra and len(extra) > 0:
            arguments.append(extra)
        arguments.append("-l")

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

        arguments.append(str(self.getOutputValue(self.OUTPUT)))
        return ["gdal_rasterize", GdalUtils.escapeAndJoin(arguments)]
コード例 #30
0
ファイル: rasterize.py プロジェクト: cayetanobv/QGIS
    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)]