Ejemplo n.º 1
0
def osr_basic_6():

    # Without version
    wkt_1 = osr.GetUserInputAsWKT('urn:x-ogc:def:crs:EPSG::4326')
    if wkt_1.find('GEOGCS["WGS 84",DATUM["WGS_1984"') == -1 or wkt_1.find(
            'AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') == -1:
        print(wkt_1)
        gdaltest.post_reason('EPSG:4326 urn lookup not as expected.')
        return 'fail'

    # With a version
    wkt_2 = osr.GetUserInputAsWKT('urn:x-ogc:def:crs:EPSG:6.6:4326')
    if wkt_2.find('GEOGCS["WGS 84",DATUM["WGS_1984"') == -1 or wkt_2.find(
            'AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') == -1:
        print(wkt_1)
        print(wkt_2)
        gdaltest.post_reason('EPSG:4326 urn lookup not as expected.')
        return 'fail'

    # Without version, but with no repeated :. Probably illegal from my understanding
    # of http://www.opengeospatial.org/ogcUrnPolicy, but found quite often in the wild
    # especially in content returned by GeoServer
    wkt_2 = osr.GetUserInputAsWKT('urn:x-ogc:def:crs:EPSG:4326')
    if wkt_2.find('GEOGCS["WGS 84",DATUM["WGS_1984"') == -1 or wkt_2.find(
            'AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') == -1:
        print(wkt_1)
        print(wkt_2)
        gdaltest.post_reason('EPSG:4326 urn lookup not as expected.')
        return 'fail'

    return 'success'
Ejemplo n.º 2
0
def sreq(*items, verbose_on=None):
    """SR items are all equal"""
    v = tuple(map(int, gdal.__version__.split('.')))
    for a, b in itertools.combinations(items, 2):
        a = osr.SpatialReference(osr.GetUserInputAsWKT(a))
        if v < (3, ):
            a.StripCTParms()
        a = a.ExportToProj4()
        a = osr.SpatialReference(osr.GetUserInputAsWKT(a))
        if v < (3, ):
            a.StripCTParms()

        b = osr.SpatialReference(osr.GetUserInputAsWKT(b))
        if v < (3, ):
            b.StripCTParms()
        b = b.ExportToProj4()
        b = osr.SpatialReference(osr.GetUserInputAsWKT(b))
        if v < (3, ):
            b.StripCTParms()

        res = bool(a.IsSame(b))
        if res is verbose_on:
            print('')
            print(a.ExportToPrettyWkt())
            print('---------- vs ----------')
            print(b.ExportToPrettyWkt())
            print('')

        if not res:
            return False
    return True
Ejemplo n.º 3
0
 def test_get_projection(self):
     projection_rd = str("EPSG:28992")
     projection_wgs = str("EPSG:4326")
     rd = osr.SpatialReference(osr.GetUserInputAsWKT(projection_rd))
     self.assertEqual(utils.get_projection(rd), projection_rd)
     wgs = osr.SpatialReference(osr.GetUserInputAsWKT(projection_wgs))
     self.assertEqual(utils.get_projection(wgs), projection_wgs)
Ejemplo n.º 4
0
def transformgeoloc_1():

    # Setup 2x2 geolocation arrays in a memory dataset with lat/long values.

    drv = gdal.GetDriverByName('MEM')
    geoloc_ds = drv.Create('geoloc_1', 2, 2, 3, gdal.GDT_Float64)

    lon_array = gdalnumeric.asarray([[-117.0, -116.0], [-116.5, -115.5]])
    lat_array = gdalnumeric.asarray([[45.0, 45.5], [44.0, 44.5]])

    geoloc_ds.GetRasterBand(1).WriteArray(lon_array)
    geoloc_ds.GetRasterBand(2).WriteArray(lat_array)
    # Z left as default zero.

    # Create a wgs84 to utm transformer.

    wgs84_wkt = osr.GetUserInputAsWKT('WGS84')
    utm_wkt = osr.GetUserInputAsWKT('+proj=utm +zone=11 +datum=WGS84')

    ll_utm_transformer = gdal.Transformer(
        None, None, ['SRC_SRS=' + wgs84_wkt, 'DST_SRS=' + utm_wkt])

    # transform the geoloc dataset in place.
    status = ll_utm_transformer.TransformGeolocations(
        geoloc_ds.GetRasterBand(1), geoloc_ds.GetRasterBand(2),
        geoloc_ds.GetRasterBand(3))

    print status

    print geoloc_ds.ReadAsArray()

    return 'success'
