Dataset
gma.gio.Dataset
[class] Dataset(data = None, shape = None, crs = None, geo_transform = None, dtype = None, nodata = None, metadata = {}, **kwargs):Create a Dataset object!
Optional:
data = Dataset||ndarray||list||tuple||None. Default None.
Input data source. Can be a Dataset object, or a NumPy ndarray, list, tuple.
If data is None, a new Dataset will be created according to the shape parameter.
shape = tuple||None. Default None.
Shape of the new Dataset. If shape is a 2-tuple, it represents (rows, columns), and the number of bands is 1. If shape is a 3-tuple, it represents (bands, rows, columns).
If shape is None, data must be set.
crs = str||int||None. Default None.
The output coordinate system. Can be EPSG, WKT, Proj4, and other types of coordinate characters. Default(None) no coordinate system!
geo_transform = tuple||None. Default None.
Geo transformation of the output raster. The affine transformation is not specified by default (None).
dtype = str||None. Default None.
A code or string tag for the output raster data type.
Supported data types include:
'Unknown', 'Byte', 'UInt16', 'Int16', 'UInt32', 'Int32','Float32', 'Float64', 'CInt16', 'CInt32', 'CFloat32', 'CFloat64', ...
For more, see const.RaDT_*.
If dtype is None, the data type is determined by the data parameter.
nodata = float||None. Default None.
Invalid value for output raster. The default is not specified (None).
metadata = dict. Default {}.
Metadata to be added.
**kwargs:
Other parameters passed to _algos.geo.dataset.raster_translate.
Example
import numpy as np
from gma import gio
# Open the Natural Earth shaded relief raster (sample data)
ds = gio.open_raster('HYP_50M_SR_W.tif')
# Clip it by Australia for the following examples
ly = gio.open_vector('Australia.shp')
ds = ds.clip(ly)
print(ds.shape)
print(ds.bounds)
# All following method examples are based on this dataset
(3, 1006, 1220)
(112.93333333330409, -43.599999999986636, 153.59999999996668, -10.066666666656673)
Method
algebraic(agg_fun, block = (None, 2048, 2048), sel_bands = None, scr_nodata = None, dst_nodata = None, **kwargs)
Perform algebraic operations on Dataset.
Parameters:
agg_fun: def.
Calculate functions. For Example:
def func(in_ar):
return in_ar[0] * 2.1
agg_fun = func
in_ar: Input NumPy arrays with block`s shape.
Optional:
block = tuple. Default (None, 2048, 2048).
Block sizes for bands, rows, and columns. Use None to represent all.
sel_bands = list||None. Default None.
Extract band numbers. Selecting a subset of bands can reduce memory usage.
The default (None) is all bands.
scr_nodata = float. Default None.
Input nodata value. The default is not specified (None).
dst_nodata = float. Default None.
Output nodata value. The default is scr_nodata (None).
**kwargs:
Other parameters passed to driver.RasterDriver.create.
Returns:
Type: Dataset.
A new Dataset after the operation. The original dataset is unchanged.
Example:
# RGB values of a pixel before the operation
print(ds.to_numpy()[:, 500, 600])
# Convert to Float32 first to avoid uint8 overflow, then convert to grayscale
res = ds.to_dtype('float32').algebraic(lambda in_ar: (in_ar[0] + in_ar[1] + in_ar[2]) / 3)
# Grayscale value after the operation
print(res.to_numpy()[:, 500, 600])
[196 188 173]
[185.66666667]
clip(layer, **kwargs)
Clip off areas that are not covered by the method layer.
Parameters:
layer: Layer||Feature||Geometry||str.
A GMA item use for cliping!
**kwargs:
Other parameters passed to _algos.geo.dataset.raster_translate
Returns:
Type: Dataset.
A new Dataset clipped by the layer. The original dataset is unchanged.
Example:
# The sample raster (global) and the clip layer
world = gio.open_raster('HYP_50M_SR_W.tif')
ly = gio.open_vector('Australia.shp')
res = world.clip(ly)
print(world.shape, '->', res.shape)
print(res.bounds)
(3, 5400, 10800) -> (3, 1006, 1220)
(112.93333333330409, -43.599999999986636, 153.59999999996668, -10.066666666656673)

extent(**kwargs)
The extent of a geometry is the bounding rectangle.
Optional:
**kwargs:
Other parameters passed to _aio.Layer.Layer.
Returns:
Type: Layer.
A new Layer of the dataset extent (bounding rectangle).
Example:
res = ds.extent()
print(res.gtype, res.bounds)
Polygon (112.93333333330409, -43.599999999986636, 153.59999999996668, -10.066666666656673)
gen_lonlat(**kwargs)
Generate latitude and longitude raster.
Returns:
Type: Dataset.
A new Dataset with two bands: Band 1 is longitude, Band 2 is latitude.
Example:
res = ds.gen_lonlat()
print(res.shape)
print(res.to_numpy()[0, 500, :3]) # Band 1: longitude
print(res.to_numpy()[1, 500, :3]) # Band 2: latitude
(2, 1006, 1220)
[112.933334 112.96667 113. ]
[-26.733334 -26.733334 -26.733334]

get_palette(bid = 1)
Get palette of the band.
Optional:
bid = int. Default 1.
Number of the element calculation band. Start with 1.
Returns:
Type: matplotlib. colors.ListedColormap or None.
The palette (color table) of the band. None if the band has no palette.
Example:
# Palette is only supported for a single Byte/UInt16 band
ar = ds.to_numpy()[0] # Band 1 of the dataset
ds_b = gio.Dataset(data=ar, crs=ds.crs, geo_transform=ds.geo_transform)
ds_b.set_nodata(255)
res = ds_b.reclassify({100: 20, 150: 128, 240: 230}, method='Range').to_dtype('Byte')
res.set_palette({20: (49, 54, 149, 255), 128: (255, 201, 101, 255), 230: (215, 90, 60, 255)})
print(type(res.get_palette()).__name__)
ListedColormap
isopleth(interval = 50, base = 0, band = 1, **kwargs)
Generate a smooth curve formed by connecting points with equal quantity index values.
Optional:
interval = float. Default 50.0.
Isopleth interval.
base = float. Default 0.0.
The offset from the zero point of the start of the interval.
band = int. Default 1.
The number of the band to be calculated starts from 1.
**kwargs:
Other parameters passed to _aio.layer.Layer.
Returns:
Type: Layer.
A new Layer of isopleths (MultiLineString).
Example:
res = ds.isopleth(interval=100)
print(res.gtype, len(res))
MultiLineString 2458

plot(ax = None, bands = None, **kwargs)
Make plots of Dataset.
Optional:
ax = None||matplotlib. ~.AxesSubplot. Default None.
A matplotlib subplot. If None, a default axes will be created.
bands = int||list||None. Default None.
The band ID to be plotted. For multi-band data, only 1, 3 (RGB), and 4 (RGBA) bands are supported for selection. Duplicate bands will only keep one. Default is the first four bands.
**kwargs:
Other parameters passed to matplotlib.image.AxesImage.
Returns:
Type: matplotlib. ~.GeoAxes.
The axes with the plotted dataset. A new GeoAxes is created if ax is None; otherwise, the provided ax is returned.
Example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax = ds.plot(ax=ax)
print(type(ax).__name__)
Axes

reclassify(remap, method = "Range", **kwargs)
Reclassifies (or changes) the values in a raster.
Parameters:
remap: dict.
Remap object. Used to remap an input value or range definition to a new value.
The format is {mapping1: value1, mapping2: value2, ...}.
Note: Items containing NAN will be rejected directly.
Optional:
method = str. Default 'Range'.
Specifies how to reclassify the values of the input raster. May be: 'Range' or 'Unique'.
'Range': The data in the range will be mapped.
'Unique': Mapped strictly on a one-to-one basis.
For example:
Remap = {1000: 1, 2000: 2, 3000: 3} 1. ReClaMethod = 'Range'.
Data <= 1000: --> 1
1000 < Data <= 1000: --> 2
2000 < Data <= 3000: --> 3
Data > 3000: --> NoData
2. ReClaMethod = 'Unique'.
Data == 1000: --> 1
Data == 2000: --> 2
Data == 3000: --> 3
Other values: --> NoData
**kwargs:
Other parameters passed to _algos.geo.dataset.raster_translate
Returns:
Type: Dataset.
A new Dataset with remapped values (Float64). The original dataset is unchanged.
Example:
# Raw values of a pixel (RGB)
print(ds.to_numpy()[:, 500, 600])
res = ds.reclassify({100: 20, 150: 128, 240: 230}, method='Range')
print(ds.dtype, '->', res.dtype)
print(res.to_numpy()[:, 500, 600])
[196 188 173]
Byte -> Float64
[230. 230. 230.]

resample(resolution, method = "Nearest", **kwargs)
Change the spatial resolution of the Dataset.
Parameters:
resolution: float||list.
Resampling resolution(X, Y).
Optional:
method = str. Default 'Nearest'.
Resampling method. Supported resampling methods include:
'Nearest', 'Bilinear', 'Cubic', 'CubicSpline', 'Lanczos', 'Average', 'RMS', 'Mode'.
**kwargs:
Other parameters passed to _algos.geo.dataset.raster_translate
Returns:
Type: Dataset.
A new Dataset with the target resolution. The original dataset is unchanged.
Example:
res = ds.resample(0.2)
print(ds.shape, '->', res.shape)
print(ds.resolution, '->', res.resolution)
(3, 1006, 1220) -> (3, 168, 203)
(0.033333333333329995, 0.03333333333332998) -> (0.2, 0.2)

set_crs(crs)
Set dataset's crs!
Parameters:
crs: str||int||None.
The output coordinate system. Can be EPSG, WKT, Proj4, and other types of coordinate characters. Default(None) no coordinate system!
Returns:
Type: None.
Modify in place.
Example:
ds.set_crs('EPSG:4326')
print(ds.crs)
<CoordinateReferenceSystem:WGS 84>
set_gcps(gcps = [(0, 0, 0, 0, 0, '', '')], crs = None)
Set GCPs.
Optional:
gcps = list[tuple]. Default [(0, 0, 0, 0, 0, '', '')].
list(4 foloat + 2str) of gcps values.
format:
[(x(float), y(float), z(float), pixel(float), line(float), info(str, opt), id(str, opt)), ...]
crs = str||int||None. Default None.
The gcps' coordinate system. Can be EPSG, WKT, Proj4, and other types of coordinate characters. Default(None) no coordinate system!
Returns:
Type: None.
Modify in place.
Example:
gcps = [(113.0, -12.0, 0.0, 0.0, 0.0, 'GCP1', '1'),
(115.0, -14.0, 3.0, 3.0, 0.0, 'GCP2', '2')]
ds.set_gcps(gcps, crs='EPSG:4326')
print(ds.gcps)
[(113.0, -12.0, 0.0, 0.0, 0.0, 'GCP1', '1'), (115.0, -14.0, 3.0, 3.0, 0.0, 'GCP2', '2')]
set_geo_transform(geo_transform)
Set dataset's geo transform!
Parameters:
geo_transform: tuple.
Geo transformation of the output raster(6 float of tuple). format:
[x min, x resolution, x rotation, y max, y rotation, y resolution]
Returns:
Type: None.
Modify in place.
Example:
print('Before:', ds.bounds)
ds.set_geo_transform((112, 0.1, 0, -10, 0, -0.1))
print('After :', ds.bounds)
Before: (112.93333333330409, -43.599999999986636, 153.59999999996668, -10.066666666656673)
After : (112.0, -110.60000000000001, 234.0, -10.0)
set_metadata(metadata)
Set dataset's metadata!
Parameters:
metadata: dict.
Metadata to be added.
Returns:
Type: None.
Modify in place.
Example:
ds.set_metadata({'': {'author': 'gma'}})
print(ds.metadata)
{'': {'author': 'gma'}, 'IMAGE_STRUCTURE': {'INTERLEAVE': 'PIXEL'}}
set_nodata(nodata, bids = None)
Set dataset's nodata value of band!
Parameters:
nodata: float.
Invalid value for output raster.
Optional:
bids = int||lint of int||None. Default None.
Number of the element calculation band. Start with 1. None for all bands.
Returns:
Type: None.
Modify in place.
Example:
print('Before:', ds.nodata)
ds.set_nodata(0)
print('After :', ds.nodata)
Before: 255.0
After : 0.0
set_palette(palette)
Set dataset's palette of band!
Parameters:
palette: dict||matplotlib. ~.cmap or a list of them.
Palette(color table) of raster bands.
For example:
1.dict({value: (R,G,B,A)}):
palette = {10:(200,50,100,255), 20:(200,50,100,255)}.
2.camp:
import matplotlib.colors as cor palette = cor.ListedColormap(['r', 'g', 'b'], N = 256)
Returns:
Type: None.
Modify in place.
Example:
# Palette is only supported for a single Byte/UInt16 band
ar = ds.to_numpy()[0] # Band 1 of the dataset
ds_b = gio.Dataset(data=ar, crs=ds.crs, geo_transform=ds.geo_transform)
ds_b.set_nodata(255)
res = ds_b.reclassify({100: 20, 150: 128, 240: 230}, method='Range').to_dtype('Byte')
res.set_palette({20: (49, 54, 149, 255), 128: (255, 201, 101, 255), 230: (215, 90, 60, 255)})
print(type(res.get_palette()).__name__)
ListedColormap

set_statistics(statistics, bids = None)
Set dataset's statistics of band!
Parameters:
statistics: None||list of tuple(vmin||vmax||vmean||vstddev).
Statistics values. None for automatically compute statistics.
Optional:
bids = int||lint of int||None. Default None.
Number of the element calculation band. Start with 1. None for all bands.
Returns:
Type: None.
Modify in place.
Example:
# Set band statistics as (vmin, vmax, vmean, vstddev) tuples
ds.set_statistics([(82, 233, 174, 19)])
# The stats property returns automatically computed statistics
print(ds.stats)
{'Band1': {'min': 82.0, 'max': 233.0, 'mean': 173.98274225862008, 'std': 18.609418232702744}, 'Band2': {'min': 115.0, 'max': 226.0, 'mean': 173.3839232364416, 'std': 11.007481465773026}, 'Band3': {'min': 100.0, 'max': 228.0, 'mean': 161.13321148641523, 'std': 10.251896008952336}}
shift(distance = 1)
Shift a distance of the dataset. **Warining: This method will modify the original data.
Parameters:
distance = float||list. Default 1.
X, Y shift distance. If a single value is provided, it is assumed that X = Y.
Returns:
Type: Dataset.
The shifted dataset itself. Warning: this method modifies the original data in place.
Example:
print('Before:', ds.bounds)
ds.shift(0.5)
print('After :', ds.bounds)
Before: (112.93333333330409, -43.599999999986636, 153.59999999996668, -10.066666666656673)
After : (113.43333333330409, -43.099999999986636, 154.09999999996668, -9.566666666656673)
to_bytearray(row_off = 0, column_off = 0, row_size = None, column_size = None, sel_bands = None)
Reads the raster dataset as a bytearray.
Optional:
row_off = int. Default 0.
The starting row of the data to be read.
column_off = int. Default 0.
The starting column of the data to be read.
row_size = int. Default None.
The number of rows to read from the start row (the row width of the data window). The default (None) is all rows from the start row.
column_size = int. Default None.
The number of columns to read from the start column (the column width of the data window). Default (None) All columns from the start column.
sel_bands = int||list. Default None.
The band number or list of band numbers to be read. Default (None) All bands (numbering starts from 1).
Returns:
Type: bytearray.
The raster data as a bytearray.
Example:
ba = ds.to_bytearray()
print(type(ba).__name__, len(ba))
bytearray 3681960
to_crs(crs, **kwargs)
Reproject to another coordinate system.
Parameters:
crs: str||int.
The output coordinate system. Can be EPSG, WKT, Proj4, and other types of coordinate characters.
Optional:
**kwargs:
Other parameters passed to _algos.geo.dataset.raster_translate
Returns:
Type: Dataset.
A new Dataset reprojected to the target crs. The original dataset is unchanged.
Example:
res = ds.to_crs('EPSG:3857')
print(res.crs)
print(res.bounds)
<CoordinateReferenceSystem:WGS 84 / Pseudo-Mercator>
(12571681.16025044, -5403798.8988850545, 17097188.38544975, -1126426.5345974586)

to_dtype(dtype, **kwargs)
Convert the data type of raster.
Parameters:
dtype: str.
A code or string tag for the output raster data type.
Supported data types include:
'Unknown', 'Byte', 'UInt16', 'Int16', 'UInt32', 'Int32','Float32', 'Float64', 'CInt16', 'CInt32', 'CFloat32', 'CFloat64', ...
for more, see const.RaDT_*.
Optional:
**kwargs:
Other parameters passed to _algos.geo.dataset.raster_translate
Returns:
Type: Dataset.
A new Dataset converted to the target dtype. The original dataset is unchanged.
Example:
res = ds.to_dtype('float32')
print(ds.dtype, '->', res.dtype)
Byte -> Float32
to_file(out_dst, driver = "GTiff", **kwargs)
Save Dataset as a raster file.
Parameters:
out_dst: str.
The output raster file path.
Optional:
driver = str. Default 'GTiff'.
Output file driver. For other drivers, see gft.RasterSummary().CreatableFormats.
**kwargs:
Other parameters passed to _algos.geo.dataset.raster_translate.
Returns:
Type: None.
The dataset is saved to the output file.
Example:
ds.to_file('result.tif')
# Reopen the saved file to verify
ds2 = gio.open_raster('result.tif')
print(ds2.shape)
(3, 1006, 1220)
to_layer(field = None, band = 1, gtype = "Polygon", mask = False, **kwargs)
Translate Dataset to Layer!
Optional:
field = str. Default None.
The name of the output vector field. None for band.
band = int. Default 1.
Number of the element calculation band. Start with 1.
gtype = str. Default 'Polygon'.
Geometry type! Can be 'Point', 'MultiPoint', 'Line', 'MultiLine', 'MultiPolygon' or 'Polygon'. The default (None) is the automatic geometry type.
mask = bool. Default False.
Whether to build mask layer(nodata:0, other:1).
**kwargs:
Other parameters passed to _algos.geo.layer.Layer.
Returns:
Type: Layer.
A new Layer translated from the dataset.
Example:
res = ds.reclassify({100: 20, 150: 128, 240: 230}, method='Range')
lay = res.to_layer()
print(lay.gtype, len(lay))
Polygon 4541

to_numpy(row_off = 0, column_off = 0, row_size = None, column_size = None, sel_bands = None, mask_nodata = False)
Reads the raster dataset as a 3-ndim Numpy array.
Optional:
row_off = int. Default 0.
The starting row of the data to be read.
column_off = int. Default 0.
The starting column of the data to be read.
row_size = int. Default None.
The number of rows to read from the start row (the row width of the data window). The default (None) is all rows from the start row.
column_size = int. Default None.
The number of columns to read from the start column (the column width of the data window). Default (None) All columns from the start column.
sel_bands = int||list. Default None.
The band number or list of band numbers to be read. Default (None) All bands (numbering starts from 1).
mask_nodata = bool. Default False.
Whether to mask array with nodata value.
Returns:
Type: array.
The raster data as a 3-ndim NumPy array.
Example:
ar = ds.to_numpy()
print(ar.shape, ar.dtype)
print(ar[0, 500, :3])
(3, 1006, 1220) uint8
[255 255 255]
write_array(ar, row_off = 0, column_off = 0, sel_bands = None)
Write array to dataset.
Parameters:
ar: np. ndarray.
The NumPy array that needs to be set.
Optional:
row_off = int. Default 0.
The starting row of the data to be read.
column_off = int. Default 0.
The starting column of the data to be read.
sel_bands = int||list. Default None.
The band number or list of band numbers to be read. Default (None) All bands (numbering starts from 1).
Returns:
Type: None.
Modify in place.
Example:
print('Before:', ds.to_numpy()[0, 500, 600])
ds.write_array(np.zeros(ds.shape, dtype='uint8'))
print('After :', ds.to_numpy()[0, 500, 600])
Before: 196
After : 0
Property
blocks
Fetch the natural block size of this band. --> list(x and y dimensions of block)
Example:
print(ds.blocks)
{'Band1': [1220, 2], 'Band2': [1220, 2], 'Band3': [1220, 2]}
bounds
Bounds. --> tuple
Example:
print(ds.bounds)
(112.93333333330409, -43.599999999986636, 153.59999999996668, -10.066666666656673)
compression
Raster compression. --> str
Example:
# The clipped in-memory Dataset has no compression.
# Open the original file to get its compression
ds_f = gio.open_raster('HYP_50M_SR_W.tif')
print(ds_f.compression)
DEFLATE
crs
Raster coordinate reference system. --> CoordinateReferenceSystem
Example:
print(ds.crs)
<CoordinateReferenceSystem:WGS 84>
driver
Raster driver. --> RasterDriver
Example:
print(ds.driver)
GTiff - Raster
dtype
Raster data type. --> str
Example:
print(ds.dtype)
Byte
gcps
Raster GCPs. --> tuple
Example:
print(ds.gcps)
[]
geo_transform
Raster geo transform. --> tuple
Example:
print(ds.geo_transform)
(112.93333333330409, 0.033333333333329995, 0.0, -10.066666666656673, 0.0, -0.03333333333332998)
link
Layer path link. --> str
Example:
# In-memory Datasets get a random link.
# Open a file to get its real link (the path of the file)
ds_f = gio.open_raster('HYP_50M_SR_W.tif')
print(ds_f.link)
HYP_50M_SR_W.tif
metadata
metadata. --> dict
Example:
print(ds.metadata)
{'': {'AREA_OR_POINT': 'Area', 'TIFFTAG_DATETIME': '2012:07:16 09:16:14', 'TIFFTAG_RESOLUTIONUNIT': '2 (pixels/inch)', 'TIFFTAG_SOFTWARE': 'Adobe Photoshop CS5 Macintosh', 'TIFFTAG_XRESOLUTION': '342.85699', 'TIFFTAG_YRESOLUTION': '342.85699'}, 'IMAGE_STRUCTURE': {'INTERLEAVE': 'PIXEL'}}
name
Raster Name. --> str
Example:
# In-memory Datasets get a random name.
# Open a file to get its real name
ds_f = gio.open_raster('HYP_50M_SR_W.tif')
print(ds_f.name)
HYP_50M_SR_W
nodata
Raster nodata values. --> float
Example:
print(ds.nodata)
255.0
resolution
X, Y resolution. --> tuple
Example:
print(ds.resolution)
(0.033333333333329995, 0.03333333333332998)
shape
Raster shape. --> tuple(band, rows, columns)
Example:
print(ds.shape)
(3, 1006, 1220)
stats
Get stats of all bands. --> dict
Example:
for band, st in ds.stats.items():
print(band, st)
Band1 {'min': 82.0, 'max': 233.0, 'mean': 173.98274225862008, 'std': 18.609418232702744}
Band2 {'min': 115.0, 'max': 226.0, 'mean': 173.3839232364416, 'std': 11.007481465773026}
Band3 {'min': 100.0, 'max': 228.0, 'mean': 161.13321148641523, 'std': 10.251896008952336}