'''
Created on Mar 20, 2014
@author: lanalfa
'''
from osgeo import ogr

inFilePoligoni = 'D:\\states.shp'
inDriver = ogr.GetDriverByName("ESRI Shapefile")
inDataPoligoni = inDriver.Open(inFilePoligoni, 0)
inLayerPoligoni = inDataPoligoni.GetLayer()

inFilePunti = 'D:\\dotti_stati.shp'
inDataPunti = inDriver.Open(inFilePunti, 0)
inLayerPunti = inDataPunti.GetLayer()

featureCount = inLayerPunti.GetFeatureCount()
#print featureCount

for feature in inLayerPoligoni:
    if feature.GetField("STATE_NAME") == 'North Dakota':
        geom = feature.GetGeometryRef()
        wkt = geom.ExportToWkt()

inLayerPunti.SetSpatialFilter(ogr.CreateGeometryFromWkt(wkt))

for feature in inLayerPunti:
    print feature.GetField("nomi")

inDataPoligoni.Destroy()
inDataPunti.Destroy()
Beispiel #2
0
    def testGeopackageTwoLayerEdition(self):
        ''' test https://issues.qgis.org/issues/17034 '''
        tmpfile = os.path.join(self.basetestpath, 'testGeopackageTwoLayerEdition.gpkg')
        ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile)
        lyr = ds.CreateLayer('layer1', geom_type=ogr.wkbPoint)
        lyr.CreateField(ogr.FieldDefn('attr', ogr.OFTInteger))
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(0 0)'))
        lyr.CreateFeature(f)
        f = None
        lyr = ds.CreateLayer('layer2', geom_type=ogr.wkbPoint)
        lyr.CreateField(ogr.FieldDefn('attr', ogr.OFTInteger))
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(1 1)'))
        lyr.CreateFeature(f)
        f = None
        ds = None

        vl1 = QgsVectorLayer(u'{}'.format(tmpfile) + "|layername=layer1", u'layer1', u'ogr')
        vl2 = QgsVectorLayer(u'{}'.format(tmpfile) + "|layername=layer2", u'layer2', u'ogr')

        # Edit vl1, vl2 multiple times
        self.assertTrue(vl1.startEditing())
        self.assertTrue(vl2.startEditing())
        self.assertTrue(vl1.changeGeometry(1, QgsGeometry.fromWkt('Point (2 2)')))
        self.assertTrue(vl2.changeGeometry(1, QgsGeometry.fromWkt('Point (3 3)')))
        self.assertTrue(vl1.commitChanges())
        self.assertTrue(vl2.commitChanges())

        self.assertTrue(vl1.startEditing())
        self.assertTrue(vl2.startEditing())
        self.assertTrue(vl1.changeAttributeValue(1, 1, 100))
        self.assertTrue(vl2.changeAttributeValue(1, 1, 101))
        self.assertTrue(vl1.commitChanges())
        self.assertTrue(vl2.commitChanges())

        self.assertTrue(vl1.startEditing())
        self.assertTrue(vl2.startEditing())
        self.assertTrue(vl1.changeGeometry(1, QgsGeometry.fromWkt('Point (4 4)')))
        self.assertTrue(vl2.changeGeometry(1, QgsGeometry.fromWkt('Point (5 5)')))
        self.assertTrue(vl1.commitChanges())
        self.assertTrue(vl2.commitChanges())

        vl1 = None
        vl2 = None

        # Check everything is as expected after re-opening
        vl1 = QgsVectorLayer(u'{}'.format(tmpfile) + "|layername=layer1", u'layer1', u'ogr')
        vl2 = QgsVectorLayer(u'{}'.format(tmpfile) + "|layername=layer2", u'layer2', u'ogr')

        got = [feat for feat in vl1.getFeatures()][0]
        got_geom = got.geometry()
        self.assertEqual(got['attr'], 100)
        reference = QgsGeometry.fromWkt('Point (4 4)')
        self.assertEqual(got_geom.asWkb(), reference.asWkb(), 'Expected {}, got {}'.format(reference.asWkt(), got_geom.asWkt()))

        got = [feat for feat in vl2.getFeatures()][0]
        got_geom = got.geometry()
        self.assertEqual(got['attr'], 101)
        reference = QgsGeometry.fromWkt('Point (5 5)')
        self.assertEqual(got_geom.asWkb(), reference.asWkb(), 'Expected {}, got {}'.format(reference.asWkt(), got_geom.asWkt()))
Beispiel #3
0
def ogr_rfc41_5():

    feature_defn = ogr.FeatureDefn()
    field_defn = ogr.FieldDefn('strfield', ogr.OFTString)
    feature_defn.AddFieldDefn(field_defn)
    feature_defn.GetGeomFieldDefn(0).SetName('geomfield')

    f = ogr.Feature(feature_defn)

    if f['strfield'] != None:
        gdaltest.post_reason('fail')
        return 'fail'
    if f.strfield != None:
        gdaltest.post_reason('fail')
        return 'fail'

    if f['geomfield'] != None:
        gdaltest.post_reason('fail')
        return 'fail'
    if f.geomfield != None:
        gdaltest.post_reason('fail')
        return 'fail'

    try:
        a = f['inexisting_field']
        gdaltest.post_reason('fail')
        return 'fail'
    except:
        pass
    try:
        a = f.inexisting_field
        gdaltest.post_reason('fail')
        return 'fail'
    except:
        pass

    try:
        f['inexisting_field'] = 'foo'
        gdaltest.post_reason('fail')
        return 'fail'
    except:
        pass

    # This works. Default Python behaviour. Stored in a dictionnary
    f.inexisting_field = 'bar'
    if f.inexisting_field != 'bar':
        gdaltest.post_reason('fail')
        return 'fail'

    f['strfield'] = 'foo'
    if f['strfield'] != 'foo':
        gdaltest.post_reason('fail')
        return 'fail'
    if f.strfield != 'foo':
        gdaltest.post_reason('fail')
        return 'fail'

    f.strfield = 'bar'
    if f['strfield'] != 'bar':
        gdaltest.post_reason('fail')
        return 'fail'
    if f.strfield != 'bar':
        gdaltest.post_reason('fail')
        return 'fail'

    wkt = 'POINT EMPTY'
    f['geomfield'] = ogr.CreateGeometryFromWkt(wkt)
    if f['geomfield'].ExportToWkt() != wkt:
        gdaltest.post_reason('fail')
        return 'fail'
    if f.geomfield.ExportToWkt() != wkt:
        gdaltest.post_reason('fail')
        return 'fail'

    wkt2 = 'POLYGON EMPTY'
    f.geomfield = ogr.CreateGeometryFromWkt(wkt2)
    if f['geomfield'].ExportToWkt() != wkt2:
        gdaltest.post_reason('fail')
        return 'fail'
    if f.geomfield.ExportToWkt() != wkt2:
        gdaltest.post_reason('fail')
        return 'fail'

    return 'success'
Beispiel #4
0
    def processAlgorithm(self, parameters, context, feedback):
        raster_layer = self.parameterAsRasterLayer(parameters, self.INPUT_DEM,
                                                   context)
        target_crs = raster_layer.crs()
        rasterPath = raster_layer.source()

        source = self.parameterAsSource(parameters, self.BOUNDARY_LAYER,
                                        context)
        if source is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.BOUNDARY_LAYER))

        step = self.parameterAsDouble(parameters, self.STEP, context)
        percentage = self.parameterAsBool(parameters, self.USE_PERCENTAGE,
                                          context)

        outputPath = self.parameterAsString(parameters, self.OUTPUT_DIRECTORY,
                                            context)

        rasterDS = gdal.Open(rasterPath, gdal.GA_ReadOnly)
        geoTransform = rasterDS.GetGeoTransform()
        rasterBand = rasterDS.GetRasterBand(1)
        noData = rasterBand.GetNoDataValue()

        cellXSize = abs(geoTransform[1])
        cellYSize = abs(geoTransform[5])
        rasterXSize = rasterDS.RasterXSize
        rasterYSize = rasterDS.RasterYSize

        rasterBBox = QgsRectangle(geoTransform[0],
                                  geoTransform[3] - cellYSize * rasterYSize,
                                  geoTransform[0] + cellXSize * rasterXSize,
                                  geoTransform[3])
        rasterGeom = QgsGeometry.fromRect(rasterBBox)

        crs = osr.SpatialReference()
        crs.ImportFromProj4(str(target_crs.toProj4()))

        memVectorDriver = ogr.GetDriverByName('Memory')
        memRasterDriver = gdal.GetDriverByName('MEM')

        features = source.getFeatures(QgsFeatureRequest().setDestinationCrs(
            target_crs, context.transformContext()))
        total = 100.0 / source.featureCount() if source.featureCount() else 0

        for current, f in enumerate(features):
            if not f.hasGeometry():
                continue

            if feedback.isCanceled():
                break

            geom = f.geometry()
            intersectedGeom = rasterGeom.intersection(geom)

            if intersectedGeom.isEmpty():
                feedback.pushInfo(
                    self.tr('Feature {0} does not intersect raster or '
                            'entirely located in NODATA area').format(f.id()))
                continue

            fName = os.path.join(
                outputPath,
                'hystogram_%s_%s.csv' % (source.sourceName(), f.id()))

            ogrGeom = ogr.CreateGeometryFromWkt(intersectedGeom.asWkt())
            bbox = intersectedGeom.boundingBox()
            xMin = bbox.xMinimum()
            xMax = bbox.xMaximum()
            yMin = bbox.yMinimum()
            yMax = bbox.yMaximum()

            (startColumn,
             startRow) = raster.mapToPixel(xMin, yMax, geoTransform)
            (endColumn, endRow) = raster.mapToPixel(xMax, yMin, geoTransform)

            width = endColumn - startColumn
            height = endRow - startRow

            srcOffset = (startColumn, startRow, width, height)
            srcArray = rasterBand.ReadAsArray(*srcOffset)

            if srcOffset[2] == 0 or srcOffset[3] == 0:
                feedback.pushInfo(
                    self.tr('Feature {0} is smaller than raster '
                            'cell size').format(f.id()))
                continue

            newGeoTransform = (geoTransform[0] +
                               srcOffset[0] * geoTransform[1], geoTransform[1],
                               0.0, geoTransform[3] +
                               srcOffset[1] * geoTransform[5], 0.0,
                               geoTransform[5])

            memVDS = memVectorDriver.CreateDataSource('out')
            memLayer = memVDS.CreateLayer('poly', crs, ogr.wkbPolygon)

            ft = ogr.Feature(memLayer.GetLayerDefn())
            ft.SetGeometry(ogrGeom)
            memLayer.CreateFeature(ft)
            ft.Destroy()

            rasterizedDS = memRasterDriver.Create('', srcOffset[2],
                                                  srcOffset[3], 1,
                                                  gdal.GDT_Byte)
            rasterizedDS.SetGeoTransform(newGeoTransform)
            gdal.RasterizeLayer(rasterizedDS, [1], memLayer, burn_values=[1])
            rasterizedArray = rasterizedDS.ReadAsArray()

            srcArray = numpy.nan_to_num(srcArray)
            masked = numpy.ma.MaskedArray(
                srcArray,
                mask=numpy.logical_or(srcArray == noData,
                                      numpy.logical_not(rasterizedArray)))

            self.calculateHypsometry(f.id(), fName, feedback, masked,
                                     cellXSize, cellYSize, percentage, step)

            memVDS = None
            rasterizedDS = None
            feedback.setProgress(int(current * total))

        rasterDS = None

        return {self.OUTPUT_DIRECTORY: outputPath}
Beispiel #5
0
def test_ogr_gmt_5():

    #######################################################
    # Create gmtory Layer
    gmt_drv = ogr.GetDriverByName('GMT')
    gmt_ds = gmt_drv.CreateDataSource('tmp/mpoly.gmt')
    gmt_lyr = gmt_ds.CreateLayer('mpoly')

    #######################################################
    # Setup Schema
    ogrtest.quick_create_layer_def(gmt_lyr, [('ID', ogr.OFTInteger)])

    #######################################################
    # Write a first multipolygon

    dst_feat = ogr.Feature(feature_def=gmt_lyr.GetLayerDefn())
    dst_feat.SetGeometryDirectly(
        ogr.CreateGeometryFromWkt(
            'MULTIPOLYGON(((0 0,0 10,10 10,0 10,0 0),(3 3,4 4, 3 4,3 3)),((12 0,14 0,12 3,12 0)))'
        ))
    dst_feat.SetField('ID', 15)
    gdal.SetConfigOption('GMT_USE_TAB', 'TRUE')  # Ticket #6453
    gmt_lyr.CreateFeature(dst_feat)
    gdal.SetConfigOption('GMT_USE_TAB', None)

    dst_feat = ogr.Feature(feature_def=gmt_lyr.GetLayerDefn())
    dst_feat.SetGeometryDirectly(
        ogr.CreateGeometryFromWkt('MULTIPOLYGON(((30 20,40 20,30 30,30 20)))'))
    dst_feat.SetField('ID', 16)
    gmt_lyr.CreateFeature(dst_feat)

    gmt_lyr = None
    gmt_ds = None

    # Reopen.

    ds = ogr.Open('tmp/mpoly.gmt')
    lyr = ds.GetLayer(0)

    assert lyr.GetLayerDefn().GetGeomType() == ogr.wkbMultiPolygon, \
        'did not get expected multipolygon type.'

    feat = lyr.GetNextFeature()

    assert not ogrtest.check_feature_geometry(
        feat,
        'MULTIPOLYGON(((0 0,0 10,10 10,0 10,0 0),(3 3,4 4, 3 4,3 3)),((12 0,14 0,12 3,12 0)))'
    )

    assert feat.GetField('ID') == 15, 'got wrong id, first feature'

    feat = lyr.GetNextFeature()

    assert not ogrtest.check_feature_geometry(
        feat, 'MULTIPOLYGON(((30 20,40 20,30 30,30 20)))')

    assert feat.GetField('ID') == 16, 'got wrong ID, second feature'

    feat = lyr.GetNextFeature()

    assert feat is None, 'did not get null feature when expected.'