Ejemplo n.º 5
0
def osr_basic_5():

    wkt_1 = osr.GetUserInputAsWKT('urn:ogc:def:crs:OGC:1.3:CRS84')
    wkt_2 = osr.GetUserInputAsWKT('WGS84')
    if wkt_1 != wkt_2:
        gdaltest.post_reason('CRS84 lookup not as expected.')
        return 'fail'

    return 'success'
Ejemplo n.º 6
0
def osr_basic_12():

    wkt_1 = osr.GetUserInputAsWKT('CRS:84')
    wkt_2 = osr.GetUserInputAsWKT('WGS84')
    if wkt_1 != wkt_2:
        gdaltest.post_reason('CRS:84 lookup not as expected.')
        return 'fail'

    return 'success'
Ejemplo n.º 7
0
def osr_basic_17():

    wkt_1 = osr.GetUserInputAsWKT('urn:ogc:def:crs:EPSG::4326')
    wkt_2 = osr.GetUserInputAsWKT('http://www.opengis.net/def/crs/EPSG/0/4326')
    if wkt_1 != wkt_2:
        gdaltest.post_reason('CRS URL parsing not as expected.')
        return 'fail'

    return 'success'
Ejemplo n.º 8
0
def test_osr_basic_18():

    # This is a dummy one, but who cares
    wkt = osr.GetUserInputAsWKT(
        'http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/def/crs/EPSG/0/4326&2=http://www.opengis.net/def/crs/EPSG/0/4326'
    )
    assert wkt.startswith('COMPD_CS'), 'CRS URL parsing not as expected.'
Ejemplo n.º 9
0
 def _convert_footprint(self, fp, sr):
     sr_tmp = osr.GetUserInputAsWKT(sr)
     sr_tmp = osr.SpatialReference(sr_tmp)
     _, to_origin = self._get_transforms(sr_tmp, fp, 'work')
     if to_origin:
         fp = fp.move(*to_origin([fp.tl, fp.tr, fp.br]))
     return fp
Ejemplo n.º 10
0
    def awrap_numpy_raster(self,
                           fp,
                           array,
                           band_schema=None,
                           sr=None,
                           mode='w'):
        """Register a numpy array as a raster anonymously in this DataSource.

        See DataSource.wrap_numpy_raster
        """
        # Parameter checking ***************************************************
        if not isinstance(fp, Footprint):  # pragma: no cover
            raise TypeError('`fp` should be a Footprint')
        array = np.asarray(array)
        if array.shape[:2] != tuple(fp.shape):  # pragma: no cover
            raise ValueError('Incompatible shape between `array` and `fp`')
        if array.ndim not in [2, 3]:  # pragma: no cover
            raise ValueError('Array should have 2 or 3 dimensions')
        band_count = 1 if array.ndim == 2 else array.shape[-1]
        band_schema = _tools.sanitize_band_schema(band_schema, band_count)
        if sr is not None:
            sr = osr.GetUserInputAsWKT(sr)
        _ = conv.of_of_mode(mode)

        if sr is not None:
            fp = self._back.convert_footprint(fp, sr)

        # Construction *********************************************************
        prox = NumpyRaster(self, fp, array, band_schema, sr, mode)

        # DataSource Registering ***********************************************
        self._register([], prox)
        return prox
