gplately.Raster
- class gplately.Raster(data=None, plate_reconstruction=None, extent: str | tuple = 'global', resample=None, resize=None, time=0.0, origin=None, *, lons=None, lats=None, grid_registration=GridRegistration.Gridline, x_dimension_name: str = '', y_dimension_name: str = '', data_variable_name: str = '', **kwargs)[source]
Bases:
objectA class to represent a raster grid with time-dependent reconstruction capabilities.
- __init__(data=None, plate_reconstruction=None, extent: str | tuple = 'global', resample=None, resize=None, time=0.0, origin=None, *, lons=None, lats=None, grid_registration=GridRegistration.Gridline, x_dimension_name: str = '', y_dimension_name: str = '', data_variable_name: str = '', **kwargs)[source]
Constructor. Create a
Rasterobject.- Parameters:
data (str or array-like or
Raster) – The raster data, either as a file path (str) or array data or aRasterobject. If aRasterobject is specified then all other arguments are ignored exceptplate_reconstructionwhich, if it is notNone, will override the plate reconstruction of theRasterobject. The data parameter accepts numpy.ndarray, xarray.DataArray or or any object that can be converted to a numpy.ndarray. Use xarray.DataArray if you want to specify the longitudes and latitudes of the raster data. If you use numpy.ndarray, then you must specify the extent parameter to tell us the longitudes and latitudes of the raster data. The default value isNone, which is for backwards compatibility only. In the future, this parameter will be required and the default value will be removed.plate_reconstruction (PlateReconstruction) – A
PlateReconstructionobject for raster reconstruction.extent (str or 4-tuple, default: 'global') – 4-tuple to specify (min_lon, max_lon, min_lat, max_lat) extents of the raster. If no extents are supplied, full global extent (-180, 180, -90, 90) is assumed (equivalent to
extent='global'). For array data with an upper-left origin, make suremin_latis greater thanmax_lat, or specifyoriginparameter. Warning: The coordinates embeded in the data or thelonsandlatsparameters will overrideextent.resample (2-tuple, optional) – Optionally resample grid, pass spacing in X and Y direction as a 2-tuple e.g. resample=(spacingX, spacingY).
resize (2-tuple, optional) – Optionally resample grid to X-columns, Y-rows as a 2-tuple e.g. resample=(resX, resY).
time (float, default: 0.0) – The geological time of the time-dependant raster data.
origin ({'lower', 'upper'}, optional) – When
datais a plain numpy array, use this parameter to specify the origin (upper left or lower left) of the data. Warning: The coordinates embeded in the data or thelonsandlatsparameters will overrideorigin.lons (array-like, optional) – 1D array of longitude values. If not provided, will be inferred from the extent, origin and the shape of the data.
lats (array-like, optional) – 1D array of latitude values. If not provided, will be inferred from the extent, origin and the shape of the data.
cell_registration ({'gridline', 'pixel'}, optional, default: 'gridline') – Specify whether the raster data is gridline-registered or pixel-registered.
x_dimension_name (str, optional, default="") – If the grid file uses the comman names, such as
x,lon,lonsorlongitude, you need not to provide this parameter. Otherwise, you need to tell us what the x dimension name is.y_dimension_name (str, optional, default="") – If the grid file uses the comman names, such as
y,lat,latsorlatitude, you need not to provide this parameter. Otherwise, you need to tell us what the y dimension name is.data_variable_name (str, optional, default="") – GPlately will try its best to guess the data variable name. However, it would be much better if you tell us what the data variable name is. Otherwise, GPlately’s guess may/may not be correct.
**kwargs – Handle deprecated arguments such as
PlateReconstruction_object,filename, andarray.
Methods
__init__([data, plate_reconstruction, ...])Constructor.
clip_by_extent(extent)Clip the raster according to a given extent
(x_min, x_max, y_min, y_max).clip_by_polygons(polygons)TODO:
copy()Return a copy of the
Rasterobject.fill_NaNs([inplace, return_array])Deprecated.
fill_gaps(*[, method, use_gmt, ...])Fill invalid cells in a raster using interpolation.
from_points(lon, lat, values[, region, ...])Class method to create a
Rasterobject from scattered geographic points.imshow([ax, projection])Deprecated.
interp(*, lons, lats[, data, method, ...])Interpolate data at given longitude/latitude locations.
interpolate(-> ~numpy.ndarray)Sample grid data at a set of points using spline interpolation.
Check if the longitude coordinates have wrapped around the antimeridian.
Check if the raster is normalized.
Return a normalized Raster object.
plot([ax_or_fig, projection, use_gmt])Plot the raster data using either matplotlib or pygmt.
query(*, lons, lats[, interpolation_method, ...])Query raster values at given longitude/latitude coordinates.
reconstruct(-> ~gplately.raster.Raster)Reconstruct the raster from its current time to a new time.
resample(spacingX, spacingY[, method, ...])Resample raster data onto a new lon-lat grid.
resize(-> ~numpy.ndarray)Resize the grid with a new resolution (
resXandresY) using linear interpolation.rotate_reference_frames(...[, ...])Rotate a grid defined in one plate model reference frame within a
Rasterobject to another plate reconstruction model reference frame.sample_values(*, lons, lats[, method])save_to_netcdf4(filename[, ...])Saves the grid attributed to the
Rasterobject to the givenfilename(including the ".nc" extension) in netCDF4 format.to_data_array([name])Convert the raster to an xarray DataArray with spatial coordinates.
to_longitude_positive_360([inplace])Convert a grid's longitude coordinates to the [0, 360] convention.
to_longitude_signed_180([inplace])Convert a grid's longitude coordinates to the [-180, 180] convention.
Unwrap the longitude coordinates around the antimeridian.
Attributes
Numpy array containing the raster data.
The data type of the array.
The spatial extent
(x0, x1, y0, y1)of the data.The filename used to create the
Rasterobject.The fill value used for the raster data.
The latitude coordinates of the raster data.
The longitude convention of the raster data.
The longitude coordinates of the raster data.
Masked Numpy array for the raster data.
The number of dimensions in the array.
The conventional spatial extent of the data.
The origin (
lowerorupper) of the data array.A
PlateReconstructionobject for raster reconstruction.The shape of the data array.
The size of the data array.
The geological time of the time-dependant raster data.
- clip_by_extent(extent)[source]
Clip the raster according to a given extent
(x_min, x_max, y_min, y_max). The extent of the returned raster may be slightly bigger than the given extent. This happens when the border of the given extent fall between two gird lines.
- property data: ndarray
Numpy array containing the raster data.
- property dtype: dtype
The data type of the array.
- property extent: Tuple[float, float, float, float]
The spatial extent
(x0, x1, y0, y1)of the data. If not supplied, global extent(-180, 180, -90, 90)is assumed.If y0 < y1, the origin is the lower-left corner; else the upper-left.
- Type:
tuple of 4 floats
- property filename: str | None
The filename used to create the
Rasterobject. If the object was created directly from an array, this attribute isNone.
- fill_NaNs(inplace=False, return_array=False)[source]
Deprecated. Use
fill_gaps()instead. This method will be removed in a future version of the library.
- fill_gaps(*, method='nearest', use_gmt=False, use_spatial_tree=False, inplace=False, valid_mask=None, invalid_value=None) Raster[source]
Fill invalid cells in a raster using interpolation.
Supports both scalar rasters (
ny x nx) and image rasters (ny x nx x channels) wherechannelsis 3 (RGB) or 4 (RGBA).- Parameters:
method (str, default: 'nearest') – Interpolation method passed to
scipy.interpolate.griddata(). Typical options are'nearest','linear'and'cubic'.use_gmt (bool, default: False) – If
True, use PyGMTgrdfill/fillgrdfor filling gaps. This option currently supports only 2D scalar rasters.use_spatial_tree (bool, default: False) – If
True, use methodRaster._query_by_KDTree()to fill the gaps. Mutually exclusive withuse_gmt. This option support both 2D scalar rasters and 3D RGB/RGBA rasters.inplace (bool, default: False) – If
True, modify and return the current object. Otherwise, return a newRaster.valid_mask (array-like of bool, optional) – A 2D mask with shape
(len(lats), len(lons))indicating valid source pixels (True= valid). If omitted, validity is inferred from finite values and, if provided,invalid_value.invalid_value (scalar or sequence, optional) –
Additional marker for invalid pixels.
For scalar rasters, cells equal to this value are treated as invalid.
For RGB/RGBA rasters, this can be a scalar (applied to all channels) or a sequence with length equal to the channel count.
- Returns:
A raster with gaps filled.
- Return type:
- Raises:
ValueError – If raster dimensionality/channel count is unsupported, mask shape is invalid, or no valid points are available for interpolation.
- property fill_value
The fill value used for the raster data.
This property is being set when this Raster object is being created with Raster reconstruction. The fill_value means there is no valid data at the corresponding location.
The value of this property could be:
None, which means this raster data was never created by reconstruction.
- a single number for 2D scalar rasters, such as np.nan, minimum value for signed integer, and the
maximum value for unsigned interger.
a 3-tuple RGB colour code, such as black (0.0, 0.0, 0.0) or (0, 0, 0).
a 4-tuple RGBA colour code, such as transparent black (0.0, 0.0, 0.0, 0.0) or (0, 0, 0, 0).
- classmethod from_points(lon, lat, values, region=None, spacing='0.1d', tension=0.35, preprocess='blockmean', **surface_kwargs) Raster[source]
Class method to create a
Rasterobject from scattered geographic points. Interpolate scattered geographic points onto a regular grid using PyGMT’s surface (Green’s-function-based minimum-curvature gridding), with optional block-averaging preprocessing to avoid duplicate/ near-duplicate point errors.- Parameters:
lon (array-like) – 1D arrays (or lists) of equal length giving the longitude, latitude, and data value of each scattered point.
lat (array-like) – 1D arrays (or lists) of equal length giving the longitude, latitude, and data value of each scattered point.
values (array-like) – 1D arrays (or lists) of equal length giving the longitude, latitude, and data value of each scattered point.
region (str or list, optional) – GMT-style region specification [xmin, xmax, ymin, ymax]. If None, it is inferred from the data extent (with no padding).
spacing (str or float, optional) – Grid spacing passed to surface/blockmean (e.g. “0.1d” for 0.1 degree, or “10k” for 10 km). Default “0.1d”.
tension (float, optional) – Tension factor for surface, between 0 (minimum curvature, can overshoot) and 1 (harmonic, no overshoot). Default 0.35.
preprocess ({"blockmean", "blockmedian", None}, optional) – Whether to pre-bin the scattered points onto the target grid spacing before running surface. surface requires at most one point per grid cell, so this is standard practice for real-world (noisy / clustered / duplicate) data. Set to None to skip and pass points to surface directly. Default “blockmean”.
**surface_kwargs – Any additional keyword arguments forwarded to pygmt.surface (e.g. maxradius, convergence, etc.).
- Returns:
A Raster object containing the gridded surface.
- Return type:
Example
>>> import numpy as np >>> lon = np.random.uniform(120, 130, 500) >>> lat = np.random.uniform(30, 40, 500) >>> val = np.random.uniform(0, 100, 500) >>> raster = Raster.from_points(lon, lat, val, spacing="0.05d")
- imshow(ax=None, projection=None, **kwargs)[source]
Deprecated. Use
plot()instead. Plot the raster data using matplotlib.
- interp(*, lons, lats, data: DataArray | None = None, method: InterpMethod = InterpMethod.LINEAR, fill_value=nan, pointwise=True) ndarray[source]
Interpolate data at given longitude/latitude locations.
data may be: - 2D, with dims (‘lat’, ‘lon’) - 3D, with dims (‘lat’, ‘lon’, <channel>) for RGB/RGBA images
- Parameters:
pointwise (bool) –
If True (default), lons/lats are treated as paired query points (lons[i], lats[i]) — e.g. sampling at scattered station locations. Output shape: (N,) or (N, C).
If False, lons/lats define a new rectangular grid (outer product) — e.g. resampling the whole image onto a new lat/lon mesh. Output shape: (len(lats), len(lons)) or (len(lats), len(lons), C).
- Return type:
np.ndarray
- interpolate(lons, lats, method='linear', *, return_indices: Literal[False] = False) ndarray[source]
- interpolate(lons, lats, method='linear', *, return_indices: Literal[True]) tuple[ndarray, tuple[ndarray, ndarray]]
Sample grid data at a set of points using spline interpolation.
- Parameters:
lons (array_like) – The longitudes and latitudes of the points to interpolate onto the gridded data. Must be broadcastable to a common shape.
lats (array_like) – The longitudes and latitudes of the points to interpolate onto the gridded data. Must be broadcastable to a common shape.
method (str or int; default: 'linear') – The order of spline interpolation. Must be an integer in the range 0-5.
nearest,linear, andcubicare aliases for 0, 1, and 3, respectively.return_indices (bool, default=False) – Whether to return the row and column indices of the nearest grid points.
- Returns:
numpy.ndarray – The values interpolated at the input points.
indices (2-tuple of numpy.ndarray) – The i- and j-indices of the nearest grid points to the input points, only present if
return_indices=True.
- Raises:
ValueError – If an invalid
methodis provided.RuntimeWarning – If
latscontains any invalid values outside of the interval [-90, 90]. Invalid values will be clipped to this interval.
Note
If
return_indicesis set toTrue, the nearest array indices are returned as a tuple of arrays, in(i, j)or(lat, lon)format.An example output:
# The first array holds the rows of the raster where point data spatially falls near. # The second array holds the columns of the raster where point data spatially falls near. sampled_indices = (array([1019, 1019, 1019, ..., 1086, 1086, 1087]), array([2237, 2237, 2237, ..., 983, 983, 983]))
- is_longitude_wrapped() bool[source]
Check if the longitude coordinates have wrapped around the antimeridian.
- is_normalized() bool[source]
Check if the raster is normalized.
For now, the normalized raster means longitude: [-180, 180] and latitude: [-90, 90].
- property lats: ndarray
The latitude coordinates of the raster data.
- property longitude_convention: LongitudeConvention
The longitude convention of the raster data.
- Type:
LongitudeConvention
- property lons: ndarray
The longitude coordinates of the raster data.
- property masked_data: MaskedArray
Masked Numpy array for the raster data.
- normalized() Raster[source]
Return a normalized Raster object.
For now, the normalized raster means longitude: [-180, 180] and latitude: [-90, 90].
- Returns:
A new Raster object with normalized longitude and latitude. If the current Raster object is already normalized, it will return itself.
- Return type:
- property normalized_extent: Tuple[float, float, float, float]
The conventional spatial extent of the data. The “extent” property above may not be in the conventional order, especially when the origin is the upper-left corner. The “normalized_extent” property always returns the extent in the conventional order.
- Regardless of origin, extent is always:
extent = [left, right, bottom, top] or extent = [xmin, xmax, ymin, ymax]
The format never changes — bottom always means the smaller y value, top always means the larger y value.
- Type:
tuple of 4 floats
- property plate_reconstruction: PlateReconstruction | None
A
PlateReconstructionobject for raster reconstruction.
- plot(ax_or_fig=None, projection=None, use_gmt=False, **kwargs)[source]
Plot the raster data using either matplotlib or pygmt.
- Parameters:
ax_or_fig (matplotlib.axes.Axes or matplotlib.figure.Figure, optional) – If specified, the image will be drawn within these axes or figure.
projection (cartopy.crs.Projection, optional) – The map projection to be used. If both
ax_or_figandprojection` are specified, this will be checked against the ``projectionattribute ofax_or_fig, if it exists.use_gmt (bool, default False) – If True, use pygmt to plot the raster data. If False, use matplotlib.
**kwargs (dict, optional) – Any further keyword arguments are passed to the plotting function.
- query(*, lons: ndarray, lats: ndarray, interpolation_method: str = 'nearest', region_of_interest: None | float = None, pointwise: bool = True)[source]
Query raster values at given longitude/latitude coordinates.
- Parameters:
lons (np.ndarray) – Longitude and latitude coordinates.
lats (np.ndarray) – Longitude and latitude coordinates.
interpolation_method (str, default "nearest") – Interpolation method, such as “linear” or “nearest”. See Raster.InterpMethod for details.
pointwise (bool, default True) – If True, sample paired points (lons[i], lats[i]). If False, treat lons and lats as 1D axes of an output grid.
- Returns:
Sampled values at the given coordinates.
- Return type:
- reconstruct(time, *, fill_value=None, partitioning_features=None, threads=1, anchor_plate_id=None, inplace=False, return_array: Literal[False] = False, use_spatial_tree: bool = False, use_old_implementation: bool = False) Raster[source]
- reconstruct(time, *, fill_value=None, partitioning_features=None, threads=1, anchor_plate_id=None, inplace=False, return_array: Literal[True], use_spatial_tree: bool = False, use_old_implementation: bool = False) ndarray
Reconstruct the raster from its current time to a new time.
- Parameters:
time (float) – Time to which the data will be reconstructed.
fill_value (float, int, str, or tuple, optional) – The value to be used for regions outside of the static polygons at
time. By default (fill_value=None), this value will be determined based on the input.partitioning_features (sequence of Feature or str, optional) – The features used to partition the raster grid and assign plate IDs. By default,
self.plate_reconstruction.static_polygonswill be used, but alternatively any valid argument topygplates.FeaturesFunctionArgumentcan be specified here.threads (int, default 1) – Number of threads to use for certain computationally heavy routines.
anchor_plate_id (int, optional) – ID of the anchored plate. By default, reconstructions are made with respect to the anchor plate ID specified in the
PlateReconstructionobject.inplace (bool, default False) – Perform the reconstruction in-place (replace the raster’s data with the reconstructed data).
return_array (bool, default False) – Return a
numpy.ndarray, rather than aRaster.use_spatial_tree (bool, default False) – Whether to use a spatial tree for faster feature lookup.
- Returns:
The reconstructed Raster as a Raster object or a numpy array. Areas with no valid data will be filled with
fill_value.- Return type:
Raster or np.ndarray
Note
For two-dimensional grids,
fill_valueshould be a single number. The default value will benp.nanfor float or complex types, the minimum value for integer types, and the maximum value for unsigned types. For RGB image grids,fill_valueshould be a 3-tuple RGB colour code or a matplotlib colour string. The default value will be black (0.0, 0.0, 0.0) or (0, 0, 0). For RGBA image grids,fill_valueshould be a 4-tuple RGBA colour code or a matplotlib colour string. The default fill value will be transparent black (0.0, 0.0, 0.0, 0.0) or (0, 0, 0, 0).
- resample(spacingX: float, spacingY: float, method='linear', inplace=False, strict_spacing: bool = True)[source]
Resample raster data onto a new lon-lat grid.
Note
This method changes the lat-lon resolution of the gridded data. Larger spacing values produce a coarser grid.
New latitude and longitude arrays are created from
spacingXandspacingY, and data values are interpolated onto that target grid. IfinplaceisTrue, the currentRasterobject is updated.- Parameters:
spacingX (float) – Target spacing in degrees in the X (longitude) and Y (latitude) directions. Both must be positive.
spacingY (float) – Target spacing in degrees in the X (longitude) and Y (latitude) directions. Both must be positive.
method (str or int; default: 'linear') – The order of spline interpolation. Must be an integer in the range 0-5. ‘nearest’, ‘linear’, and ‘cubic’ are aliases for 0, 1, and 3, respectively.
inplace (bool, default=False) – Choose to overwrite the data (the
self.dataattribute), latitude array (self.lats) and longitude array (self.lons) currently attributed to theRasterobject.strict_spacing (bool, default=True) –
Controls whether spacing or extent is preserved exactly.
- If
True, output spacing is exactlyspacingX/spacingYand the output extent may differ slightly from the input extent.
- If
- If
False, output extent is preserved exactly and the effective spacing may differ slightly from
spacingX/spacingY.
- If
- Returns:
The resampled grid. If
inplaceis set toTruethe returned raster isself, otherwise a newRasterobject is returned.- Return type:
- resize(resX: int, resY: int, inplace=False, method='linear', *, return_array: Literal[True]) ndarray[source]
- resize(resX: int, resY: int, inplace=False, method='linear', *, return_array: Literal[False] = False) Raster
Resize the grid with a new resolution (
resXandresY) using linear interpolation.Note
Ultimately, The
resize()“stretches” a raster in the x and y directions. The larger the resolutions in x and y, the more stretched the raster appears in x and y.It creates new latitude and longitude arrays with specific resolutions in the X and Y directions (
resXandresY). These arrays are linearly interpolated into a new raster. Ifinplaceis set toTrue, the resized latitude, longitude arrays and raster will inplace the ones currently attributed to theRasterobject.- Parameters:
resX (int) – Specify the resolutions with which to resize the raster. The larger
resXis, the more longitudinally-stretched the raster becomes. The largerresYis, the more latitudinally-stretched the raster becomes.resY (int) – Specify the resolutions with which to resize the raster. The larger
resXis, the more longitudinally-stretched the raster becomes. The largerresYis, the more latitudinally-stretched the raster becomes.method (str or int; default: 'linear') – The order of spline interpolation. Must be an integer in the range 0-5. ‘nearest’, ‘linear’, and ‘cubic’ are aliases for 0, 1, and 3, respectively.
inplace (bool, default=False) – Choose to overwrite the data (the
self.dataattribute), latitude array (self.lats) and longitude array (self.lons) currently attributed to theRasterobject.return_array (bool, default False) – Return a
numpy.ndarray, rather than aRasterobject.
- Returns:
The resized grid. If
inplaceis set toTruethe returned raster isself(or returned array isself.dataifreturn_arrayisTrue), otherwise a newRasterobject is returned (or a new data array ifreturn_arrayisTrue).- Return type:
Raster or numpy.ndarray
- rotate_reference_frames(grid_spacing_degrees, reconstruction_time, from_rotation_features_or_model=None, to_rotation_features_or_model=None, from_rotation_reference_plate=0, to_rotation_reference_plate=0, non_reference_plate=701, output_name=None)[source]
Rotate a grid defined in one plate model reference frame within a
Rasterobject to another plate reconstruction model reference frame.- Parameters:
grid_spacing_degrees (float) – The spacing (in degrees) for the output rotated grid.
reconstruction_time (float) – The time at which to rotate the input grid.
from_rotation_features_or_model (str, list of str, instance of pygplates.RotationModel, filename(s), or pyGPlates feature(s)/collection(s)) – A filename, or a list of filenames, or a pyGPlates RotationModel object that defines the rotation model that the input grid is currently associated with.
to_rotation_features_or_model (str, list of str, instance of pygplates.RotationModel, filename(s), or pyGPlates feature(s)/collection(s)) – A filename, or a list of filenames, or a pyGPlates RotationModel object that defines the rotation model that the input grid shall be rotated with.
from_rotation_reference_plate (int, default = 0) – The current reference plate for the plate model the grid is defined in. Defaults to the anchor plate 0.
to_rotation_reference_plate (int, default = 0) – The desired reference plate for the plate model the grid is being rotated to. Defaults to the anchor plate 0.
non_reference_plate (int, default = 701) – An arbitrary placeholder reference frame with which to define the “from” and “to” reference frames.
output_name (str, default None) – If passed, the rotated grid is saved as a netCDF grid to this filename.
- Returns:
An instance of the
Rasterobject containing the rotated grid.- Return type:
- save_to_netcdf4(filename, significant_digits=None, fill_value=None)[source]
Saves the grid attributed to the
Rasterobject to the givenfilename(including the “.nc” extension) in netCDF4 format.
- to_data_array(name='')[source]
Convert the raster to an xarray DataArray with spatial coordinates.
Supports both:
2D scalar rasters with dimensions
(lat, lon)3D RGB/RGBA rasters with dimensions
(lat, lon, band)
- to_longitude_positive_360(inplace=False)[source]
Convert a grid’s longitude coordinates to the [0, 360] convention.
- to_longitude_signed_180(inplace=False)[source]
Convert a grid’s longitude coordinates to the [-180, 180] convention.
- unwrap_longitude()[source]
Unwrap the longitude coordinates around the antimeridian. For example, if the longitude coordinates are [170, 175, 180, -175, -170] in range[-180, 180], they will be unwrapped to [170, 175, 180, 185, 190] in range[0, 360].
Note
There is no need to rearrange the raster data because unwrapping the longitude coordinates does not change the order of the data. The data will still be in the same order as before, but the longitude coordinates will be adjusted to avoid wrapping around the antimeridian.