Beispiel #6
0
def test_gdalwarp_lib_128():

    mem_ds = gdal.GetDriverByName('MEM').Create('', 1177, 4719)
    rpc = [
        "HEIGHT_OFF=109",
        "LINE_NUM_COEFF=-0.001245683 -0.09427649 -1.006342 -1.954469e-05 0.001033926 2.020534e-08 -3.845472e-07 -0.002075817 0.0005520694 0 -4.642442e-06 -3.271793e-06 2.705977e-05 -7.634384e-07 -2.132832e-05 -3.248862e-05 -8.17894e-06 -3.678094e-07 2.002032e-06 3.693162e-08",
        "LONG_OFF=7.1477",
        "SAMP_DEN_COEFF=1 0.01415176 -0.003715018 -0.001205632 -0.0007738299 4.057763e-05 -1.649126e-05 0.0001453584 0.0001628194 -7.354731e-05 4.821444e-07 -4.927701e-06 -1.942371e-05 -2.817499e-06 1.946396e-06 3.04243e-06 2.362282e-07 -2.5371e-07 -1.36993e-07 1.132432e-07",
        "LINE_SCALE=2360",
        "SAMP_NUM_COEFF=0.04337163 1.775948 -0.87108 0.007425391 0.01783631 0.0004057179 -0.000184695 -0.04257537 -0.01127869 -1.531228e-06 1.017961e-05 0.000572344 -0.0002941 -0.0001301705 -0.0003289546 5.394918e-05 6.388447e-05 -4.038289e-06 -7.525785e-06 -5.431241e-07",
        "LONG_SCALE=0.8383", "SAMP_SCALE=593", "SAMP_OFF=589",
        "LAT_SCALE=1.4127", "LAT_OFF=33.8992", "LINE_OFF=2359",
        "LINE_DEN_COEFF=1 0.0007273139 -0.0006006867 -4.272095e-07 2.578717e-05 4.718479e-06 -2.116976e-06 -1.347805e-05 -2.209958e-05 8.131258e-06 -7.290143e-08 5.105109e-08 -7.353388e-07 0 2.131142e-06 9.697701e-08 1.237039e-08 7.153246e-08 6.758015e-08 5.811124e-08",
        "HEIGHT_SCALE=96.3"
    ]
    mem_ds.SetMetadata(rpc, "RPC")
    mem_ds.GetRasterBand(1).Fill(255)

    cutlineDSName = '/vsimem/test_gdalwarp_lib_128.json'
    cutline_ds = ogr.GetDriverByName('GeoJSON').CreateDataSource(cutlineDSName)
    cutline_lyr = cutline_ds.CreateLayer('cutline')
    f = ogr.Feature(cutline_lyr.GetLayerDefn())
    f.SetGeometry(
        ogr.CreateGeometryFromWkt(
            'POLYGON ((7.2151 32.51930,7.214316 32.58116,7.216043 32.59476,7.21666 32.5193,7.2151 32.51930))'
        ))
    cutline_lyr.CreateFeature(f)
    f = None
    cutline_lyr = None
    cutline_ds = None

    # Default is GDALWARP_DENSIFY_CUTLINE=YES
    ds = gdal.Warp(
        '',
        mem_ds,
        format='MEM',
        cutlineDSName=cutlineDSName,
        dstSRS='EPSG:4326',
        outputBounds=[7.2, 32.52, 7.217, 32.59],
        xRes=0.000226555,
        yRes=0.000226555,
        transformerOptions=['RPC_DEM=data/test_gdalwarp_lib_128_dem.tif'])
    cs = ds.GetRasterBand(1).Checksum()

    if cs != 4351:
        gdaltest.post_reason('bad checksum')
        print(cs)
        return 'fail'

    # Below steps depend on GEOS
    if not ogrtest.have_geos():
        gdal.Unlink(cutlineDSName)
        return 'success'

    gdal.SetConfigOption('GDALWARP_DENSIFY_CUTLINE', 'ONLY_IF_INVALID')
    ds = gdal.Warp(
        '',
        mem_ds,
        format='MEM',
        cutlineDSName=cutlineDSName,
        dstSRS='EPSG:4326',
        outputBounds=[7.2, 32.52, 7.217, 32.59],
        xRes=0.000226555,
        yRes=0.000226555,
        transformerOptions=['RPC_DEM=data/test_gdalwarp_lib_128_dem.tif'])
    gdal.SetConfigOption('GDALWARP_DENSIFY_CUTLINE', None)
    cs = ds.GetRasterBand(1).Checksum()

    if cs != 4351:
        gdaltest.post_reason('bad checksum')
        print(cs)
        return 'fail'

    gdal.SetConfigOption('GDALWARP_DENSIFY_CUTLINE', 'NO')
    with gdaltest.error_handler():
        ds = gdal.Warp(
            '',
            mem_ds,
            format='MEM',
            cutlineDSName=cutlineDSName,
            dstSRS='EPSG:4326',
            outputBounds=[7.2, 32.52, 7.217, 32.59],
            xRes=0.000226555,
            yRes=0.000226555,
            transformerOptions=['RPC_DEM=data/test_gdalwarp_lib_128_dem.tif'])
    gdal.SetConfigOption('GDALWARP_DENSIFY_CUTLINE', None)
    if ds is not None:
        gdaltest.post_reason('expected none return')
        return 'fail'

    gdal.Unlink(cutlineDSName)

    return 'success'
Beispiel #7
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###############################################################################
from osgeo import osr
source = osr.SpatialReference()
source.ImportFromEPSG(2927)
target = osr.SpatialReference()
target.ImportFromEPSG(4326)
transform = osr.CoordinateTransformation(source, target)
transform.TransformPoint(609000,4928000)
###############################################################################
from osgeo import ogr
point = ogr.CreateGeometryFromWkt("POINT (1120351.57 741921.42)")
point.Transform(transform)
point.ExportToWkt()
Beispiel #8
0
def getDatasetFootprint(datafile):

    if datafile is None:
        print 'Missing dataset'
        return None

    cols = datafile.RasterXSize
    rows = datafile.RasterYSize
    bands = datafile.RasterCount

    """Print the information to the screen. Converting the numbers returned to strings using str()"""

    print "Number of columns: " + str(cols)
    print "Number of rows: " + str(rows)
    print "Number of bands: " + str(bands)

    """First we call the GetGeoTransform method of our datafile object"""
    geoinformation = datafile.GetGeoTransform()

    """The top left X and Y coordinates are at list positions 0 and 3 respectively"""

    topLeftX = geoinformation[0]
    topLeftY = geoinformation[3]

    """Print this information to screen"""

    print "Top left X: " + str(topLeftX)
    print "Top left Y: " + str(topLeftY)

    """first we access the projection information within our datafile using the GetProjection() method. This returns a string in WKT format"""

    projInfo = datafile.GetProjection()

    """Then we use the osr module that comes with GDAL to create a spatial reference object"""

    spatialRef = osr.SpatialReference()

    """We import our WKT string into spatialRef"""

    spatialRef.ImportFromWkt(projInfo)

    """We use the ExportToProj4() method to return a proj4 style spatial reference string."""

    spatialRefProj = spatialRef.ExportToProj4()

    """We can then print them out"""

    print "WKT format: " + str(spatialRef)
    print "Proj4 format: " + str(spatialRefProj)

    gcps = datafile.GetGCPs()

    projection = None
    if gcps is None or len(gcps) == 0:
        print('No GCPs found in file')
        geotransform = datafile.GetGeoTransform()
        projection = datafile.GetProjection()
    else:
        geotransform = gdal.GCPsToGeoTransform( gcps )
        projection = datafile.GetGCPProjection()

    if geotransform is None:
        print('Unable to extract a geotransform.')
        return None

    def toWKT(col, row):
        lng = geotransform[0] + col * geotransform[1] + row * geotransform[2]
        lat = geotransform[3] + col * geotransform[4] + row * geotransform[5]
        return str(lng) + " " + str(lat)

    wktGeometry = "POLYGON((" + toWKT(0, 0)  + ", " + toWKT(0, rows) + ", " + toWKT(cols, rows) + ", " + toWKT(cols, 0) + ", " + toWKT(0, 0) + "))"
    print "Footprint geometry " + wktGeometry + ", projection is " + projection

    footprint = ogr.CreateGeometryFromWkt(wktGeometry)

    # now make sure we have the footprint in 4326
    if projection is not None:
        source = osr.SpatialReference(projection)
        target = osr.SpatialReference()
        target.ImportFromEPSG(4326)
        transform = osr.CoordinateTransformation(source, target)
        footprint.Transform(transform)
        print "Footprint geometry reprojected " + footprint.ExportToWkt()

    return footprint.ExportToWkt()
Beispiel #9
0
def test_gdal_grid_1():
    if gdal_grid is None:
        return 'skip'

    shape_drv = ogr.GetDriverByName('ESRI Shapefile')
    outfiles.append('tmp/n43.tif')

    try:
        os.remove('tmp/n43.shp')
    except:
        pass
    try:
        os.remove('tmp/n43.dbf')
    except:
        pass
    try:
        os.remove('tmp/n43.shx')
    except:
        pass
    try:
        os.remove('tmp/n43.qix')
    except:
        pass

    # Create an OGR grid from the values of n43.dt0
    ds = gdal.Open('../gdrivers/data/n43.dt0')
    geotransform = ds.GetGeoTransform()

    shape_drv = ogr.GetDriverByName('ESRI Shapefile')
    shape_ds = shape_drv.CreateDataSource( 'tmp' )
    shape_lyr = shape_ds.CreateLayer( 'n43' )

    data = ds.ReadRaster(0, 0, 121, 121)
    array_val = struct.unpack('h' * 121*121, data)
    for j in range(121):
        for i in range(121):
            wkt = 'POINT(%f %f %s)' % ( geotransform[0] + (i + .5) * geotransform[1],
                                        geotransform[3] + (j + .5) * geotransform[5],
                                        array_val[j * 121 + i] )
            dst_feat = ogr.Feature( feature_def = shape_lyr.GetLayerDefn() )
            dst_feat.SetGeometry(ogr.CreateGeometryFromWkt(wkt))
            shape_lyr.CreateFeature( dst_feat )

    dst_feat.Destroy()

    shape_ds.ExecuteSQL('CREATE SPATIAL INDEX ON n43')

    shape_ds.Destroy()

    # Create a GDAL dataset from the previous generated OGR grid
    (out, err) = gdaltest.runexternal_out_and_err(gdal_grid + ' -txe -80.0041667 -78.9958333 -tye 42.9958333 44.0041667 -outsize 121 121 -ot Int16 -l n43 -a nearest:radius1=0.0:radius2=0.0:angle=0.0 -co TILED=YES -co BLOCKXSIZE=256 -co BLOCKYSIZE=256 tmp/n43.shp ' + outfiles[-1])
    if not (err is None or err == '') :
        gdaltest.post_reason('got error/warning')
        print(err)
        return 'fail'

    # We should get the same values as in n43.td0
    ds2 = gdal.Open(outfiles[-1])
    if ds.GetRasterBand(1).Checksum() != ds2.GetRasterBand(1).Checksum():
        print('bad checksum : got %d, expected %d' % (ds.GetRasterBand(1).Checksum() , ds2.GetRasterBand(1).Checksum()))
        return 'fail'
    if ds2.GetRasterBand(1).GetNoDataValue() is not None:
        print('did not expect nodata value')
        return 'fail'

    ds = None
    ds2 = None

    return 'success'