Ejemplo n.º 11
0
    def __init__(self, path, layer, feature, **kwargs):
        """ Prepare a lot. """
        attribute = kwargs.pop('attribute')
        self.server = kwargs.pop('server')
        self.operation = operations[kwargs.pop('operation')](**kwargs)

        self.projection = kwargs.pop('projection')
        self.cellsize = kwargs.pop('cellsize')

        self.wkt = osr.GetUserInputAsWKT(str(self.projection))
        self.sr = osr.SpatialReference(self.wkt)
        self.paths = self._make_paths(path, layer, feature, attribute)
        self.rpath = self.paths.pop('rpath')
        self.geometry = self._prepare_geometry(feature)
        self.datasets = self._get_or_create_datasets()

        # Get resume value
        try:
            with open(self.rpath) as resume_file:
                self.resume = int(resume_file.read())
        except IOError:
            self.resume = 0

        self.index = self._create_index()

        if self.index:
            if self.resume > 0:
                print('Resuming from tile {}.'.format(self.resume))
        else:
            print('Already complete.')
            raise CompleteError()
Ejemplo n.º 12
0
def create_targets(source):
    """ Return a generator with created targets. """
    polygon = get_polygon(source).Buffer(-1)
    datasource = ogr.Open(index_path)
    layer = datasource[0]
    layer.SetSpatialFilter(polygon)
    wkt = osr.GetUserInputAsWKT(str('epsg:28992'))
    no_data_value = source.GetRasterBand(1).GetNoDataValue()
    for feature in layer:
        target = GDAL_MEM_DRIVER.Create('', 2000, 2500, 1, gdal.GDT_Float32)
        target.SetGeoTransform(GEO_TRANSFORM.shifted(feature.geometry()))
        target.SetProjection(osr.GetUserInputAsWKT(str('epsg:28992')))
        target.GetRasterBand(1).SetNoDataValue(no_data_value)
        target.GetRasterBand(1).Fill(no_data_value)
        gdal.ReprojectImage(source, target, wkt, wkt, 0, 0.0, 0.125)
        yield feature[str('BLADNR')][1:], target
Ejemplo n.º 13
0
def create_dataset(array,
                   geo_transform=None,
                   projection=None,
                   no_data_value=None):
    """
    Create and return a gdal dataset.

    :param array: A numpy array.
    :param geo_transform: 6-tuple of floats
    :param projection: wkt projection string
    :param no_data_value: integer or float

    This is the fastest way to get a gdal dataset from a numpy array, but
    keep a reference to the array around, or a segfault will occur. Also,
    don't forget to call FlushCache() on the dataset after any operation
    that affects the array.
    """
    # prepare dataset name pointing to array
    datapointer = array.ctypes.data
    bands, lines, pixels = array.shape
    datatypecode = gdal_array.NumericTypeCodeToGDALTypeCode(array.dtype.type)
    datatype = gdal.GetDataTypeName(datatypecode)
    bandoffset, lineoffset, pixeloffset = array.strides
    # if projection is wrong there will be a segfault in RasterizeLayer
    projection = osr.GetUserInputAsWKT(str(projection))

    dataset_name_template = ("MEM:::"
                             "DATAPOINTER={datapointer},"
                             "PIXELS={pixels},"
                             "LINES={lines},"
                             "BANDS={bands},"
                             "DATATYPE={datatype},"
                             "PIXELOFFSET={pixeloffset},"
                             "LINEOFFSET={lineoffset},"
                             "BANDOFFSET={bandoffset}")
    dataset_name = dataset_name_template.format(
        datapointer=datapointer,
        pixels=pixels,
        lines=lines,
        bands=bands,
        datatype=datatype,
        pixeloffset=pixeloffset,
        lineoffset=lineoffset,
        bandoffset=bandoffset,
    )

    # access the array memory as gdal dataset
    dataset = gdal.Open(dataset_name, gdal.GA_Update)

    # set additional properties from kwargs
    if geo_transform is not None:
        dataset.SetGeoTransform(geo_transform)
    if projection is not None:
        dataset.SetProjection(projection)
    if no_data_value is not None:
        for i in range(len(array)):
            dataset.GetRasterBand(i + 1).SetNoDataValue(no_data_value)

    return dataset
