gplately.Raster

class gplately.Raster(data=None, plate_reconstruction=None, extent: str | tuple = 'global', realign=False, resample=None, resize=None, time=0.0, origin=None, x_dimension_name: str = '', y_dimension_name: str = '', data_variable_name: str = '', **kwargs)[source]

Bases: object

The functionalities include sampling data at points using spline interpolation, resampling rasters with new X and Y-direction spacings and resizing rasters using new X and Y grid pixel resolutions. NaN-type data in rasters can be replaced with the values of their nearest valid neighbours.

__init__(data=None, plate_reconstruction=None, extent: str | tuple = 'global', realign=False, resample=None, resize=None, time=0.0, origin=None, x_dimension_name: str = '', y_dimension_name: str = '', data_variable_name: str = '', **kwargs)[source]

Constructor. Create a Raster object.

Parameters:
  • data (str or array-like) – The raster data, either as a file path (str) or array data.

  • plate_reconstruction (PlateReconstruction) –

    A PlateReconstruction object to provide the following essential components for reconstructing points.

  • 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 sure min_lat is greater than max_lat, or specify origin parameter.

  • 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 the time-dependant raster data.

  • origin ({'lower', 'upper'}, optional) – When data is an array, use this parameter to specify the origin (upper left or lower left) of the data (overriding extent).

  • x_dimension_name (str, optional, default="") – If the grid file uses the comman names, such as x, lon, lons or longitude, 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, lats or latitude, 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, and array.

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).

copy()

Return a copy of the Raster object.

fill_NaNs([inplace, return_array])

Search for the invalid data cells containing NaN-type entries and replaces NaNs with the value of the nearest valid data cell.

imshow([ax, projection])

Display raster data.

interpolate(lons, lats[, method, return_indices])

Sample grid data at a set of points using spline interpolation.

plot([ax, projection])

Display raster data.

query(lons, lats[, region_of_interest])

Given a set of location coordinates, return the grid values at these locations.

reconstruct(time[, fill_value, ...])

Reconstruct the raster from its initial time (self.time) to a new time.

resample(spacingX, spacingY[, method, inplace])

Resamples the grid with a new spacingX and spacingY, meshed with linear interpolation.

resize(resX, resY[, inplace, method, ...])

Resize the grid with a new resolution (resX and resY) using linear interpolation.

rotate_reference_frames(...[, ...])

Rotate a grid defined in one plate model reference frame within a Raster object to another plate reconstruction model reference frame.

save_to_netcdf4(filename[, ...])

Saves the grid attributed to the Raster object to the given filename (including the ".nc" extension) in netCDF4 format.

Attributes

data

Array containing the raster data.

dtype

The data type of the array.

extent

The spatial extent (x0, x1, y0, y1) of the data.

filename

The filename used to create the Raster object.

lats

The y-coordinates of the raster data.

lons

The x-coordinates of the raster data.

ndim

The number of dimensions in the array.

origin

The origin (lower or upper) of the data array.

plate_reconstruction

A PlateReconstruction object to provide the following essential components for reconstructing points.

shape

The shape of the data array.

size

The size of the data array.

time

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.

Parameters:

extent (tuple) – A tuple of 4 (min_lon, max_lon, min_lat, max_lat) extent.

Returns:

The clipped grid.

Return type:

Raster

copy()[source]

Return a copy of the Raster object.

Returns:

A copy of the current Raster object.

Return type:

Raster

property data

Array containing the raster data. This attribute can be modified after creating the Raster object.

Type:

ndarray, shape (ny, nx)

property dtype

The data type of the array.

property extent

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

The filename used to create the Raster object. If the object was created directly from an array, this attribute is None.

Type:

str or None

fill_NaNs(inplace=False, return_array=False)[source]

Search for the invalid data cells containing NaN-type entries and replaces NaNs with the value of the nearest valid data cell.

Parameters:
  • inplace (bool, default=False) – Choose whether to overwrite the grid currently held in the data attribute with the filled grid.

  • return_array (bool, default False) – Return a numpy.ndarray, rather than a Raster.

Returns:

The resized grid. If inplace is set to True, the data in Raster.data will be overwritten.

Return type:

Raster

imshow(ax=None, projection=None, **kwargs)[source]

Display raster data.

A pre-existing matplotlib Axes instance is used if available, else a new one is created. The origin and extent of the image are determined automatically and should not be specified.

Parameters:
  • ax (matplotlib.axes.Axes, optional) – If specified, the image will be drawn within these axes.

  • projection (cartopy.crs.Projection, optional) – The map projection to be used. If both ax and projection are specified, this will be checked against the projection attribute of ax, if it exists.

  • **kwargs (dict, optional) – Any further keyword arguments are passed to matplotlib.pyplot.imshow or matplotlib.axes.Axes.imshow, where appropriate.

Return type:

matplotlib.image.AxesImage

Raises:

ValueError – If ax and projection are both specified, but do not match (i.e. ax.projection != projection).

interpolate(lons, lats, method='linear', return_indices=False)[source]

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, and cubic are 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 method is provided.

  • RuntimeWarning – If lats contains any invalid values outside of the interval [-90, 90]. Invalid values will be clipped to this interval.

Note

If return_indices is set to True, 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]))
property lats

