Ejemplo n.º 1
0
    def create_file(cls, path, fp, dtype, channel_count, channels_schema,
                    driver, options, wkt, ow):
        """Create a raster dataset"""

        # Step 0 - Find driver ********************************************** **
        success, payload = GDALErrorCatcher(gdal.GetDriverByName,
                                            none_is_error=True)(driver)
        if not success:
            raise ValueError(
                'Could not find a driver named `{}` (gdal error: `{}`)'.format(
                    driver, payload[1]))
        dr = payload

        # Step 1 - Overwrite ************************************************ **
        if dr.ShortName != 'MEM' and os.path.exists(path):
            if ow:
                success, payload = GDALErrorCatcher(
                    dr.Delete, nonzero_int_is_error=True)(path)
                if not success:
                    msg = 'Could not delete `{}` using driver `{}` (gdal error: `{}`)'.format(
                        path, dr.ShortName, payload[1])
                    raise RuntimeError(msg)
            else:
                msg = "Can't create `{}` with `ow=False` (overwrite) because file exist".format(
                    path, )
                raise RuntimeError(msg)

        # Step 2 - Create gdal_ds ******************************************* **
        options = [str(arg) for arg in options]
        success, payload = GDALErrorCatcher(dr.Create)(
            path, fp.rsizex, fp.rsizey, channel_count,
            conv.gdt_of_any_equiv(dtype), options)
        if not success:  # pragma: no cover
            raise RuntimeError(
                'Could not create `{}` using driver `{}` (gdal error: `{}`)'.
                format(path, dr.ShortName, payload[1]))
        gdal_ds = payload

        # Step 3 - Set spatial reference ************************************ **
        if wkt is not None:
            gdal_ds.SetProjection(wkt)
        gdal_ds.SetGeoTransform(fp.gt)

        # Step 4 - Set channels schema ************************************** **
        channels_schema = _tools.sanitize_channels_schema(
            channels_schema, channel_count)
        cls._apply_channels_schema(gdal_ds, channels_schema)

        gdal_ds.FlushCache()
        return gdal_ds
Ejemplo n.º 2
0
    def delete(self):
        super(BackGDALFileRaster, self).delete()

        success, payload = GDALErrorCatcher(gdal.GetDriverByName,
                                            none_is_error=True)(self.driver)
        if not success:  # pragma: no cover
            raise ValueError(
                'Could not find a driver named `{}` (gdal error: `{}`)'.format(
                    self.driver, payload[1]))
        dr = payload

        success, payload = GDALErrorCatcher(dr.Delete,
                                            nonzero_int_is_error=True)(
                                                self.path)
        if not success:  # pragma: no cover
            raise RuntimeError(
                'Could not delete `{}` using driver `{}` (gdal error: `{}`)'.
                format(self.path, dr.ShortName, payload[1]))
Ejemplo n.º 3
0
    def open_file(path, layer, driver, options, mode):
        """Open a vector dataset"""
        options = [str(arg) for arg in options] if len(options) else []
        success, payload = GDALErrorCatcher(gdal.OpenEx, none_is_error=True)(
            path,
            conv.of_of_mode(mode) | conv.of_of_str('vector'),
            [driver],
            options,
        )
        if not success:
            raise RuntimeError(
                'Could not open `{}` using driver `{}` (gdal error: `{}`)'.
                format(path, driver, payload[1]))
        gdal_ds = payload

        if layer is None:
            layer = 0
        if np.all(np.isreal(layer)):
            success, payload = GDALErrorCatcher(gdal_ds.GetLayer)(int(layer))
        else:
            success, payload = GDALErrorCatcher(gdal_ds.GetLayerByName)(layer)

        if not success:  # pragma: no cover
            count = gdal_ds.GetLayerCount()
            raise Exception(
                'Could not open layer `{}` of `{}` ({} layers available: {}) (gdal error: `{}`)'
                .format(
                    layer,
                    path,
                    count,
                    {
                        i: gdal_ds.GetLayerByIndex(i).GetName()
                        for i in range(count)
                    },
                    payload[1],
                ))
        lyr = payload

        return gdal_ds, lyr