Ejemplo n.º 14
0
    def from_type_B(cls, nc):
        """
        Load and init netCDF with results (type B).

        The netCDF contains separate variables for 2D nodes, but contain
        groundwater and surface water nodes mixed together.

        Convention: variable names referring to netCDF variables or indices
        thereof are prefixed with an underscore.

        All unique centers are placed on self, but the mapping for node types
        other than surface and groundwater are not included.
        """
        obj = Data()

        # find the indexes per node type
        _node_type = nc['Mesh2DNode_type']
        _node_type_data = _node_type[:]
        _node_type_sw = int(_node_type.surface_water_2d)
        _node_type_gw = int(_node_type.groundwater_2d)
        _index_all = dict(zip(*get_groups(_node_type_data)))
        _index_sw = _index_all.get(_node_type_sw, np.array([], int))
        _index_gw = _index_all.get(_node_type_gw, np.array([], int))

        # read centers of 2d nodes
        _n = nc.dimensions['nMesh2D_nodes'].size
        _centers = np.empty((_n, 2), 'f8')
        _centers[:, 0] = nc['Mesh2DFace_xcc'][:]
        _centers[:, 1] = nc['Mesh2DFace_ycc'][:]

        # determine unique set of centers
        _centers1d = _centers.view('f8,f8').ravel()
        centers, unique = np.unique(_centers1d, return_index=True)
        obj.centers = centers.view('f8').reshape(-1, 2)
        n = len(centers)

        # read only x coordinates for size analysis assuming square nodes
        edges_x = nc['Mesh2DContour_x'][:]
        x1, x2 = edges_x[unique].min(1), edges_x[unique].max(1)
        obj.size, obj.index = get_groups(array=x2 - x1)

        # derive a mapping from returned node index to netcdf node index
        index_sw = np.searchsorted(centers, _centers1d[_index_sw])
        obj.nodes_sw = np.full(n, _n, dtype='i8')
        obj.nodes_sw[index_sw] = _index_sw
        index_gw = np.searchsorted(centers, _centers1d[_index_gw])
        obj.nodes_gw = np.full(n, _n, dtype='i8')
        obj.nodes_gw[index_gw] = _index_gw
        obj.no_data_node = _n

        # attributes
        projection = nc['projected_coordinate_system'].EPSG_code
        obj.kwargs = {
            'no_data_value': n,
            'projection': osr.GetUserInputAsWKT(str(projection)),
        }

        return obj
Ejemplo n.º 15
0
def test_tps_1():

    drv = gdal.GetDriverByName('MEM')
    ds = drv.Create('foo', 2, 2)
    gcp_list = [
        gdal.GCP(0, 0, 0, 0, 0),
        gdal.GCP(0, 50, 0, 0, 50),
        gdal.GCP(50, 0, 0, 50, 0),
        gdal.GCP(50, 50, 0, 50, 50),
        gdal.GCP(0 * 25, 0 * 25, 0, 25, 25),
    ]
    ds.SetGCPs(gcp_list, osr.GetUserInputAsWKT('WGS84'))
    utm_wkt = osr.GetUserInputAsWKT('+proj=utm +zone=11 +datum=WGS84')

    with gdaltest.error_handler():
        transformer = gdal.Transformer(
            ds, None, ['DST_SRS=' + utm_wkt, 'METHOD=GCP_TPS'])
    assert transformer is None