The y-coordinates of the raster data. This attribute can be modified after creating the Raster object.

Type:

ndarray, shape (ny,)

property lons

The x-coordinates of the raster data. This attribute can be modified after creating the Raster object.

Type:

ndarray, shape (nx,)

property ndim

The number of dimensions in the array.

property origin

The origin (lower or upper) of the data array.

Type:

str

property plate_reconstruction

A PlateReconstruction object to provide the following essential components for reconstructing points.

Type:

PlateReconstruction

plot(ax=None, projection=None, **kwargs)

Display raster data.

A pre-existing matplotlib Axes instance is used if available, else a new one is created. The origin and extent of the image are determined automatically and should not be specified.

Parameters:
  • ax (matplotlib.axes.Axes, optional) – If specified, the image will be drawn within these axes.

  • projection (cartopy.crs.Projection, optional) – The map projection to be used. If both ax and projection are specified, this will be checked against the projection attribute of ax, if it exists.

  • **kwargs (dict, optional) – Any further keyword arguments are passed to matplotlib.pyplot.imshow or matplotlib.axes.Axes.imshow, where appropriate.

Return type:

matplotlib.image.AxesImage

Raises:

ValueError – If ax and projection are both specified, but do not match (i.e. ax.projection != projection).

query(lons, lats, region_of_interest=None)[source]

Given a set of location coordinates, return the grid values at these locations.

Parameters:
  • lons (list) – a list of longitudes of the location coordinates

  • lats (list) – a list of latitude of the location coordinates

  • region_of_interest (float) – the radius of the region of interest in km this is the arch length. we need to calculate the straight distance between the two points in 3D space from this arch length.

Returns:

a list of grid values for the given locations.

Return type:

list

reconstruct(time, fill_value=None, partitioning_features=None, threads=1, anchor_plate_id=None, inplace=False, return_array=False)[source]

Reconstruct the raster from its initial time (self.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_polygons will be used, but alternatively any valid argument to pygplates.FeaturesFunctionArgument can 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 PlateReconstruction object.

  • 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 a Raster.

Returns:

  • Raster or np.ndarray – The reconstructed grid. Areas for which no plate ID could be determined will be filled with fill_value.

  • .. note:: – For two-dimensional grids, fill_value should be a single number. The default value will be np.nan for float or complex types, the minimum value for integer types, and the maximum value for unsigned types. For RGB image grids, fill_value should 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_value should 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, spacingY, method='linear', inplace=False)[source]

Resamples the grid with a new spacingX and spacingY, meshed with linear interpolation.

Note

Ultimately, the resample() changes the lat-lon resolution of the gridded data. The larger the x and y spacings given are, the larger the pixellation of raster data.

The resample() creates new latitude and longitude arrays with specified spacings in the X and Y directions (spacingX and spacingY). These arrays are linearly interpolated into a new raster. If inplace is set to True, the respaced latitude array, longitude array and raster will inplace the ones currently attributed to the Raster object.

Parameters:
  • spacingX (ndarray) – Specify the spacing in the X and Y directions with which to resample. The larger spacingX and spacingY are, the larger the raster pixels become (less resolved). Note: to keep the size of the raster consistent, set spacingX = spacingY; otherwise, if for example spacingX > spacingY, the raster will appear stretched longitudinally.

  • spacingY (ndarray) – Specify the spacing in the X and Y directions with which to resample. The larger spacingX and spacingY are, the larger the raster pixels become (less resolved). Note: to keep the size of the raster consistent, set spacingX = spacingY; otherwise, if for example spacingX > spacingY, the raster will appear stretched longitudinally.

  • 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.data attribute), latitude array (self.lats) and longitude array (self.lons) currently attributed to the Raster object.

Returns:

The resampled grid. If inplace is set to True, this raster overwrites the one attributed to data.

Return type:

Raster

resize(resX, resY, inplace=False, method='linear', return_array=False)[source]

Resize the grid with a new resolution (resX and resY) 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 (resX and resY). These arrays are linearly interpolated into a new raster. If inplace is set to True, the resized latitude, longitude arrays and raster will inplace the ones currently attributed to the Raster object.

Parameters:
  • resX (ndarray) – Specify the resolutions with which to resize the raster. The larger resX is, the more longitudinally-stretched the raster becomes. The larger resY is, the more latitudinally-stretched the raster becomes.

  • resY (ndarray) – Specify the resolutions with which to resize the raster. The larger resX is, the more longitudinally-stretched the raster becomes. The larger resY is, 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.data attribute), latitude array (self.lats) and longitude array (self.lons) currently attributed to the Raster object.

  • return_array (bool, default False) – Return a numpy.ndarray, rather than a Raster object.

Returns:

The resized grid. If inplace is set to True, the data in Raster.data will be overwritten.

Return type:

Raster

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 Raster object 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, or instance of pygplates.RotationModel) – 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, or instance of pygplates.RotationModel) – 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 Raster object containing the rotated grid.

Return type:

Raster

save_to_netcdf4(filename, significant_digits=None, fill_value=nan)[source]

Saves the grid attributed to the Raster object to the given filename (including the “.nc” extension) in netCDF4 format.

property shape

The shape of the data array.

property size

The size of the data array.

property time

The geological time of the time-dependant raster data.

Type:

float