Beispiel #10
0
def test_ogr_oci_21():

    if gdaltest.oci_ds is None:
        pytest.skip()

    lyr = gdaltest.oci_ds.CreateLayer('ogr_oci_21',
                                      geom_type=ogr.wkbPoint,
                                      options=['DIM=2'])

    field_defn = ogr.FieldDefn('field_string', ogr.OFTString)
    field_defn.SetDefault("'a''b'")
    lyr.CreateField(field_defn)

    field_defn = ogr.FieldDefn('field_int', ogr.OFTInteger)
    field_defn.SetDefault('123')
    lyr.CreateField(field_defn)

    field_defn = ogr.FieldDefn('field_real', ogr.OFTReal)
    field_defn.SetDefault('1.23')
    lyr.CreateField(field_defn)

    field_defn = ogr.FieldDefn('field_nodefault', ogr.OFTInteger)
    lyr.CreateField(field_defn)

    field_defn = ogr.FieldDefn('field_datetime', ogr.OFTDateTime)
    field_defn.SetDefault("CURRENT_TIMESTAMP")
    lyr.CreateField(field_defn)

    field_defn = ogr.FieldDefn('field_datetime2', ogr.OFTDateTime)
    field_defn.SetDefault("'2015/06/30 12:34:56'")
    lyr.CreateField(field_defn)

    # field_defn = ogr.FieldDefn( 'field_date', ogr.OFTDate )
    # field_defn.SetDefault("CURRENT_DATE")
    # lyr.CreateField(field_defn)

    # field_defn = ogr.FieldDefn( 'field_time', ogr.OFTTime )
    # field_defn.SetDefault("CURRENT_TIME")
    # lyr.CreateField(field_defn)

    f = ogr.Feature(lyr.GetLayerDefn())
    f.SetField('field_string', 'c')
    f.SetField('field_int', 456)
    f.SetField('field_real', 4.56)
    f.SetField('field_datetime', '2015/06/30 12:34:56')
    f.SetField('field_datetime2', '2015/06/30 12:34:56')
    f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 1)'))
    lyr.CreateFeature(f)
    f = None

    # Transition from BoundCopy to UnboundCopy
    f = ogr.Feature(lyr.GetLayerDefn())
    f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 1)'))
    lyr.CreateFeature(f)
    f = None

    lyr.SyncToDisk()

    oci_ds2 = ogr.Open(os.environ['OCI_DSNAME'])

    lyr = oci_ds2.GetLayerByName('ogr_oci_21')
    assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(
        'field_string')).GetDefault() == "'a''b'"
    assert lyr.GetLayerDefn().GetFieldDefn(
        lyr.GetLayerDefn().GetFieldIndex('field_int')).GetDefault() == '123'
    assert lyr.GetLayerDefn().GetFieldDefn(
        lyr.GetLayerDefn().GetFieldIndex('field_real')).GetDefault() == '1.23'
    assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(
        'field_nodefault')).GetDefault() is None
    assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(
        'field_datetime')).GetDefault() == 'CURRENT_TIMESTAMP'
    assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(
        'field_datetime2')).GetDefault() == "'2015/06/30 12:34:56'"
    # if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault() != "CURRENT_DATE":
    #    gdaltest.post_reason('fail')
    #    print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_date')).GetDefault())
    #    return 'fail'
    # if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_time')).GetDefault() != "CURRENT_TIME":
    #    gdaltest.post_reason('fail')
    #    return 'fail'

    f = lyr.GetNextFeature()
    if f.GetField('field_string') != 'c':
        f.DumpReadable()
        pytest.fail()

    f = lyr.GetNextFeature()
    if f.GetField('field_string') != 'a\'b' or f.GetField('field_int') != 123 or \
       f.GetField('field_real') != 1.23 or \
       not f.IsFieldNull('field_nodefault') or not f.IsFieldSet('field_datetime') or \
       f.GetField('field_datetime2') != '2015/06/30 12:34:56':
        f.DumpReadable()
        pytest.fail()

    gdal.Unlink('/vsimem/ogr_gpkg_24.gpkg')
Beispiel #11
0
def ogr_pgdump_3():

    try:
        os.remove('tmp/tpoly.sql')
    except:
        pass

    gdal.SetConfigOption( 'PG_USE_COPY', 'YES' )

    ds = ogr.GetDriverByName('PGDump').CreateDataSource('tmp/tpoly.sql', options = [ 'LINEFORMAT=LF' ] )

    ######################################################
    # Create Layer
    lyr = ds.CreateLayer( 'tpoly', geom_type = ogr.wkbNone, options = [ 'SCHEMA=another_schema' ] )

    ######################################################
    # Setup Schema
    ogrtest.quick_create_layer_def( lyr,
                                    [ ('EMPTYCHAR', ogr.OFTString),
                                      ('AREA', ogr.OFTReal),
                                      ('EAS_ID', ogr.OFTInteger),
                                      ('PRFEDEA', ogr.OFTString),
                                      ('SHORTNAME', ogr.OFTString, 8) ] )

    ######################################################
    # Copy in poly.shp

    dst_feat = ogr.Feature( feature_def = lyr.GetLayerDefn() )

    shp_ds = ogr.Open( 'data/poly.shp' )
    shp_lyr = shp_ds.GetLayer(0)
    feat = shp_lyr.GetNextFeature()
    gdaltest.poly_feat = []

    i = 0
    
    while feat is not None:

        gdaltest.poly_feat.append( feat )

        dst_feat.SetFrom( feat )
        if i == 0:
            # Be perverse and test the case where a feature has a geometry
            # even if it's a wkbNone layer ! (#4040)
            dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT(0 1)'))
        elif i == 1:
            # Field with 0 character (not empty!) (#4040)
            dst_feat.SetField(0, '')
        i = i + 1
        lyr.CreateFeature( dst_feat )

        feat = shp_lyr.GetNextFeature()

    dst_feat.Destroy()
    ds.Destroy()

    gdal.SetConfigOption( 'PG_USE_COPY', 'NO' )

    f = open('tmp/tpoly.sql')
    sql = f.read()
    f.close()
    
    if sql.find("""DROP TABLE IF EXISTS "another_schema"."tpoly" CASCADE;""") == -1 or \
       sql.find("""DELETE FROM geometry_columns""") != -1 or \
       sql.find("""BEGIN;""") == -1 or \
       sql.find("""CREATE TABLE "another_schema"."tpoly" (    OGC_FID SERIAL,    CONSTRAINT "tpoly_pk" PRIMARY KEY (OGC_FID) );""") == -1 or \
       sql.find("""SELECT AddGeometryColumn""") != -1 or \
       sql.find("""CREATE INDEX "tpoly_wkb_geometry_geom_idx""") != -1 or \
       sql.find("""ALTER TABLE "another_schema"."tpoly" ADD COLUMN "area" FLOAT8;""") == -1 or \
       sql.find("""ALTER TABLE "another_schema"."tpoly" ADD COLUMN "eas_id" INTEGER;""") == -1 or \
       sql.find("""ALTER TABLE "another_schema"."tpoly" ADD COLUMN "prfedea" VARCHAR;""") == -1 or \
       sql.find("""ALTER TABLE "another_schema"."tpoly" ADD COLUMN "shortname" VARCHAR(8);""") == -1 or \
       sql.find("""COPY "another_schema"."tpoly" ("emptychar", "area", "eas_id", "prfedea", "shortname") FROM STDIN;""") == -1 or \
       sql.find("""\\N	215229.266	168	35043411	\\N""") == -1 or \
       sql.find("""	5268.813	170	35043413	\\N""") == -1 or \
       sql.find("""\\.""") == -1 or \
       sql.find("""COMMIT;""") == -1 :
        print(sql)
        return 'fail'
        
    return 'success'
Beispiel #12
0
def test_ogr_oci_20():

    if gdaltest.oci_ds is None:
        pytest.skip()
    lyr = gdaltest.oci_ds.CreateLayer(
        'ogr_oci_20',
        geom_type=ogr.wkbPoint,
        options=['GEOMETRY_NULLABLE=NO', 'DIM=2'])
    assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0
    field_defn = ogr.FieldDefn('field_not_nullable', ogr.OFTString)
    field_defn.SetNullable(0)
    lyr.CreateField(field_defn)
    field_defn = ogr.FieldDefn('field_nullable', ogr.OFTString)
    lyr.CreateField(field_defn)

    f = ogr.Feature(lyr.GetLayerDefn())
    f.SetField('field_not_nullable', 'not_null')
    f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 1)'))
    ret = lyr.CreateFeature(f)
    f = None
    assert ret == 0

    # Error case: missing geometry
    f = ogr.Feature(lyr.GetLayerDefn())
    f.SetField('field_not_nullable', 'not_null')
    gdal.PushErrorHandler()
    ret = lyr.CreateFeature(f)
    gdal.PopErrorHandler()
    assert ret != 0
    f = None

    # Error case: missing non-nullable field
    f = ogr.Feature(lyr.GetLayerDefn())
    f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 0)'))
    gdal.PushErrorHandler()
    ret = lyr.CreateFeature(f)
    gdal.PopErrorHandler()
    assert ret != 0
    f = None
    lyr.SyncToDisk()

    # Test with nullable geometry
    lyr = gdaltest.oci_ds.CreateLayer('ogr_oci_20bis',
                                      geom_type=ogr.wkbPoint,
                                      options=['DIM=2'])
    assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 1
    f = ogr.Feature(lyr.GetLayerDefn())
    f.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 1)'))
    ret = lyr.CreateFeature(f)
    f = None
    assert ret == 0

    f = ogr.Feature(lyr.GetLayerDefn())
    ret = lyr.CreateFeature(f)
    f = None
    assert ret == 0
    lyr.SyncToDisk()

    oci_ds2 = ogr.Open(os.environ['OCI_DSNAME'])

    lyr = oci_ds2.GetLayerByName('ogr_oci_20')
    assert lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(
        'field_not_nullable')).IsNullable() == 0
    assert lyr.GetLayerDefn().GetFieldDefn(
        lyr.GetLayerDefn().GetFieldIndex('field_nullable')).IsNullable() == 1
    assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0

    lyr = oci_ds2.GetLayerByName('ogr_oci_20bis')
    assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 1
    feat = lyr.GetNextFeature()
    assert feat.GetGeometryRef() is not None
    feat = lyr.GetNextFeature()
    assert feat.GetGeometryRef() is None
Beispiel #13
0
def build_rectangle_from_point(x, y, radius=0.1):
    return ogr.CreateGeometryFromWkt('POLYGON((%f %f,%f %f,%f %f,%f %f,%f %f))' % \
        (x-radius,y-radius,x-radius,y+radius,x+radius,y+radius,x+radius,y-radius,x-radius,y-radius))
Beispiel #14
0
def build_rectangle(x1, y1, x2, y2):
    return ogr.CreateGeometryFromWkt('POLYGON((%f %f,%f %f,%f %f,%f %f,%f %f))' % \
        (x1,y1,x1,y2,x2,y2,x2,y1,x1,y1))
Beispiel #15
0
 def segmentize_src_poly(length_scale):
     src_poly_geom = ogr.CreateGeometryFromWkt(src_poly.wkt)
     src_poly_geom.Segmentize(length_scale)
     return wkt.loads(src_poly_geom.ExportToWkt())