Ejemplo n.º 16
0
    def create_file(cls, path, geometry, fields, layer, driver, options, sr):
        """Create a vector datasource"""

        with Env(_osgeo_use_exceptions=False):
            dr = gdal.GetDriverByName(driver)
            gdal_ds = gdal.OpenEx(
                path,
                conv.of_of_mode('w') | conv.of_of_str('vector'),
                [driver],
                options,
            )
            if gdal_ds is None:
                gdal_ds = dr.Create(path, 0, 0, 0, 0, options)
            else:
                if gdal_ds.GetLayerByName(
                        layer) is not None:  # pragma: no cover
                    err = gdal_ds.DeleteLayer(layer)
                    if err:
                        raise Exception('Could not delete %s' % path)

            # See TODO on deletion of existing file
            # if gdal_ds.GetLayerCount() == 0:
            #     del gdal_ds
            #     err = dr.DeleteDataSource(path)
            #     if err:
            #         raise Exception('Could not delete %s' % path)
            #     gdal_ds = dr.CreateDataSource(path, options)

            if gdal_ds is None:  # pragma: no cover
                raise Exception('Could not create gdal dataset (%s)' %
                                str(gdal.GetLastErrorMsg()).strip('\n'))

        if sr is not None:
            sr = osr.SpatialReference(osr.GetUserInputAsWKT(sr))

        geometry = conv.wkbgeom_of_str(geometry)
        lyr = gdal_ds.CreateLayer(layer, sr, geometry, options)

        if lyr is None:  # pragma: no cover
            raise Exception('Could not create layer (%s)' %
                            str(gdal.GetLastErrorMsg()).strip('\n'))

        for field in fields:
            flddef = ogr.FieldDefn(field['name'], field['type'])
            if field['precision'] is not None:
                flddef.SetPrecision(field['precision'])
            if field['width'] is not None:
                flddef.SetWidth(field['width'])
            if field['nullable'] is not None:
                flddef.SetNullable(field['nullable'])
            if field['default'] is not None:
                flddef.SetDefault(field['default'])
            lyr.CreateField(flddef)
        lyr.SyncToDisk()
        gdal_ds.FlushCache()
        return gdal_ds, lyr
Ejemplo n.º 17
0
    def acreate_raster(self,
                       path,
                       fp,
                       dtype,
                       band_count,
                       band_schema=None,
                       driver='GTiff',
                       options=(),
                       sr=None):
        """Create a raster file anonymously in this DataSource. Only metadata are kept in memory.

        See DataSource.create_raster

        Example
        -------
        >>> mask = ds.acreate_raster('mask.tif', ds.dem.fp, bool, 1, options=['SPARSE_OK=YES'])
        >>> open_options = mask.open_options

        >>> band_schema = {
        ...     'nodata': -32767,
        ...     'interpretation': ['blackband', 'cyanband'],
        ... }
        >>> out = ds.acreate_raster('output.tif', ds.dem.fp, 'float32', 2, band_schema)
        >>> band_interpretation = out.band_schema['interpretation']

        """
        # Parameter checking ***************************************************
        path = str(path)
        if not isinstance(fp, Footprint):  # pragma: no cover
            raise TypeError('`fp` should be a Footprint')
        dtype = np.dtype(dtype)
        band_count = int(band_count)
        band_schema = _tools.sanitize_band_schema(band_schema, band_count)
        driver = str(driver)
        options = [str(arg) for arg in options]
        if sr is not None:
            sr = osr.GetUserInputAsWKT(sr)

        if sr is not None:
            fp = self._back.convert_footprint(fp, sr)

        # Construction dispatch ************************************************
        if driver.lower() == 'mem':
            # TODO: Check not concurrent
            prox = GDALMemRaster(self, fp, dtype, band_count, band_schema,
                                 options, sr)
        elif True:
            allocator = lambda: BackGDALFileRaster.create_file(
                path, fp, dtype, band_count, band_schema, driver, options, sr)
            prox = GDALFileRaster(self, allocator, options, 'w')
        else:
            pass

        # DataSource Registering ***********************************************
        self._register([], prox)
        return prox
Ejemplo n.º 18
0
def get_sr(user_input):
    """ Return osr.SpatialReference for user input. """
    sr = osr.SpatialReference(osr.GetUserInputAsWKT(str(user_input)))
    # https://github.com/OSGeo/gdal/blob/release/3.0/gdal/MIGRATION_GUIDE.TXT
    #
    # GDAL takes into account official axis order.
    # Traditional GIS-friendly axis order can be restored with:
    if GDAL3:
        sr.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
    return sr
Ejemplo n.º 19
0
def osr_basic_18():

    # This is a dummy one, but who cares
    wkt = osr.GetUserInputAsWKT( 'http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/def/crs/EPSG/0/4326&2=http://www.opengis.net/def/crs/EPSG/0/4326' )
    if wkt.find('COMPD_CS') != 0:
        print(wkt)
        gdaltest.post_reason( 'CRS URL parsing not as expected.' )
        return 'fail'

    return 'success'
