Exemple #1
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
Exemple #2
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
Exemple #3
0
    def create_file(cls, path, fp, dtype, band_count, band_schema, driver,
                    options, wkt):
        """Create a raster datasource"""
        dr = gdal.GetDriverByName(driver)
        if os.path.isfile(path):
            err = dr.Delete(path)
            if err:  # pragma: no cover
                raise Exception('Could not delete %s' % path)

        options = [str(arg) for arg in options]
        gdal_ds = dr.Create(path, fp.rsizex, fp.rsizey, band_count,
                            conv.gdt_of_any_equiv(dtype), options)
        if gdal_ds is None:  # pragma: no cover
            raise Exception('Could not create gdal dataset (%s)' %
                            str(gdal.GetLastErrorMsg()).strip('\n'))
        if wkt is not None:
            gdal_ds.SetProjection(wkt)
        gdal_ds.SetGeoTransform(fp.gt)

        band_schema = _tools.sanitize_band_schema(band_schema, band_count)
        cls._apply_band_schema(gdal_ds, band_schema)

        gdal_ds.FlushCache()
        return gdal_ds
Exemple #4
0
    def wrap_numpy_raster(self,
                          key,
                          fp,
                          array,
                          band_schema=None,
                          sr=None,
                          mode='w'):
        """Register a numpy array as a raster under `key` in this DataSource.

        Parameters
        ----------
        key: hashable (like a string)
            File identifier within DataSource
        fp: Footprint of shape (Y, X)
            Description of the location and size of the raster to create.
        array: ndarray of shape (Y, X) or (Y, X, B)
        band_schema: dict or None
            Band(s) metadata. (see `Band fields` below)
        sr: string or None
            Spatial reference of the new file

            if None: don't set a spatial reference
            if string:
                if path: Use same projection as file at `path`
                if textual spatial reference:
                    http://gdal.org/java/org/gdal/osr/SpatialReference.html#SetFromUserInput-java.lang.String-
        mode: one of {'r', 'w'}

        Returns
        -------
        NumpyRaster

        Band fields
        -----------
        Fields:
            'nodata': None or number
            'interpretation': None or str
            'offset': None or number
            'scale': None or number
            'mask': None or one of ('')
        Interpretation values:
            undefined, grayindex, paletteindex, redband, greenband, blueband, alphaband, hueband,
            saturationband, lightnessband, cyanband, magentaband, yellowband, blackband
        Mask values:
            all_valid, per_dataset, alpha, nodata

        A field missing or None is kept to default value.
        A field can be passed as:
            a value: All bands are set to this value
            a sequence of length `band_count` of value: All bands will be set to respective state

        """
        # Parameter checking ***************************************************
        self._validate_key(key)
        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([key], prox)
        return prox
Exemple #5
0
    def create_raster(self,
                      key,
                      path,
                      fp,
                      dtype,
                      band_count,
                      band_schema=None,
                      driver='GTiff',
                      options=(),
                      sr=None):
        """Create a raster file and register it under `key` in this DataSource. Only metadata are
        kept in memory.

        Parameters
        ----------
        key: hashable (like a string)
            File identifier within DataSource
        path: string
        fp: Footprint
            Description of the location and size of the raster to create.
        dtype: numpy type (or any alias)
        band_count: integer
            number of bands
        band_schema: dict or None
            Band(s) metadata. (see `Band fields` below)
        driver: string
            gdal driver to use when opening the file
            http://www.gdal.org/formats_list.html
        options: sequence of str
            options for gdal
            http://www.gdal.org/frmt_gtiff.html
        sr: string or None
            Spatial reference of the new file

            if None: don't set a spatial reference
            if string:
                if path: Use same projection as file at `path`
                if textual spatial reference:
                    http://gdal.org/java/org/gdal/osr/SpatialReference.html#SetFromUserInput-java.lang.String-

        Returns
        -------
        one of {GDALFileRaster, GDALMemRaster}
            depending on the `driver` parameter

        Band fields
        -----------
        Fields:
            'nodata': None or number
            'interpretation': None or str
            'offset': None or number
            'scale': None or number
            'mask': None or one of ('')
        Interpretation values:
            undefined, grayindex, paletteindex, redband, greenband, blueband, alphaband, hueband,
            saturationband, lightnessband, cyanband, magentaband, yellowband, blackband
        Mask values:
            all_valid, per_dataset, alpha, nodata

        A field missing or None is kept to default value.
        A field can be passed as:
            a value: All bands are set to this value
            a sequence of length `band_count` of value: All bands will be set to respective state

        Example
        -------
        >>> ds.create_raster('out', 'output.tif', ds.dem.fp, 'float32', 1)
        >>> file_footprint = ds.out.fp

        Caveat
        ------
        When using the GTiff driver, specifying a `mask` or `interpretation` field may lead to unexpected results.

        """
        # Parameter checking ***************************************************
        self._validate_key(key)
        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([key], prox)
        return prox