Beispiel #16
0
@author: Alex
"""
from osgeo import ogr
from osgeo import osr
import shapely.wkt

wkt = "POLYGON((-73.973057 40.764356, -73.981898 40.768094, -73.958209 40.800621, -73.949282 40.796853, -73.973057 40.764356))"
outline = shapely.wkt.loads(wkt)

#result in square degrees (meaningless number)
print outline.area

#to calculate real area, must convert unprojected long/lat to "equal area" map projection in meters
#create ogr geometry object
polygon = ogr.CreateGeometryFromWkt(wkt)

src_spatialReference = osr.SpatialReference()
src_spatialReference.ImportFromEPSG(4326)

dst_spatialReference = osr.SpatialReference()
dst_spatialReference.ImportFromEPSG(54009)

transform = osr.CoordinateTransformation(src_spatialReference, dst_spatialReference)

#transform geometry from WGS84 to Mollweide Porjection and convert back to Shapely geometry
polygon.Transform(transform)

outline = shapely.wkt.loads(polygon.ExportToWkt())
print outline.area
Beispiel #17
0
def ogr_of_shapely(geom):
    return ogr.CreateGeometryFromWkt(geom.wkt)
Beispiel #18
0
def exportData(shapefile):

    dstDir = tempfile.mkdtemp()
    dstFile = str(os.path.join(dstDir, shapefile.filename))

    dstSpatialRef = osr.SpatialReference()
    dstSpatialRef.ImportFromWkt(shapefile.srs_wkd)

    driver = ogr.GetDriverByName("ESRI Shapefile")
    datasource = driver.CreateDataSource(dstFile)
    layer = datasource.CreateLayer(str(shapefile.filename), dstSpatialRef)

    # find the spatial reference
    srcSpatialRef = osr.SpatialReference()
    srcSpatialRef.ImportFromEPSG(4326)
    coordTransform = osr.CoordinateTransformation(srcSpatialRef, dstSpatialRef)

    geomField = utils.calcGeometryField(shapefile.geom_type)

    # Define layer attributes
    for attr in shapefile.attribute_set.all():
        field = ogr.FieldDefn(str(attr.name), attr.type)
        field.SetWidth(attr.width)
        field.SetPrecision(attr.precision)
        layer.CreateField(field)

    # Add all the (Single type) geometries for this layer
    for feature in shapefile.feature_set.all():

        # Geometry is a django construct inherited from GeometryField

        geometry = getattr(feature, geomField)
        geometry = utils.unwrapGEOSGeometry(geometry)

        dstGeometry = ogr.CreateGeometryFromWkt(geometry.wkt)
        dstGeometry.Transform(coordTransform)

        dstFeature = ogr.Feature(layer.GetLayerDefn())
        dstFeature.SetGeometry(dstGeometry)

        # add in the feature's attributes
        for attrValue in feature.attributevalue_set.all():
            utils.setOGRFeatureAttribute(attrValue.attribute, attrValue.value,
                                         dstFeature, shapefile.encoding)

        layer.CreateFeature(dstFeature)
        dstFeature.Destroy()

    datasource.Destroy()

    # Compress the shapefile
    temp = tempfile.TemporaryFile()
    zipHandle = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)

    for fName in os.listdir(dstDir):
        zipHandle.write(os.path.join(dstDir, fName), fName)
    zipHandle.close()

    # useful links to temp's directory
    #  shapefileBase = os.path.splitext ( dstFile) [0]
    shapefileName = os.path.splitext(shapefile.filename)[0]

    # Delete the temporary files
    shutil.rmtree(dstDir)

    # Return the zip archive to the user
    f = FileWrapper(temp)
    response = HttpResponse(f, content_type="application\zip")
    response ['Content-Disposition'] = \
       "attachment; filename=" + shapefileName + ".zip"
    response['Content-Length'] = temp.tell()
    temp.seek(0)
    return response
Beispiel #19
0
def ogr_gtm_write_1():

    ds = ogr.GetDriverByName('GPSTrackMaker').CreateDataSource('tmp/gtm.gtm')
    lyr = ds.CreateLayer('gtm_waypoints', geom_type=ogr.wkbPoint)

    dst_feat = ogr.Feature(lyr.GetLayerDefn())
    dst_feat.SetField('name', 'WAY0000000')
    dst_feat.SetField('comment', 'Waypoint 0')
    dst_feat.SetField('icon', 10)
    dst_feat.SetField('time', '2009/12/23 14:25:46')
    dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (-21 -47)'))
    if lyr.CreateFeature(dst_feat) != 0:
        gdaltest.post_reason('CreateFeature failed.')
        return 'fail'

    dst_feat = ogr.Feature(lyr.GetLayerDefn())
    dst_feat.SetField('name', 'WAY0000001')
    dst_feat.SetField('comment', 'Waypoint 1')
    dst_feat.SetField('icon', 31)
    dst_feat.SetGeometry(
        ogr.CreateGeometryFromWkt('POINT (-21.123 -47.231 800)'))
    if lyr.CreateFeature(dst_feat) != 0:
        gdaltest.post_reason('CreateFeature failed.')
        return 'fail'

    lyr = ds.CreateLayer('gtm_tracks', geom_type=ogr.wkbLineString)

    dst_feat = ogr.Feature(lyr.GetLayerDefn())
    dst_feat.SetField('name', '1st Street')
    dst_feat.SetField('type', 2)
    dst_feat.SetField('color', 0x0000FF)
    dst_feat.SetGeometry(
        ogr.CreateGeometryFromWkt(
            'LINESTRING (-21.1 -47.1, -21.2 -47.2, -21.3 -47.3, -21.4 -47.4)'))
    if lyr.CreateFeature(dst_feat) != 0:
        gdaltest.post_reason('CreateFeature failed.')
        return 'fail'

    dst_feat = ogr.Feature(lyr.GetLayerDefn())
    dst_feat.SetField('name', '2nd Street')
    dst_feat.SetField('type', 1)
    dst_feat.SetField('color', 0x000000)
    dst_feat.SetGeometry(
        ogr.CreateGeometryFromWkt(
            'LINESTRING (-21.11 -47.1, -21.21 -47.2, -21.31 -47.3, -21.41 -47.4)'
        ))
    if lyr.CreateFeature(dst_feat) != 0:
        gdaltest.post_reason('CreateFeature failed.')
        return 'fail'

    dst_feat = ogr.Feature(lyr.GetLayerDefn())
    dst_feat.SetField('name', '3rd Street')
    dst_feat.SetField('type', 2)
    dst_feat.SetField('color', 0x000000)
    dst_feat.SetGeometry(ogr.CreateGeometryFromWkt('MULTILINESTRING ((-21.12 -47.1, -21.22 -47.2, -21.32 -47.3, -21.42 -47.4),' + \
                                                   '(-21.12 -47.1, -21.02 -47.0, -20.92 -46.9))'))
    if lyr.CreateFeature(dst_feat) != 0:
        gdaltest.post_reason('CreateFeature failed.')
        return 'fail'

    ds = None

    return 'success'
    def testSubsetStringFids(self):
        """
          - tests that feature ids are stable even if a subset string is set
          - tests that the subset string is correctly set on the ogr layer event when reloading the data source (issue #17122)
        """

        tmpfile = os.path.join(self.basetestpath, 'subsetStringFids.sqlite')
        ds = ogr.GetDriverByName('SQLite').CreateDataSource(tmpfile)
        lyr = ds.CreateLayer('test',
                             geom_type=ogr.wkbPoint,
                             options=['FID=fid'])
        lyr.CreateField(ogr.FieldDefn('type', ogr.OFTInteger))
        lyr.CreateField(ogr.FieldDefn('value', ogr.OFTInteger))
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetFID(0)
        f.SetField(0, 1)
        f.SetField(1, 11)
        f.SetGeometry(ogr.CreateGeometryFromWkt('Point (0 0)'))
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetFID(1)
        f.SetField(0, 1)
        f.SetField(1, 12)
        f.SetGeometry(ogr.CreateGeometryFromWkt('Point (1 1)'))
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetFID(2)
        f.SetField(0, 1)
        f.SetField(1, 13)
        f.SetGeometry(ogr.CreateGeometryFromWkt('Point (2 2)'))
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetFID(3)
        f.SetField(0, 2)
        f.SetField(1, 14)
        f.SetGeometry(ogr.CreateGeometryFromWkt('Point (3 3)'))
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetFID(4)
        f.SetField(0, 2)
        f.SetField(1, 15)
        f.SetGeometry(ogr.CreateGeometryFromWkt('Point (4 4)'))
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetFID(5)
        f.SetField(0, 2)
        f.SetField(1, 16)
        f.SetGeometry(ogr.CreateGeometryFromWkt('Point (5 5)'))
        lyr.CreateFeature(f)
        f = None
        ds = None

        vl = QgsVectorLayer(tmpfile, 'test', 'ogr')
        self.assertTrue(vl.isValid())
        self.assertEqual([f.name() for f in vl.fields()],
                         ['fid', 'type', 'value'])
        original_fields = vl.fields()

        vl = QgsVectorLayer(tmpfile + "|subset=type=2", 'test', 'ogr')
        self.assertTrue(vl.isValid())

        def run_checks():
            self.assertEqual([f.name() for f in vl.fields()],
                             ['fid', 'type', 'value'])

            # expression
            req = QgsFeatureRequest()
            req.setFilterExpression("value=16")
            it = vl.getFeatures(req)
            f = QgsFeature()
            self.assertTrue(it.nextFeature(f))
            self.assertEqual(f.id(), 5)
            self.assertEqual(f.attributes(), [5, 2, 16])
            self.assertEqual([field.name() for field in f.fields()],
                             ['fid', 'type', 'value'])
            self.assertEqual(f.geometry().asWkt(), 'Point (5 5)')

            # filter fid
            req = QgsFeatureRequest()
            req.setFilterFid(5)
            it = vl.getFeatures(req)
            f = QgsFeature()
            self.assertTrue(it.nextFeature(f))
            self.assertEqual(f.id(), 5)
            self.assertEqual(f.attributes(), [5, 2, 16])
            self.assertEqual([field.name() for field in f.fields()],
                             ['fid', 'type', 'value'])
            self.assertEqual(f.geometry().asWkt(), 'Point (5 5)')

            # filter fids
            req = QgsFeatureRequest()
            req.setFilterFids([5])
            it = vl.getFeatures(req)
            f = QgsFeature()
            self.assertTrue(it.nextFeature(f))
            self.assertEqual(f.id(), 5)
            self.assertEqual(f.attributes(), [5, 2, 16])
            self.assertEqual([field.name() for field in f.fields()],
                             ['fid', 'type', 'value'])
            self.assertEqual(f.geometry().asWkt(), 'Point (5 5)')

            # check with subset of attributes
            req = QgsFeatureRequest()
            req.setFilterFids([5])
            req.setSubsetOfAttributes([2])
            it = vl.getFeatures(req)
            f = QgsFeature()
            self.assertTrue(it.nextFeature(f))
            self.assertEqual(f.id(), 5)
            self.assertEqual(f.attributes()[2], 16)
            self.assertEqual([field.name() for field in f.fields()],
                             ['fid', 'type', 'value'])
            self.assertEqual(f.geometry().asWkt(), 'Point (5 5)')

            # filter rect and expression
            req = QgsFeatureRequest()
            req.setFilterExpression("value=16 or value=14")
            req.setFilterRect(QgsRectangle(4.5, 4.5, 5.5, 5.5))
            it = vl.getFeatures(req)
            f = QgsFeature()
            self.assertTrue(it.nextFeature(f))
            self.assertEqual(f.id(), 5)
            self.assertEqual(f.attributes(), [5, 2, 16])
            self.assertEqual([field.name() for field in f.fields()],
                             ['fid', 'type', 'value'])
            self.assertEqual(f.geometry().asWkt(), 'Point (5 5)')

            # filter rect and fids
            req = QgsFeatureRequest()
            req.setFilterFids([3, 5])
            req.setFilterRect(QgsRectangle(4.5, 4.5, 5.5, 5.5))
            it = vl.getFeatures(req)
            f = QgsFeature()
            self.assertTrue(it.nextFeature(f))
            self.assertEqual(f.id(), 5)
            self.assertEqual(f.attributes(), [5, 2, 16])
            self.assertEqual([field.name() for field in f.fields()],
                             ['fid', 'type', 'value'])
            self.assertEqual(f.geometry().asWkt(), 'Point (5 5)')

            # Ensure that orig_ogc_fid is still retrieved even if attribute subset is passed
            req = QgsFeatureRequest()
            req.setSubsetOfAttributes([])
            it = vl.getFeatures(req)
            ids = []
            geoms = {}
            while it.nextFeature(f):
                ids.append(f.id())
                geoms[f.id()] = f.geometry().asWkt()
            self.assertCountEqual(ids, [3, 4, 5])
            self.assertEqual(geoms, {
                3: 'Point (3 3)',
                4: 'Point (4 4)',
                5: 'Point (5 5)'
            })

        run_checks()
        # Check that subset string is correctly set on reload
        vl.reload()
        run_checks()
Beispiel #21
0
def write_centroids(src_path, dst_path, datum='WGS84'):
    """
    Use Shapely to calculate centroid. Output a shapefile with the points.
    in_path = os.path.join(home, "countries", "TM_WORLD_BORDERS-0.3.shp")
    dst_path = os.path.join(home, "shapefile_out", "TM_WORLD_BORDERS-centroids.shp")

    :param src_path:
    :type src_path:
    :param dst_path:
    :type dst_path:
    :param datum:
    :type datum:
    :return:
    :rtype:
    """
    src_shapefile = ogr.Open(src_path)
    src_layer = src_shapefile.GetLayer(0)

    driver = ogr.GetDriverByName("ESRI Shapefile")
    dst_shapefile = driver.CreateDataSource(dst_path)

    spatial_ref = osr.SpatialReference()
    spatial_ref.SetWellKnownGeogCS(datum)
    dst_layer = dst_shapefile.CreateLayer("centroids", spatial_ref)

    field = ogr.FieldDefn("ID", ogr.OFTInteger)
    field.SetWidth(4)
    dst_layer.CreateField(field)

    field = ogr.FieldDefn("ISO3", ogr.OFTString)
    field.SetWidth(3)
    dst_layer.CreateField(field)

    field = ogr.FieldDefn("NAME", ogr.OFTString)
    field.SetWidth(4)
    dst_layer.CreateField(field)

    centroids = []

    for i in range(src_layer.GetFeatureCount()):
        feature = src_layer.GetFeature(i)

        country_code = feature.GetField("ISO3")
        country_name = feature.GetField("NAME")
        shape = feature.GetGeometryRef()

        # Convert to shapely geometry
        country_shape = shapely.wkt.loads(shape.ExportToWkt())
        centroid_wkt = shapely.wkt.dumps(country_shape.centroid)
        centroids.append(centroid_wkt)

        feature = ogr.Feature(dst_layer.GetLayerDefn())
        feature.SetField("ID", i)
        feature.SetField("ISO3", country_code)
        feature.SetField("NAME", country_name)
        geometry = ogr.CreateGeometryFromWkt(centroid_wkt)
        feature.SetGeometry(geometry)

        dst_layer.CreateFeature(feature)

        # Close feature
        feature.Destroy()  # or feature = None

    # Close file handle
    dst_shapefile.FlushCache()
    dst_shapefile.Destroy()  # or dst_shapefile = None

    return centroids
Beispiel #22
0
def ogr_idrisi_3():

    ds = ogr.Open('data/polygons.vct')
    if ds is None:
        gdaltest.post_reason('fail')
        return 'fail'

    lyr = ds.GetLayer(0)
    if lyr.GetGeomType() != ogr.wkbPolygon:
        gdaltest.post_reason('fail')
        return 'fail'

    if lyr.GetFeatureCount() != 2:
        gdaltest.post_reason('fail')
        return 'fail'

    if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1:
        gdaltest.post_reason('fail')
        return 'fail'

    if lyr.TestCapability(ogr.OLCFastGetExtent) != 1:
        gdaltest.post_reason('fail')
        return 'fail'

    if lyr.GetExtent() != (400000.0, 600000.0, 4000000.0, 5000000.0):
        gdaltest.post_reason('fail')
        print(lyr.GetExtent())
        return 'fail'

    feat = lyr.GetNextFeature()
    if feat.GetFieldAsDouble(0) != 1.0:
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    if ogrtest.check_feature_geometry(
            feat,
            ogr.CreateGeometryFromWkt(
                'POLYGON ((400000 4000000,400000 5000000,600000 5000000,600000 4000000,400000 4000000),(450000 4250000,450000 4750000,550000 4750000,550000 4250000,450000 4250000))'
            )) != 0:
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    feat = lyr.GetNextFeature()
    if feat.GetFieldAsDouble(0) != 2.0:
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    if ogrtest.check_feature_geometry(
            feat,
            ogr.CreateGeometryFromWkt(
                'POLYGON ((400000 4000000,400000 5000000,600000 5000000,600000 4000000,400000 4000000))'
            )) != 0:
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    lyr.SetSpatialFilterRect(0, 0, 1, 1)
    lyr.ResetReading()
    feat = lyr.GetNextFeature()
    if feat is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    ds = None

    return 'success'
def save_shapefile_from_polygons(polygons, image_filepath, output_shapefile_filepath, properties_list=None):
    """
    https://gis.stackexchange.com/a/52708/8104
    """
    if properties_list is not None:
        assert len(polygons) == len(properties_list), "polygons and properties_list should have the same length"

    coor, gt, coor_system = get_coor_in_space(image_filepath)
    transform_mat = compute_image_to_epsg_mat(coor, gt)
    # Convert polygons to ogr_polygons
    ogr_polygons = create_ogr_polygons(polygons, transform_mat)

    driver = ogr.GetDriverByName('Esri Shapefile')
    ds = driver.CreateDataSource(output_shapefile_filepath)

    # create the spatial reference, WGS84
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(4326)

    layer = ds.CreateLayer('', None, ogr.wkbPolygon)
    # Add one attribute
    field_name_list = []
    field_type_list = []
    if properties_list is not None:
        for properties in properties_list:
            for (key, value) in properties.items():
                if key not in field_name_list:
                    field_name_list.append(key)
                    field_type_list.append(type(value))
    for (name, py_type) in zip(field_name_list, field_type_list):
        if py_type == int:
            ogr_type = ogr.OFTInteger
        elif py_type == float:
            print("is float")
            ogr_type = ogr.OFTReal
        elif py_type == str:
            ogr_type = ogr.OFTString
        else:
            ogr_type = ogr.OFTInteger
        layer.CreateField(ogr.FieldDefn(name, ogr_type))

    defn = layer.GetLayerDefn()

    for index in range(len(ogr_polygons)):
        ogr_polygon = ogr_polygons[index]
        if properties_list is not None:
            properties = properties_list[index]
        else:
            properties = {}

        # Create a new feature (attribute and geometry)
        feat = ogr.Feature(defn)
        for (key, value) in properties.items():
            feat.SetField(key, value)

        # Make a geometry, from Shapely object
        geom = ogr.CreateGeometryFromWkt(ogr_polygon)
        feat.SetGeometry(geom)

        layer.CreateFeature(feat)
        feat = geom = None  # destroy these

    # Save and close everything
    ds = layer = feat = geom = None
Beispiel #24
0
def ogr_idrisi_1():

    ds = ogr.Open('data/points.vct')
    if ds is None:
        gdaltest.post_reason('fail')
        return 'fail'

    lyr = ds.GetLayer(0)
    if lyr.GetGeomType() != ogr.wkbPoint:
        gdaltest.post_reason('fail')
        return 'fail'

    if lyr.GetLayerDefn().GetFieldDefn(1).GetName() != 'IntegerField':
        gdaltest.post_reason('fail')
        return 'fail'

    if lyr.GetLayerDefn().GetFieldDefn(1).GetType() != ogr.OFTInteger:
        gdaltest.post_reason('fail')
        return 'fail'

    sr = lyr.GetSpatialRef()
    if sr.ExportToWkt().find('PROJCS["UTM Zone 31, Northern Hemisphere"') != 0:
        gdaltest.post_reason('fail')
        print(sr.ExportToWkt())
        return 'fail'

    if lyr.GetFeatureCount() != 2:
        gdaltest.post_reason('fail')
        return 'fail'

    if lyr.TestCapability(ogr.OLCFastFeatureCount) != 1:
        gdaltest.post_reason('fail')
        return 'fail'

    if lyr.TestCapability(ogr.OLCFastGetExtent) != 1:
        gdaltest.post_reason('fail')
        return 'fail'

    if lyr.GetExtent() != (400000.0, 600000.0, 4000000.0, 5000000.0):
        gdaltest.post_reason('fail')
        print(lyr.GetExtent())
        return 'fail'

    feat = lyr.GetNextFeature()
    if feat.GetFieldAsDouble(0) != 1.0:
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    if feat.GetFieldAsInteger(1) != 2:
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    if feat.GetFieldAsDouble(2) != 3.45:
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    if feat.GetFieldAsString(3) != 'foo':
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    if ogrtest.check_feature_geometry(
            feat, ogr.CreateGeometryFromWkt('POINT(400000 5000000)')) != 0:
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    feat = lyr.GetNextFeature()
    if feat.GetFieldAsDouble(0) != 2.0:
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    if ogrtest.check_feature_geometry(
            feat, ogr.CreateGeometryFromWkt('POINT (600000 4000000)')) != 0:
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    lyr.SetSpatialFilterRect(600000 - 1, 4000000 - 1, 600000 + 1, 4000000 + 1)
    lyr.ResetReading()
    feat = lyr.GetNextFeature()
    if feat.GetFieldAsDouble(0) != 2.0:
        gdaltest.post_reason('fail')
        feat.DumpReadable()
        return 'fail'

    lyr.SetSpatialFilterRect(0, 0, 1, 1)
    lyr.ResetReading()
    feat = lyr.GetNextFeature()
    if feat is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    ds = None

    return 'success'
Beispiel #25
0
    def test_check_geometries(self):
        """DelineateIt: Check that we can reasonably repair geometries."""
        from natcap.invest.delineateit import delineateit
        srs = osr.SpatialReference()
        srs.ImportFromEPSG(32731)  # WGS84/UTM zone 31s
        projection_wkt = srs.ExportToWkt()

        dem_matrix = numpy.array(
            [[0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0],
             [0, 1, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 0, 0, 0, 0],
             [0, 1, 0, 0, 0, 0]],
            dtype=numpy.int8)
        dem_raster_path = os.path.join(self.workspace_dir, 'dem.tif')
        # byte datatype
        pygeoprocessing.numpy_array_to_raster(dem_matrix, 255, (2, -2),
                                              (2, -2), projection_wkt,
                                              dem_raster_path)

        # empty geometry
        invalid_geometry = ogr.CreateGeometryFromWkt('POLYGON EMPTY')
        self.assertTrue(invalid_geometry.IsEmpty())

        # point outside of the DEM bbox
        invalid_point = ogr.CreateGeometryFromWkt('POINT (-100 -100)')

        # line intersects the DEM but is not contained by it
        valid_line = ogr.CreateGeometryFromWkt(
            'LINESTRING (-100 100, 100 -100)')

        # invalid polygon coult fixed by buffering by 0
        invalid_bowtie_polygon = ogr.CreateGeometryFromWkt(
            'POLYGON ((2 -2, 6 -2, 2 -6, 6 -6, 2 -2))')
        self.assertFalse(invalid_bowtie_polygon.IsValid())

        # Bowtie polygon with vertex in the middle, could be fixed
        # by buffering by 0
        invalid_alt_bowtie_polygon = ogr.CreateGeometryFromWkt(
            'POLYGON ((2 -2, 6 -2, 4 -4, 6 -6, 2 -6, 4 -4, 2 -2))')
        self.assertFalse(invalid_alt_bowtie_polygon.IsValid())

        # invalid polygon could be fixed by closing rings
        invalid_open_ring_polygon = ogr.CreateGeometryFromWkt(
            'POLYGON ((2 -2, 6 -2, 6 -6, 2 -6))')
        self.assertFalse(invalid_open_ring_polygon.IsValid())

        gpkg_driver = gdal.GetDriverByName('GPKG')
        outflow_vector_path = os.path.join(self.workspace_dir, 'vector.gpkg')
        outflow_vector = gpkg_driver.Create(outflow_vector_path, 0, 0, 0,
                                            gdal.GDT_Unknown)
        outflow_layer = outflow_vector.CreateLayer('outflow_layer', srs,
                                                   ogr.wkbUnknown)
        outflow_layer.CreateField(ogr.FieldDefn('geom_id', ogr.OFTInteger))

        outflow_layer.StartTransaction()
        for index, geometry in enumerate(
            (invalid_geometry, invalid_point, valid_line,
             invalid_bowtie_polygon, invalid_alt_bowtie_polygon,
             invalid_open_ring_polygon)):
            if geometry is None:
                self.fail('Geometry could not be created')

            outflow_feature = ogr.Feature(outflow_layer.GetLayerDefn())
            outflow_feature.SetField('geom_id', index)
            outflow_feature.SetGeometry(geometry)
            outflow_layer.CreateFeature(outflow_feature)
        outflow_layer.CommitTransaction()

        self.assertEqual(outflow_layer.GetFeatureCount(), 6)
        outflow_layer = None
        outflow_vector = None

        target_vector_path = os.path.join(self.workspace_dir,
                                          'checked_geometries.gpkg')
        with self.assertRaises(ValueError) as cm:
            delineateit.check_geometries(outflow_vector_path,
                                         dem_raster_path,
                                         target_vector_path,
                                         skip_invalid_geometry=False)
        self.assertTrue('is invalid' in str(cm.exception))

        delineateit.check_geometries(outflow_vector_path,
                                     dem_raster_path,
                                     target_vector_path,
                                     skip_invalid_geometry=True)

        # I only expect to see 1 feature in the output layer, as there's only 1
        # valid geometry.
        expected_geom_areas = {
            2: 0,
        }

        target_vector = gdal.OpenEx(target_vector_path, gdal.OF_VECTOR)
        target_layer = target_vector.GetLayer()
        self.assertEqual(target_layer.GetFeatureCount(),
                         len(expected_geom_areas))

        for feature in target_layer:
            geom = feature.GetGeometryRef()
            self.assertAlmostEqual(
                geom.Area(), expected_geom_areas[feature.GetField('geom_id')])

        target_layer = None
        target_vector = None
Beispiel #26
0
def clip_image_to_shape(source_image_path, output_image_path):
    def image_to_array(pil_array):
        """
        Converts a Python Imaging Library (PIL) array to a
        gdalnumeric image.
        """
        gdal_numeric_array = gdalnumeric.fromstring(pil_array.tobytes(), 'b')
        gdal_numeric_array.shape = pil_array.im.size[1], pil_array.im.size[0]
        return gdal_numeric_array

    def split_path(source_path):
        file_dir = os.path.split(source_path)[0]
        file_name = os.path.split(source_path)[1]
        file_extension = os.path.splitext(file_name)[1]
        file_name = os.path.splitext(file_name)[0]

        print(file_name)

        return file_dir, file_name, file_extension

    def get_geometry_extent(polygons):
        xs = []
        ys = []
        for polygon in polygons:
            for point in polygon:
                xs.append(point[0])
                ys.append(point[1])

        min_x = min(xs)
        max_x = max(xs)
        min_y = min(ys)
        max_y = max(ys)

        # min_x = min(points, key=lambda x: x[0])[0]
        # max_x = max(points, key=lambda x: x[0])[0]
        # min_y = min(points, key=lambda x: x[1])[1]
        # max_y = max(points, key=lambda x: x[1])[1]
        return min_x, max_x, min_y, max_y

    def world_to_pixel(geotransform_matrix, x, y):
        """
        Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
        the pixel location of a geospatial coordinate
        """

        min_x = geotransform_matrix[0]
        max_y = geotransform_matrix[3]
        pixel_size_x = geotransform_matrix[1]
        pixel_size_y = geotransform_matrix[5]
        # rtnX = geotransform_matrix[2]
        # rtnY = geotransform_matrix[4]
        column = int((x - min_x) / pixel_size_x)
        row = int((y - max_y) / pixel_size_y)
        return column, row

    source_file_dir, source_file_name, source_file_extension = split_path(source_image_path)

    # Output file geographic projection
    wkt_projection = 'GEOGCS["WGS 84",' \
                     'DATUM["WGS_1984",' \
                     'SPHEROID["WGS 84",6378137,298.257223563,' \
                     'AUTHORITY["EPSG","7030"]],' \
                     'AUTHORITY["EPSG","6326"]],' \
                     'PRIMEM["Greenwich",0,' \
                     'AUTHORITY["EPSG","8901"]],' \
                     'UNIT["degree",0.01745329251994328,' \
                     'AUTHORITY["EPSG","9122"]],' \
                     'AUTHORITY["EPSG","4326"]]'

    if source_file_extension == '.tif' or source_file_extension == '.tiff':
        source_image = gdal.Open(source_image_path)

        # (x, y) coordinates refer are geographical coordinates (latitude and longtitude)
        # (i, j) and (cols, rows) are pixel coordinates

        # Read coordinates of ground control points (GCPs) and calculate their extent (min and max x, y values)
        gcps = source_image.GetGCPs()
        gcp_x = []
        gcp_y = []
        for a, val in enumerate(gcps):
            gcp_x.append(gcps[a].GCPX)
            gcp_y.append(gcps[a].GCPY)
        min_source_x = min(gcp_x)
        max_source_x = max(gcp_x)
        min_source_y = min(gcp_y)
        max_source_y = max(gcp_y)

        # A warped virtual raster (middle_raster) needs to be created
        # because the source_raster has no geographical projection.
        # That's why it's being reprojected from None to wkt_projection (None to WGS84).
        error_threshold = 0.125
        resampling = gdal.GRA_NearestNeighbour
        middle_image = gdal.AutoCreateWarpedVRT(source_image, None, wkt_projection, resampling, error_threshold)
        source_image = None

        # Calculate the GeoTransform matrix for the input image
        # geotransform[0]   top left x, minimal x value
        # geotransform[1]   pixel width, pixel size in x dimension
        # geotransform[2]   0
        # geotransform[3]   top left y, maximal y value
        # geotransform[4]   0
        # geotransform[5]   pixel height, pixel size in y dimension, should be negative
        source_cols = middle_image.RasterXSize
        source_rows = middle_image.RasterYSize
        geotransform = [min_source_x, (max_source_x - min_source_x) / source_cols, 0,
                        max_source_y, 0, (max_source_y - min_source_y) / source_rows * (-1)]

        # Calculate the x, y coordinates for a lower right corner of the source_image
        pixel_size_source_x = geotransform[1]
        pixel_size_source_y = geotransform[5]
        max_source_x = min_source_x + (source_cols * pixel_size_source_x)
        min_source_y = max_source_y + (source_rows * pixel_size_source_y)

        # Create a polygon equal to extent of the source_image
        # POLYGON((x1 y1, x2 y2, x3 y3, x4 y4, x1 y1))
        image_wkt = 'POLYGON ((' \
                    + str(min_source_x) + ' ' \
                    + str(max_source_y) + ',' \
                    + str(max_source_x) + ' ' \
                    + str(max_source_y) + ',' \
                    + str(max_source_x) + ' ' \
                    + str(min_source_y) + ',' \
                    + str(min_source_x) + ' ' \
                    + str(min_source_y) + ',' \
                    + str(min_source_x) + ' ' \
                    + str(max_source_y) + '))'
        source_geometry = ogr.CreateGeometryFromWkt(image_wkt)

        # Load a *.shp file and read the single feature containing border
        shapefile = ogr.Open(SHP_PATH)
        shapefile_layer = shapefile.GetLayer("PL")
        shapefile_polygon = shapefile_layer.GetNextFeature()
        border_geometry = shapefile_polygon.GetGeometryRef()

        # Calculate the spatial intersection of the source_image and the border shapefile
        # It's a shape of the output image
        output_geometry = border_geometry.Intersection(source_geometry)
        output_geometry_type = output_geometry.GetGeometryType()
        output_geometry_geom_count = output_geometry.GetGeometryCount()

        # GetGeometryType() == 2: LINEARRING
        # GetGeometryType() == 3: POLYGON
        # GetGeometryType() == 6: MULTIPOLYGON

        # Create a list of (x,y) pairs of output_geometry coordinates
        polygons = []
        if output_geometry_type == 3:
            pts = output_geometry.GetGeometryRef(0)
            polygon = []
            for point in range(pts.GetPointCount()):
                polygon.append((pts.GetX(point), pts.GetY(point)))
            polygons.append(polygon)
        elif output_geometry_type == 6:
            for geom in range(output_geometry_geom_count):
                pts = output_geometry.GetGeometryRef(geom)
                pts = pts.GetGeometryRef(0)
                polygon = []
                for p in range(pts.GetPointCount()):
                    polygon.append((pts.GetX(p), pts.GetY(p)))
                polygons.append(polygon)

        # Calculate the pixel extent of the output_geometry polygon
        min_output_x, max_output_x, min_output_y, max_output_y = get_geometry_extent(polygons)
        min_output_i, max_output_j = world_to_pixel(geotransform, min_output_x, max_output_y)
        max_output_i, min_output_j = world_to_pixel(geotransform, max_output_x, min_output_y)

        # If calculated extent is outside of the source_image array it has to be clipped
        if min_output_i < 0:
            min_output_i = 0
        if max_output_j < 0:
            max_output_j = 0
        if max_output_i > source_cols:
            max_output_i = source_cols
        if min_output_j > source_rows:
            min_output_j = source_rows

        # Width and height of the output_raster in pixels
        output_cols = int(max_output_i - min_output_i)
        output_rows = int(min_output_j - max_output_j)

        # Read the middle image as array and select pixels within calculated range
        middle_array = np.array(middle_image.GetRasterBand(1).ReadAsArray())
        clip = middle_array[max_output_j:min_output_j, min_output_i:max_output_i]

        # Calculate the GeoTransform matrix for the output image, it has a different x and y origin
        output_geotransform = geotransform
        output_geotransform[0] = min_output_x
        output_geotransform[3] = max_output_y

        # Convert (x,y) pairs of output_geometry coordinates to pixel coordinates
        polygons_pixel = []
        for polygon in polygons:
            polygon_pixel = []
            for point in polygon:
                polygon_pixel.append(world_to_pixel(output_geotransform, point[0], point[1]))
            polygons_pixel.append(polygon_pixel)

        # Create a new PIL image and rasterize the clipping shape
        polygon_raster = Image.new("L", (output_cols, output_rows), 1)
        rasterize = ImageDraw.Draw(polygon_raster)

        for polygon in polygons_pixel:
            rasterize.polygon(polygon, 0)

        mask = image_to_array(polygon_raster)
        clip = gdalnumeric.choose(mask, (clip, 0)).astype(gdalnumeric.uint16)

        # Create the output file
        driver = gdal.GetDriverByName('GTiff')
        # !
        # proj = middle_image.GetProjection()
        output_image = driver.Create(output_image_path, output_cols, output_rows, 1, gdal.GDT_UInt16)
        output_image.GetRasterBand(1).WriteArray(clip)
        output_image.SetGeoTransform(output_geotransform)
        # !
        output_image.SetProjection(wkt_projection)
        output_image.FlushCache()
        output_image = None

    elif source_file_extension == '.jp2':
        source_image = gdal.Open(source_image_path)

        # TODO: output_image should be in UTM projection
        gdal.Warp(os.path.join(source_file_dir,
                               source_file_name
                               + '_WGS84'
                               + source_file_extension),
                  source_image,
                  dstSRS='EPSG:4326')

        source_image = gdal.Open(os.path.join(source_file_dir,
                                              source_file_name
                                              + '_WGS84'
                                              + source_file_extension))

        source_array = gdalnumeric.LoadFile(os.path.join(source_file_dir,
                                                         source_file_name
                                                         + '_WGS84'
                                                         + source_file_extension))
        geotransform = source_image.GetGeoTransform()

        min_source_x = geotransform[0]
        max_source_y = geotransform[3]

        source_cols = source_image.RasterXSize
        source_rows = source_image.RasterYSize

        pixel_size_source_x = geotransform[1]
        pixel_size_source_y = geotransform[5]
        max_source_x = min_source_x + (source_cols * pixel_size_source_x)
        min_source_y = max_source_y + (source_rows * pixel_size_source_y)

        image_wkt = 'POLYGON ((' \
                    + str(min_source_x) + ' ' \
                    + str(max_source_y) + ',' \
                    + str(max_source_x) + ' ' \
                    + str(max_source_y) + ',' \
                    + str(max_source_x) + ' ' \
                    + str(min_source_y) + ',' \
                    + str(min_source_x) + ' ' \
                    + str(min_source_y) + ',' \
                    + str(min_source_x) + ' ' \
                    + str(max_source_y) + '))'
        source_geometry = ogr.CreateGeometryFromWkt(image_wkt)

        shapefile = ogr.Open(SHP_PATH)
        shapefile_layer = shapefile.GetLayer("PL")
        shapefile_polygon = shapefile_layer.GetNextFeature()
        border_geometry = shapefile_polygon.GetGeometryRef()

        output_geometry = border_geometry.Intersection(source_geometry)
        output_geometry_type = output_geometry.GetGeometryType()
        output_geometry_geom_count = output_geometry.GetGeometryCount()

        # GetGeometryType() == 2: LINEARRING
        # GetGeometryType() == 3: POLYGON
        # GetGeometryType() == 6: MULTIPOLYGON
        polygons = []
        if output_geometry_type == 3:
            pts = output_geometry.GetGeometryRef(0)
            polygon = []
            for point in range(pts.GetPointCount()):
                polygon.append((pts.GetX(point), pts.GetY(point)))
            polygons.append(polygon)

        elif output_geometry_type == 6:
            for geom in range(output_geometry_geom_count):
                pts = output_geometry.GetGeometryRef(geom)
                pts = pts.GetGeometryRef(0)
                polygon = []
                for p in range(pts.GetPointCount()):
                    polygon.append((pts.GetX(p), pts.GetY(p)))
                polygons.append(polygon)

        min_output_x, max_output_x, min_output_y, max_output_y = get_geometry_extent(polygons)

        min_ouput_i, max_output_j = world_to_pixel(geotransform, min_output_x, max_output_y)
        max_output_i, min_output_j = world_to_pixel(geotransform, max_output_x, min_output_y)

        if min_ouput_i < 0:
            min_ouput_i = 0
        if max_output_j < 0:
            max_output_j = 0
        if max_output_i > source_cols:
            max_output_i = source_cols
        if min_output_j > source_rows:
            min_output_j = source_rows

        output_cols = int(max_output_i - min_ouput_i)
        output_rows = int(min_output_j - max_output_j)

        clip = source_array[max_output_j:min_output_j, min_ouput_i:max_output_i]

        output_geotransform = list(geotransform)
        output_geotransform[0] = min_output_x
        output_geotransform[3] = max_output_y

        polygons_pixel = []
        for polygon in polygons:
            polygon_pixel = []
            for point in polygon:
                polygon_pixel.append(world_to_pixel(output_geotransform, point[0], point[1]))
            polygons_pixel.append(polygon_pixel)

        polygon_raster = Image.new("L", (output_cols, output_rows), 1)
        rasterize = ImageDraw.Draw(polygon_raster)

        for polygon in polygons_pixel:
            rasterize.polygon(polygon, 0)

        mask = image_to_array(polygon_raster)

        clip = gdalnumeric.choose(mask, (clip, 0)).astype(gdalnumeric.uint16)

        driver = gdal.GetDriverByName('GTiff')
        output_image = driver.Create(output_image_path, output_cols, output_rows, 1, gdal.GDT_UInt16)
        output_image.GetRasterBand(1).WriteArray(clip)

        proj = source_image.GetProjection()
        output_image.SetGeoTransform(output_geotransform)
        output_image.SetProjection(proj)
        output_image.FlushCache()
        output_image = None

    else:
        print('unknown file format')
Beispiel #27
0
def ogr_rfc41_4():

    ds = ogr.GetDriverByName('memory').CreateDataSource('')
    if ds.TestCapability(ogr.ODsCCreateGeomFieldAfterCreateLayer) == 0:
        gdaltest.post_reason('fail')
        return 'fail'
    sr = osr.SpatialReference()
    lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint, srs=sr)
    if lyr.TestCapability(ogr.OLCCreateGeomField) == 0:
        gdaltest.post_reason('fail')
        return 'fail'
    if lyr.GetSpatialRef().IsSame(sr) == 0:
        gdaltest.post_reason('fail')
        return 'fail'
    if lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef().IsSame(sr) == 0:
        gdaltest.post_reason('fail')
        return 'fail'
    lyr.GetLayerDefn().GetGeomFieldDefn(0).SetName('a_name')
    feat = ogr.Feature(lyr.GetLayerDefn())
    feat.SetGeometry(ogr.CreateGeometryFromWkt('POINT (1 2)'))
    lyr.CreateFeature(feat)
    lyr.ResetReading()
    feat = lyr.GetNextFeature()
    geom = feat.GetGeometryRef()
    if geom.GetSpatialReference().IsSame(sr) == 0:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    lyr.CreateGeomField(ogr.GeomFieldDefn('another_geom_field',
                                          ogr.wkbPolygon))
    lyr.ResetReading()
    feat = lyr.GetNextFeature()
    feat.SetGeomField(
        1,
        ogr.CreateGeometryFromWkt('POLYGON ((10 10,10 11,11 11,11 10,10 10))'))
    lyr.SetFeature(feat)
    lyr.ResetReading()
    feat = lyr.GetNextFeature()
    geom = feat.GetGeomFieldRef(0)
    if geom.ExportToWkt() != 'POINT (1 2)':
        gdaltest.post_reason('fail')
        return 'fail'
    geom = feat.GetGeomFieldRef('another_geom_field')
    if geom.ExportToWkt() != 'POLYGON ((10 10,10 11,11 11,11 10,10 10))':
        gdaltest.post_reason('fail')
        return 'fail'

    # Test GetExtent()
    got_extent = lyr.GetExtent(geom_field=1)
    if got_extent != (10.0, 11.0, 10.0, 11.0):
        gdaltest.post_reason('fail')
        return 'fail'
    # Test invalid geometry field index
    gdal.ErrorReset()
    gdal.PushErrorHandler('CPLQuietErrorHandler')
    got_extent = lyr.GetExtent(geom_field=2)
    gdal.PopErrorHandler()
    if gdal.GetLastErrorMsg() == '':
        gdaltest.post_reason('fail')
        return 'fail'

    # Test SetSpatialFilter()
    lyr.SetSpatialFilter(
        1,
        ogr.CreateGeometryFromWkt(
            'POLYGON ((-10 10,-10 11,-11 11,-11 10,-10 10))'))
    lyr.ResetReading()
    feat = lyr.GetNextFeature()
    if feat is not None:
        gdaltest.post_reason('fail')
        return 'fail'
    lyr.SetSpatialFilter(
        1,
        ogr.CreateGeometryFromWkt('POLYGON ((10 10,10 11,11 11,11 10,10 10))'))
    lyr.ResetReading()
    feat = lyr.GetNextFeature()
    if feat is None:
        gdaltest.post_reason('fail')
        return 'fail'
    lyr.SetSpatialFilterRect(1, 10, 10, 11, 11)
    lyr.ResetReading()
    feat = lyr.GetNextFeature()
    if feat is None:
        gdaltest.post_reason('fail')
        return 'fail'
    # Test invalid spatial filter index
    gdal.ErrorReset()
    gdal.PushErrorHandler('CPLQuietErrorHandler')
    lyr.SetSpatialFilterRect(2, 0, 0, 0, 0)
    gdal.PopErrorHandler()
    if gdal.GetLastErrorMsg() == '':
        gdaltest.post_reason('fail')
        return 'fail'

    lyr.SetSpatialFilter(None)
    another_lyr = ds.CopyLayer(lyr, 'dup_test')
    dup_feat = another_lyr.GetNextFeature()
    geom = dup_feat.GetGeomFieldRef('a_name')
    if geom.ExportToWkt() != 'POINT (1 2)':
        gdaltest.post_reason('fail')
        return 'fail'
    geom = dup_feat.GetGeomFieldRef('another_geom_field')
    if geom.ExportToWkt() != 'POLYGON ((10 10,10 11,11 11,11 10,10 10))':
        gdaltest.post_reason('fail')
        return 'fail'

    return 'success'
Beispiel #28
0
    def processAlgorithm(self, feedback):
        rasterPath = self.getParameterValue(self.INPUT_DEM)
        layer = dataobjects.getObjectFromUri(
            self.getParameterValue(self.BOUNDARY_LAYER))
        step = self.getParameterValue(self.STEP)
        percentage = self.getParameterValue(self.USE_PERCENTAGE)

        outputPath = self.getOutputValue(self.OUTPUT_DIRECTORY)

        rasterDS = gdal.Open(rasterPath, gdal.GA_ReadOnly)
        geoTransform = rasterDS.GetGeoTransform()
        rasterBand = rasterDS.GetRasterBand(1)
        noData = rasterBand.GetNoDataValue()

        cellXSize = abs(geoTransform[1])
        cellYSize = abs(geoTransform[5])
        rasterXSize = rasterDS.RasterXSize
        rasterYSize = rasterDS.RasterYSize

        rasterBBox = QgsRectangle(geoTransform[0],
                                  geoTransform[3] - cellYSize * rasterYSize,
                                  geoTransform[0] + cellXSize * rasterXSize,
                                  geoTransform[3])
        rasterGeom = QgsGeometry.fromRect(rasterBBox)

        crs = osr.SpatialReference()
        crs.ImportFromProj4(str(layer.crs().toProj4()))

        memVectorDriver = ogr.GetDriverByName('Memory')
        memRasterDriver = gdal.GetDriverByName('MEM')

        features = vector.features(layer)
        total = 100.0 / len(features)

        for current, f in enumerate(features):
            geom = f.geometry()
            intersectedGeom = rasterGeom.intersection(geom)

            if intersectedGeom.isEmpty():
                feedback.pushInfo(
                    self.tr('Feature %d does not intersect raster or '
                            'entirely located in NODATA area' % f.id()))
                continue

            fName = os.path.join(
                outputPath, 'hystogram_%s_%s.csv' % (layer.name(), f.id()))

            ogrGeom = ogr.CreateGeometryFromWkt(intersectedGeom.exportToWkt())
            bbox = intersectedGeom.boundingBox()
            xMin = bbox.xMinimum()
            xMax = bbox.xMaximum()
            yMin = bbox.yMinimum()
            yMax = bbox.yMaximum()

            (startColumn,
             startRow) = raster.mapToPixel(xMin, yMax, geoTransform)
            (endColumn, endRow) = raster.mapToPixel(xMax, yMin, geoTransform)

            width = endColumn - startColumn
            height = endRow - startRow

            srcOffset = (startColumn, startRow, width, height)
            srcArray = rasterBand.ReadAsArray(*srcOffset)

            if srcOffset[2] == 0 or srcOffset[3] == 0:
                feedback.pushInfo(
                    self.tr('Feature %d is smaller than raster '
                            'cell size' % f.id()))
                continue

            newGeoTransform = (geoTransform[0] +
                               srcOffset[0] * geoTransform[1], geoTransform[1],
                               0.0, geoTransform[3] +
                               srcOffset[1] * geoTransform[5], 0.0,
                               geoTransform[5])

            memVDS = memVectorDriver.CreateDataSource('out')
            memLayer = memVDS.CreateLayer('poly', crs, ogr.wkbPolygon)

            ft = ogr.Feature(memLayer.GetLayerDefn())
            ft.SetGeometry(ogrGeom)
            memLayer.CreateFeature(ft)
            ft.Destroy()

            rasterizedDS = memRasterDriver.Create('', srcOffset[2],
                                                  srcOffset[3], 1,
                                                  gdal.GDT_Byte)
            rasterizedDS.SetGeoTransform(newGeoTransform)
            gdal.RasterizeLayer(rasterizedDS, [1], memLayer, burn_values=[1])
            rasterizedArray = rasterizedDS.ReadAsArray()

            srcArray = numpy.nan_to_num(srcArray)
            masked = numpy.ma.MaskedArray(
                srcArray,
                mask=numpy.logical_or(srcArray == noData,
                                      numpy.logical_not(rasterizedArray)))

            self.calculateHypsometry(f.id(), fName, feedback, masked,
                                     cellXSize, cellYSize, percentage, step)

            memVDS = None
            rasterizedDS = None
            feedback.setProgress(int(current * total))

        rasterDS = None
Beispiel #29
0
def ogr_rfc41_6():

    ds = ogr.GetDriverByName('memory').CreateDataSource('')
    sr = osr.SpatialReference()
    lyr = ds.CreateLayer('poly', geom_type=ogr.wkbPolygon, srs=sr)
    lyr.GetLayerDefn().GetGeomFieldDefn(0).SetName('geomfield')
    lyr.CreateField(ogr.FieldDefn('intfield', ogr.OFTInteger))
    lyr.CreateField(ogr.FieldDefn('wkt', ogr.OFTString))
    feat = ogr.Feature(lyr.GetLayerDefn())
    feat.SetField('intfield', 1)
    feat.SetField('wkt', 'POINT (0 0)')
    feat.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POLYGON EMPTY'))
    lyr.CreateFeature(feat)
    feat = ogr.Feature(lyr.GetLayerDefn())
    lyr.CreateFeature(feat)
    feat = None

    # Test implicit geometry column (since poly has one single geometry column)
    # then explicit geometry column
    for sql in [
            'SELECT intfield FROM poly', 'SELECT * FROM poly',
            'SELECT intfield, geomfield FROM poly',
            'SELECT geomfield, intfield FROM poly'
    ]:
        sql_lyr = ds.ExecuteSQL(sql)
        if sql_lyr.GetLayerDefn().GetGeomFieldDefn(
                0).GetType() != ogr.wkbPolygon:
            gdaltest.post_reason('fail')
            return 'fail'
        if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is None:
            gdaltest.post_reason('fail')
            return 'fail'
        feat = sql_lyr.GetNextFeature()
        if feat.GetField('intfield') != 1:
            gdaltest.post_reason('fail')
            return 'fail'
        if feat.GetGeomFieldRef('geomfield') is None:
            gdaltest.post_reason('fail')
            return 'fail'
        feat = sql_lyr.GetNextFeature()
        if feat.GetGeomFieldRef('geomfield') is not None:
            gdaltest.post_reason('fail')
            return 'fail'
        feat = None
        ds.ReleaseResultSet(sql_lyr)

    # Test CAST(geometry_field AS GEOMETRY)
    sql_lyr = ds.ExecuteSQL(
        'SELECT CAST(geomfield AS GEOMETRY) AS mygeom FROM poly WHERE CAST(geomfield AS GEOMETRY) IS NOT NULL'
    )
    if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbUnknown:
        gdaltest.post_reason('fail')
        return 'fail'
    if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is not None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = sql_lyr.GetNextFeature()
    if feat.GetGeomFieldRef('mygeom') is None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test CAST(xxx AS GEOMETRY(POLYGON))
    sql_lyr = ds.ExecuteSQL(
        'SELECT CAST(geomfield AS GEOMETRY(POLYGON)) AS mygeom FROM poly WHERE CAST(geomfield AS GEOMETRY(POLYGON)) IS NOT NULL'
    )
    if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbPolygon:
        gdaltest.post_reason('fail')
        return 'fail'
    if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is not None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = sql_lyr.GetNextFeature()
    if feat.GetGeomFieldRef('mygeom') is None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test CAST(xxx AS GEOMETRY(POLYGON,4326))
    sql_lyr = ds.ExecuteSQL(
        'SELECT CAST(geomfield AS GEOMETRY(POLYGON,4326)) AS mygeom FROM poly WHERE CAST(geomfield AS GEOMETRY(POLYGON,4326)) IS NOT NULL'
    )
    if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbPolygon:
        gdaltest.post_reason('fail')
        return 'fail'
    if sql_lyr.GetLayerDefn().GetGeomFieldDefn(
            0).GetSpatialRef().ExportToWkt().find('4326') < 0:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = sql_lyr.GetNextFeature()
    if feat.GetGeomFieldRef('mygeom') is None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test CAST(a_multipolygon AS GEOMETRY(POLYGON))
    sql_lyr = ds.ExecuteSQL(
        "SELECT CAST('MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)))' AS GEOMETRY(POLYGON)) AS mygeom FROM poly"
    )
    feat = sql_lyr.GetNextFeature()
    if feat.GetGeomFieldRef(
            'mygeom').ExportToWkt() != 'POLYGON ((0 0,0 1,1 1,1 0,0 0))':
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test CAST(a_polygon AS GEOMETRY(MULTIPOLYGON))
    sql_lyr = ds.ExecuteSQL(
        "SELECT CAST('POLYGON ((0 0,0 1,1 1,1 0,0 0))' AS GEOMETRY(MULTIPOLYGON)) AS mygeom FROM poly"
    )
    feat = sql_lyr.GetNextFeature()
    if feat.GetGeomFieldRef('mygeom').ExportToWkt(
    ) != 'MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)))':
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test CAST(a_multilinestring AS GEOMETRY(LINESTRING))
    sql_lyr = ds.ExecuteSQL(
        "SELECT CAST('MULTILINESTRING ((0 0,0 1,1 1,1 0,0 0))' AS GEOMETRY(LINESTRING)) AS mygeom FROM poly"
    )
    feat = sql_lyr.GetNextFeature()
    if feat.GetGeomFieldRef(
            'mygeom').ExportToWkt() != 'LINESTRING (0 0,0 1,1 1,1 0,0 0)':
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test CAST(a_linestring AS GEOMETRY(MULTILINESTRING))
    sql_lyr = ds.ExecuteSQL(
        "SELECT CAST('LINESTRING (0 0,0 1,1 1,1 0,0 0)' AS GEOMETRY(MULTILINESTRING)) AS mygeom FROM poly"
    )
    feat = sql_lyr.GetNextFeature()
    if feat.GetGeomFieldRef('mygeom').ExportToWkt(
    ) != 'MULTILINESTRING ((0 0,0 1,1 1,1 0,0 0))':
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test expression with cast CHARACTER <--> GEOMETRY
    sql_lyr = ds.ExecuteSQL(
        'SELECT CAST(CAST(geomfield AS CHARACTER) AS GEOMETRY) AS mygeom, intfield FROM poly'
    )
    if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbUnknown:
        gdaltest.post_reason('fail')
        return 'fail'
    if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetSpatialRef() is not None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = sql_lyr.GetNextFeature()
    if feat.GetField('intfield') != 1:
        gdaltest.post_reason('fail')
        return 'fail'
    if feat.GetGeomFieldRef('mygeom') is None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test CAST(NULL AS GEOMETRY)
    sql_lyr = ds.ExecuteSQL('SELECT CAST(NULL AS GEOMETRY) FROM poly')
    if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbUnknown:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = sql_lyr.GetNextFeature()
    if feat.GetGeomFieldRef('') is not None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test CAST(stringfield AS GEOMETRY)
    sql_lyr = ds.ExecuteSQL('SELECT CAST(wkt AS GEOMETRY) FROM poly')
    if sql_lyr.GetLayerDefn().GetGeomFieldDefn(0).GetType() != ogr.wkbUnknown:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = sql_lyr.GetNextFeature()
    if feat.GetGeomFieldRef('wkt').ExportToWkt() != 'POINT (0 0)':
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test COUNT(geometry)
    sql_lyr = ds.ExecuteSQL('SELECT COUNT(geomfield) FROM poly')
    feat = sql_lyr.GetNextFeature()
    if feat is None:
        gdaltest.post_reason('fail')
        return 'fail'
    if feat.GetField(0) != 1:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    wrong_sql_list = [
        ('SELECT DISTINCT geomfield FROM poly',
         'SELECT DISTINCT on a geometry not supported'),
        ('SELECT COUNT(DISTINCT geomfield) FROM poly',
         'SELECT COUNT DISTINCT on a geometry not supported'),
        ('SELECT MAX(geomfield) FROM poly',
         'Use of field function MAX() on geometry field'),
        ('SELECT CAST(5 AS GEOMETRY) FROM poly',
         'Cannot cast integer to geometry'),
        ('SELECT CAST(geomfield AS integer) FROM poly',
         'Cannot cast geometry to integer'),
        ('SELECT CAST(geomfield AS GEOMETRY(2)) FROM poly',
         'First argument of CAST operator should be an geometry type identifier'
         ),
        ('SELECT CAST(geomfield AS GEOMETRY(UNSUPPORTED_TYPE)) FROM poly',
         'SQL Expression Parsing Error: syntax error'),
        ('SELECT CAST(geomfield AS GEOMETRY(UNSUPPORTED_TYPE,5)) FROM poly',
         'SQL Expression Parsing Error: syntax error'),
    ]

    for (sql, error_msg) in wrong_sql_list:
        gdal.ErrorReset()
        gdal.PushErrorHandler('CPLQuietErrorHandler')
        sql_lyr = ds.ExecuteSQL(sql)
        gdal.PopErrorHandler()
        if gdal.GetLastErrorMsg().find(error_msg) != 0:
            gdaltest.post_reason('fail')
            print('For %s, expected error %s, got %s' %
                  (sql, error_msg, gdal.GetLastErrorMsg()))
            return 'fail'
        if sql_lyr is not None:
            gdaltest.post_reason('fail')
            return 'fail'

    # Test invalid expressions with geometry
    for sql in [
            "SELECT geomfield + 'a' FROM poly",
            "SELECT geomfield * 'a' FROM poly",
            "SELECT geomfield + 'a' FROM poly",
            "SELECT geomfield - 'a' FROM poly",
            "SELECT geomfield % 'a' FROM poly",
            "SELECT CONCAT(geomfield, 'a') FROM poly",
            "SELECT SUBSTR(geomfield, 0, 1) FROM poly",
            "SELECT * FROM poly WHERE geomfield = CAST('POINT EMPTY' AS GEOMETRY)",
            "SELECT * FROM poly WHERE geomfield LIKE 'a'",
            "SELECT * FROM poly WHERE geomfield IN( 'a' )"
    ]:
        gdal.ErrorReset()
        gdal.PushErrorHandler('CPLQuietErrorHandler')
        sql_lyr = ds.ExecuteSQL(sql)
        gdal.PopErrorHandler()
        if gdal.GetLastErrorMsg().find(
                'Cannot use geometry field in this operation') != 0:
            gdaltest.post_reason('fail')
            print(gdal.GetLastErrorMsg())
            return 'fail'
        if sql_lyr is not None:
            gdaltest.post_reason('fail')
            return 'fail'

    # Test expression with geometry in WHERE
    sql_lyr = ds.ExecuteSQL('SELECT * FROM poly WHERE geomfield IS NOT NULL')
    feat = sql_lyr.GetNextFeature()
    if feat.GetField('intfield') != 1:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = sql_lyr.GetNextFeature()
    if feat is not None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    sql_lyr = ds.ExecuteSQL('SELECT * FROM poly WHERE geomfield IS NULL')
    feat = sql_lyr.GetNextFeature()
    if feat.IsFieldSet(0):
        gdaltest.post_reason('fail')
        return 'fail'
    feat = sql_lyr.GetNextFeature()
    if feat is not None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    sql_lyr = ds.ExecuteSQL(
        "SELECT * FROM poly WHERE CAST(geomfield AS CHARACTER) = 'POLYGON EMPTY'"
    )
    feat = sql_lyr.GetNextFeature()
    if feat is None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = sql_lyr.GetNextFeature()
    if feat is not None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    sql_lyr = ds.ExecuteSQL(
        'SELECT count(*) FROM poly WHERE geomfield IS NULL')
    feat = sql_lyr.GetNextFeature()
    if feat.GetField(0) != 1:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    sql_lyr = ds.ExecuteSQL(
        'SELECT count(*) FROM poly WHERE geomfield IS NOT NULL')
    feat = sql_lyr.GetNextFeature()
    if feat.GetField(0) != 1:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test spatial filter
    feat = lyr.GetFeature(0)
    feat.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(1 2)'))
    lyr.SetFeature(feat)
    feat = None

    lyr.DeleteFeature(1)

    sql_lyr = ds.ExecuteSQL("SELECT * FROM poly")
    sql_lyr.SetSpatialFilterRect(0, 0, 0, 0)
    feat = sql_lyr.GetNextFeature()
    if feat is not None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None

    sql_lyr.SetSpatialFilterRect(0, 1, 2, 1, 2)
    feat = sql_lyr.GetNextFeature()
    if feat is None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None

    # Test invalid spatial filter index
    gdal.ErrorReset()
    gdal.PushErrorHandler('CPLQuietErrorHandler')
    sql_lyr.SetSpatialFilterRect(2, 0, 0, 0, 0)
    gdal.PopErrorHandler()
    if gdal.GetLastErrorMsg() == '':
        gdaltest.post_reason('fail')
        return 'fail'

    # Test invalid geometry field index
    gdal.ErrorReset()
    gdal.PushErrorHandler('CPLQuietErrorHandler')
    got_extent = sql_lyr.GetExtent(geom_field=2)
    gdal.PopErrorHandler()
    if gdal.GetLastErrorMsg() == '':
        gdaltest.post_reason('fail')
        return 'fail'

    ds.ReleaseResultSet(sql_lyr)

    # Test querying several geometry fields
    sql_lyr = ds.ExecuteSQL(
        'SELECT geomfield as geom1, geomfield as geom2 FROM poly')
    feat = sql_lyr.GetNextFeature()
    if feat is None:
        gdaltest.post_reason('fail')
        return 'fail'
    if feat.GetGeomFieldRef('geom1') is None:
        gdaltest.post_reason('fail')
        return 'fail'
    if feat.GetGeomFieldRef('geom2') is None:
        gdaltest.post_reason('fail')
        return 'fail'
    feat = None
    ds.ReleaseResultSet(sql_lyr)

    # Test querying a layer with several geometry fields
    lyr.CreateGeomField(ogr.GeomFieldDefn('secondarygeom', ogr.wkbPoint))
    lyr.ResetReading()
    feat = lyr.GetNextFeature()
    feat.SetGeomField('secondarygeom',
                      ogr.CreateGeometryFromWkt('POINT (10 100)'))
    lyr.SetFeature(feat)
    feat = None

    for sql in [
            'SELECT * FROM poly', 'SELECT geomfield, secondarygeom FROM poly',
            'SELECT secondarygeom, geomfield FROM poly'
    ]:
        sql_lyr = ds.ExecuteSQL(sql)
        feat = sql_lyr.GetNextFeature()
        if feat.GetGeomFieldRef('geomfield').ExportToWkt() != 'POINT (1 2)':
            gdaltest.post_reason('fail')
            return 'fail'
        if feat.GetGeomFieldRef(
                'secondarygeom').ExportToWkt() != 'POINT (10 100)':
            gdaltest.post_reason('fail')
            return 'fail'
        feat = None
        ds.ReleaseResultSet(sql_lyr)

    # Check that we don't get an implicit geometry field
    sql_lyr = ds.ExecuteSQL('SELECT intfield FROM poly')
    if sql_lyr.GetLayerDefn().GetGeomFieldCount() != 0:
        gdaltest.post_reason('fail')
        return 'fail'
    ds.ReleaseResultSet(sql_lyr)

    # Check GetExtent() and SetSpatialFilter()
    sql_lyr = ds.ExecuteSQL('SELECT * FROM poly')
    if sql_lyr.GetExtent(geom_field=0) != (1.0, 1.0, 2.0, 2.0):
        gdaltest.post_reason('fail')
        return 'fail'
    if sql_lyr.GetExtent(geom_field=1) != (10.0, 10.0, 100.0, 100.0):
        gdaltest.post_reason('fail')
        return 'fail'
    sql_lyr.SetSpatialFilterRect(0, 0.5, 1.5, 1.5, 2.5)
    if sql_lyr.GetFeatureCount() != 1:
        gdaltest.post_reason('fail')
        return 'fail'
    sql_lyr.SetSpatialFilterRect(0, 0, 0, 0.5, 0.5)
    if sql_lyr.GetFeatureCount() != 0:
        gdaltest.post_reason('fail')
        return 'fail'
    sql_lyr.SetSpatialFilterRect(1, 9, 99, 11, 101)
    if sql_lyr.GetFeatureCount() != 1:
        gdaltest.post_reason('fail')
        return 'fail'
    sql_lyr.SetSpatialFilterRect(1, 0, 0, 0.5, 0.5)
    if sql_lyr.GetFeatureCount() != 0:
        gdaltest.post_reason('fail')
        return 'fail'
    ds.ReleaseResultSet(sql_lyr)

    ds = None

    return 'success'
Beispiel #30
0
    def testTransaction(self):

        tmpfile = os.path.join(self.basetestpath, 'testTransaction.gpkg')
        ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile)
        lyr = ds.CreateLayer('lyr1', geom_type=ogr.wkbPoint)
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(0 1)'))
        lyr.CreateFeature(f)
        lyr = ds.CreateLayer('lyr2', geom_type=ogr.wkbPoint)
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(2 3)'))
        lyr.CreateFeature(f)
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(4 5)'))
        lyr.CreateFeature(f)
        ds = None

        vl1 = QgsVectorLayer(u'{}'.format(tmpfile) + "|layername=" + "lyr1",
                             'test', u'ogr')
        self.assertTrue(vl1.isValid())
        vl2 = QgsVectorLayer(u'{}'.format(tmpfile) + "|layername=" + "lyr2",
                             'test', u'ogr')
        self.assertTrue(vl2.isValid())

        # prepare a project with transactions enabled
        p = QgsProject()
        p.setAutoTransaction(True)
        p.addMapLayers([vl1, vl2])

        self.assertTrue(vl1.startEditing())
        self.assertIsNotNone(vl1.dataProvider().transaction())
        self.assertTrue(vl1.deleteFeature(1))

        # An iterator opened on the layer should see the feature deleted
        self.assertEqual(
            len([f for f in vl1.getFeatures(QgsFeatureRequest())]), 0)

        # But not if opened from another connection
        vl1_external = QgsVectorLayer(
            u'{}'.format(tmpfile) + "|layername=" + "lyr1", 'test', u'ogr')
        self.assertTrue(vl1_external.isValid())
        self.assertEqual(
            len([f for f in vl1_external.getFeatures(QgsFeatureRequest())]), 1)
        del vl1_external

        self.assertTrue(vl1.commitChanges())

        # Should still get zero features on vl1
        self.assertEqual(
            len([f for f in vl1.getFeatures(QgsFeatureRequest())]), 0)
        self.assertEqual(
            len([f for f in vl2.getFeatures(QgsFeatureRequest())]), 2)

        # Test undo/redo
        self.assertTrue(vl2.startEditing())
        self.assertIsNotNone(vl2.dataProvider().transaction())
        self.assertTrue(vl2.editBuffer().deleteFeature(1))
        self.assertEqual(
            len([f for f in vl2.getFeatures(QgsFeatureRequest())]), 1)
        self.assertTrue(vl2.editBuffer().deleteFeature(2))
        self.assertEqual(
            len([f for f in vl2.getFeatures(QgsFeatureRequest())]), 0)
        vl2.undoStack().undo()
        self.assertEqual(
            len([f for f in vl2.getFeatures(QgsFeatureRequest())]), 1)
        vl2.undoStack().undo()
        self.assertEqual(
            len([f for f in vl2.getFeatures(QgsFeatureRequest())]), 2)
        vl2.undoStack().redo()
        self.assertEqual(
            len([f for f in vl2.getFeatures(QgsFeatureRequest())]), 1)
        self.assertTrue(vl2.commitChanges())

        self.assertEqual(
            len([f for f in vl2.getFeatures(QgsFeatureRequest())]), 1)
        del vl1
        del vl2

        vl2_external = QgsVectorLayer(
            u'{}'.format(tmpfile) + "|layername=" + "lyr2", 'test', u'ogr')
        self.assertTrue(vl2_external.isValid())
        self.assertEqual(
            len([f for f in vl2_external.getFeatures(QgsFeatureRequest())]), 1)
        del vl2_external