Ejemplo n.º 20
0
def tps_1():

    drv = gdal.GetDriverByName('MEM')
    ds = drv.Create('foo', 2, 2)
    gcp_list = [
        gdal.GCP(0, 0, 0, 0, 0),
        gdal.GCP(0, 50, 0, 0, 50),
        gdal.GCP(50, 0, 0, 50, 0),
        gdal.GCP(50, 50, 0, 50, 50),
        gdal.GCP(0 * 25, 0 * 25, 0, 25, 25),
    ]
    ds.SetGCPs(gcp_list, osr.GetUserInputAsWKT('WGS84'))
    utm_wkt = osr.GetUserInputAsWKT('+proj=utm +zone=11 +datum=WGS84')

    transformer = gdal.Transformer(ds, None,
                                   ['DST_SRS=' + utm_wkt, 'METHOD=GCP_TPS'])
    if transformer is None or gdal.GetLastErrorType() == 0:
        return 'fail'

    return 'success'
Ejemplo n.º 21
0
def osr_basic_7():

    wkt_1 = osr.GetUserInputAsWKT('urn:ogc:def:crs:OGC::AUTO42001:-117:33')
    wkt_2 = 'PROJCS["UTM Zone 11, Northern Hemisphere",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.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1,AUTHORITY["EPSG","9001"]]]'
    if wkt_1 != wkt_2:
        print(wkt_1)
        print(wkt_2)
        gdaltest.post_reason('AUTO42001 urn lookup not as expected.')
        return 'fail'

    return 'success'
Ejemplo n.º 22
0
def test_transformgeoloc_1():

    try:
        import numpy
    except ImportError:
        pytest.skip()

    # Setup 2x2 geolocation arrays in a memory dataset with lat/long values.

    drv = gdal.GetDriverByName('MEM')
    geoloc_ds = drv.Create('geoloc_1', 2, 2, 3, gdal.GDT_Float64)

    lon_array = numpy.asarray([[-117.0, -116.0], [-116.5, -115.5]])
    lat_array = numpy.asarray([[45.0, 45.5], [44.0, 44.5]])

    geoloc_ds.GetRasterBand(1).WriteArray(lon_array)
    geoloc_ds.GetRasterBand(2).WriteArray(lat_array)
    # Z left as default zero.

    # Create a wgs84 to utm transformer.

    wgs84_wkt = osr.GetUserInputAsWKT('WGS84')
    utm_wkt = osr.GetUserInputAsWKT('+proj=utm +zone=11 +datum=WGS84')

    ll_utm_transformer = gdal.Transformer(
        None, None, ['SRC_SRS=' + wgs84_wkt, 'DST_SRS=' + utm_wkt])

    # transform the geoloc dataset in place.
    status = ll_utm_transformer.TransformGeolocations(
        geoloc_ds.GetRasterBand(1), geoloc_ds.GetRasterBand(2),
        geoloc_ds.GetRasterBand(3))

    assert status == 0

    expected = numpy.asarray([[[500000., 578126.73752062],
                               [540087.07398217, 619246.88515195]],
                              [[4982950.40022655, 5038982.81207855],
                               [4871994.34702622, 4928503.38229753]],
                              [[0., 0.], [0., 0.]]])

    assert numpy.allclose(geoloc_ds.ReadAsArray(), expected)