Ejemplo n.º 4
0
    def open_file(path, driver, options, mode):
        """Open a raster dataset"""

        success, payload = GDALErrorCatcher(gdal.OpenEx, none_is_error=True)(
            path,
            conv.of_of_mode(mode) | conv.of_of_str('raster'),
            [driver],
            options,
        )
        if not success:
            raise RuntimeError(
                'Could not open `{}` using driver `{}` (gdal error: `{}`)'.
                format(path, driver, payload[1]))
        gdal_ds = payload

        return gdal_ds
Ejemplo n.º 5
0
    def sample_bands_driver(self, fp, channel_ids, gdal_ds):
        rtlx, rtly = self.fp.spatial_to_raster(fp.tl)
        assert rtlx >= 0 and rtlx < self.fp.rsizex, '{} >= 0 and {} < {}'.format(
            rtlx, rtlx, self.fp.rsizex)
        assert rtly >= 0 and rtly < self.fp.rsizey, '{} >= 0 and {} < {}'.format(
            rtly, rtly, self.fp.rsizey)

        dstarray = np.empty(np.r_[fp.shape, len(channel_ids)], self.dtype)
        for i, channel_id in enumerate(channel_ids):
            gdal_band = gdal_ds.GetRasterBand(channel_id + 1)
            success, payload = GDALErrorCatcher(gdal_band.ReadAsArray,
                                                none_is_error=True)(
                                                    int(rtlx),
                                                    int(rtly),
                                                    int(fp.rsizex),
                                                    int(fp.rsizey),
                                                    buf_obj=dstarray[..., i],
                                                )
            if not success:  # pragma: no cover
                raise ValueError(
                    'Could not read array (gdal error: `{}`)'.format(
                        payload[1]))
        return dstarray
Ejemplo n.º 6
0
    def create_file(cls, path, geometry, fields, layer, driver, options, wkt,
                    ow):
        """Create a vector dataset"""

        # Step 0 - Find driver ********************************************** **
        success, payload = GDALErrorCatcher(gdal.GetDriverByName,
                                            none_is_error=True)(driver)
        if not success:
            raise ValueError(
                'Could not find a driver named `{}` (gdal error: `{}`)'.format(
                    driver, payload[1]))
        dr = payload

        # Step 1 - Overwrite ************************************************ **
        if dr.ShortName != 'Memory' and os.path.exists(path):
            if ow:
                success, payload = GDALErrorCatcher(
                    dr.Delete, nonzero_int_is_error=True)(path)
                if not success:
                    msg = 'Could not delete `{}` using driver `{}` (gdal error: `{}`)'.format(
                        path, dr.ShortName, payload[1])
                    raise RuntimeError(msg)
            else:
                msg = "Can't create `{}` with `ow=False` (overwrite) because file exist".format(
                    path, )
                raise RuntimeError(msg)

        # Step 2 - Create gdal_ds ******************************************* **
        success, payload = GDALErrorCatcher(dr.Create)(path, 0, 0, 0, 0,
                                                       options)
        if not success:  # pragma: no cover
            raise RuntimeError(
                'Could not create `{}` using driver `{}` (gdal error: `{}`)'.
                format(path, dr.ShortName, payload[1]))
        gdal_ds = payload

        # Step 3 - Get spatial reference ************************************ **
        if wkt is not None:
            sr = osr.SpatialReference(wkt)
        else:
            sr = None

        # Step 4 - Create layer ********************************************* **
        geometry = conv.wkbgeom_of_str(geometry)
        success, payload = GDALErrorCatcher(gdal_ds.CreateLayer,
                                            none_is_error=True)(layer, sr,
                                                                geometry,
                                                                options)
        if not success:  # pragma: no cover
            msg = 'Could not create layer `{}` in `{}` using driver `{}` (gdal error: `{}`)'.format(
                layer, path, dr.ShortName, payload[1])
            raise RuntimeError(msg)
        lyr = payload

        # Step 5 - Set fields *********************************************** **
        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