Ejemplo n.º 23
0
def rextract(shape_path, output_path, username, attribute, srs, **kwargs):
    """
    Prepare and extract for each feature.
    """
    # session
    if username is None:
        # no login
        session = requests
    else:
        # login, might be needed for every thread...
        password = getpass.getpass('password for %s: ' % username)
        session = requests.Session()
        session.post(
            url=LOGIN_URL % kwargs['subdomain'],
            headers={'User-Agent': USER_AGENT},
            data={
                'username': username,
                'password': password
            },
        )
        if 'sessionid' not in session.cookies:
            # abort
            print('Login failed.')
            exit()

    # extract
    sr = osr.SpatialReference(osr.GetUserInputAsWKT(srs))
    output_path.mkdir(exist_ok=True)
    for layer in ogr.Open(shape_path):
        layer_name = layer.GetName()
        layer_path = output_path / layer_name
        layer_path.mkdir(exist_ok=True)
        for feature_no in range(layer.GetFeatureCount()):
            feature = layer[feature_no]
            geometry = feature.geometry()
            geometry.AssignSpatialReference(sr)  # ignore original srs
            try:
                feature_name = feature[attribute]
            except ValueError:
                msg = 'Attribute "%s" not found in layer "%s"'
                print(msg % (attribute, layer_name))
                exit()
            raster_extraction = RasterExtraction(
                path=layer_path / feature_name,
                geometry=geometry,
                **kwargs,
            )
            raster_extraction.process(session=session,
                                      srs=srs,
                                      subdomain=kwargs['subdomain'],
                                      time=kwargs['time'],
                                      uuid=kwargs['uuid'])
Ejemplo n.º 24
0
def get_epsg_or_wkt(text):
    """
    Return EPSG:<code> where possible, and WKT otherwise.

    :param text: Textual representation of a spatial reference system.
    """
    wkt = osr.GetUserInputAsWKT(str(text))
    sr = osr.SpatialReference(wkt)
    key = str("GEOGCS") if sr.IsGeographic() else str("PROJCS")
    name = sr.GetAuthorityName(key)
    if name is None:
        return wkt
    code = sr.GetAuthorityCode(key)
    return "{name}:{code}".format(name=name, code=code)
Ejemplo n.º 25
0
 def test_get_epsg_or_wkt(self):
     # epsg
     wkt = osr.GetUserInputAsWKT(str("EPSG:3857"))
     out = utils.get_epsg_or_wkt(wkt)
     self.assertEqual(out, "EPSG:3857")
     # no epsg
     wkt = """GEOGCS["GCS_WGS_1984",
                  DATUM["D_WGS_1984",SPHEROID[
                      "WGS_1984",6378137,298.257223563]],
                  PRIMEM["Greenwich",0],
                  UNIT["Degree",
                      0.017453292519943295]]"""
     out = utils.get_epsg_or_wkt(wkt)
     self.assertEqual(out, wkt.replace(" ", "").replace("\n", ""))
Ejemplo n.º 26
0
def get_crs(user_input):
    """
    Return fiona CRS dictionary for user input.
    """
    wkt = osr.GetUserInputAsWKT(str(user_input))
    sr = osr.SpatialReference(wkt)
    key = str("GEOGCS") if sr.IsGeographic() else str("PROJCS")
    name = sr.GetAuthorityName(key)
    if name == "EPSG":
        # we can specify CRS in EPSG code which is more compatible with output
        # file types
        return fiona.crs.from_epsg(int(sr.GetAuthorityCode(key)))
    else:
        # we have to go through Proj4
        return fiona.crs.from_string(sr.ExportToProj4())
Ejemplo n.º 27
0
    def acreate_vector(self,
                       path,
                       geometry,
                       fields=(),
                       layer=None,
                       driver='ESRI Shapefile',
                       options=(),
                       sr=None):
        """Create a vector file anonymously in this DataSource. Only metadata are kept in memory.

        See DataSource.create_vector

        Example
        -------
        >>> lines = ds.acreate_vector('/path/to.shp', 'linestring')
        >>> file_proj4 = lines.proj4_stored

        """
        # Parameter checking ***************************************************
        path = str(path)
        geometry = conv.str_of_wkbgeom(conv.wkbgeom_of_str(geometry))
        fields = _tools.normalize_fields_defn(fields)
        if layer is None:
            layer = '.'.join(ntpath.basename(path).split('.')[:-1])
        else:
            layer = str(layer)
        driver = str(driver)
        options = [str(arg) for arg in options]
        if sr is not None:
            sr = osr.GetUserInputAsWKT(sr)

        # Construction dispatch ************************************************
        if driver.lower() == 'memory':
            # TODO: Check not concurrent
            allocator = lambda: BackGDALFileVector.create_file(
                '', geometry, fields, layer, 'Memory', options, sr)
            prox = GDALMemoryVector(self, allocator, options)
        elif True:
            allocator = lambda: BackGDALFileVector.create_file(
                path, geometry, fields, layer, driver, options, sr)
            prox = GDALFileVector(self, allocator, options, 'w')
        else:
            pass

        # DataSource Registering ***********************************************
        self._register([], prox)
        return prox
Ejemplo n.º 28
0
def wkt_of_any(string):
    """Wkt of user input"""
    out = osr.GetUserInputAsWKT(string)
    if isinstance(out, str):
        return out
    else:
        prj = None
        gdal_ds = gdal.OpenEx(string, conv.of_of_str('raster'))
        if gdal_ds is not None:
            prj = gdal_ds.GetProjection()
        gdal_ds = gdal.OpenEx(string, conv.of_of_str('vector'))
        if gdal_ds is not None:
            lyr = gdal_ds.GetLayerByIndex(0)
            if lyr is not None:
                prj = lyr.GetSpatialRef()
        if prj is not None:
            return prj.ExportToWkt()
    raise ValueError('Could not convert to wkt ({})'.format(str(gdal.GetLastErrorMsg()).strip('\n')))
Ejemplo n.º 29
0
 def test_get_epsg_or_wkt(self):
     # epsg
     wkt = osr.GetUserInputAsWKT(str("EPSG:3857"))
     out = utils.get_epsg_or_wkt(wkt)
     self.assertEqual(out, "EPSG:3857")
     # no epsg
     wkt = """GEOGCS["GCS_WGS_1984",
                     DATUM["D_WGS_1984",SPHEROID[
                         "WGS_1984",6378137,298.257223563]],
                     PRIMEM["Greenwich",0],
                     UNIT["Degree",
                         0.017453292519943295]]"""
     out = utils.get_epsg_or_wkt(wkt)
     # do not test exact equality: different GDAL versions give different
     # results
     assert out.startswith("GEOGCS")
     assert 'PRIMEM["Greenwich",0]' in out
     assert 'UNIT["Degree"' in out
Ejemplo n.º 30
0
    def _set_coords(self):
        geotransform = self.source.GetGeoTransform()

        self.target.createDimension("y", self.raster_y_size)
        ycoords = self.target.createVariable("y", "f4", ("y",))

        # In CF-1.6 the coordinates are cell centers, while GDAL interprets
        # them as the upper-left corner.
        y_upper_left = geotransform[3] + geotransform[5] / 2
        ycoords[:] = np.arange(
            y_upper_left,
            y_upper_left + geotransform[5] * self.raster_y_size,
            geotransform[5]
        )
        ycoords.standard_name = "projection_y_coordinate"
        ycoords.long_name = "y coordinate of projection"
        ycoords.units = "m"
        ycoords.axis = "Y"

        self.target.createDimension("x", self.raster_x_size)
        xcoords = self.target.createVariable("x", "f4", ("x",))

        # CF 1.6 coordinates are cell center, while GDAL interprets
        # them as the upper-left corner.
        x_upper_left = geotransform[0] + geotransform[1] / 2
        xcoords[:] = np.arange(
            x_upper_left,
            x_upper_left + geotransform[1] * self.raster_x_size,
            geotransform[1]
        )
        xcoords.standard_name = "projection_x_coordinate"
        xcoords.long_name = "x coordinate of projection"
        xcoords.units = "m"
        xcoords.axis = "X"

        projection = self.target.createVariable(
            "projected_coordinate_system", "i4"
        )
        projection.EPSG_code = f"EPSG:{self.ra.epsg_code}"
        projection.epsg = self.ra.epsg_code
        projection.long_name = "Spatial Reference"
        projection.spatial_ref = osr.GetUserInputAsWKT(
            f"EPSG:{self.ra.epsg_code}"
        )  # for GDAL