API Reference
This section provides a detailed reference for smmregrid’s Application Programming Interface (API).
smmregrid module
- class smmregrid.CdoGenerate(source_grid, target_grid=None, extra=None, cdo_extra=None, cdo_options=None, cdo_download_path=None, cdo_icon_grids=None, cdo='cdo', loglevel='warning')
Bases:
objectCDO-based class to generate weights for smmregrid.
Initialize GenerateWeights class for regridding using Climate Data Operators (CDO), accommodating both 2D and 3D grid cases.
- Parameters:
source_grid (str or xarray.Dataset) – The source grid from which to generate weights. This can be a file path or an xarray dataset.
target_grid (str or xarray.Dataset) – The target grid to which the source grid will be regridded. This can also be a file path or an xarray dataset.
loglevel (str, optional) – The logging level for messages. Default is ‘warning’. Options include ‘debug’, ‘info’, ‘warning’, ‘error’, and ‘critical’.
extra (list, optional) – Deprecated. Previously used for additional CDO options. Use cdo_extra instead.
cdo_extra (list, optional) – Additional CDO command-line options. Defaults to None.
cdo_options (list, optional) – Options for CDO commands. Defaults to None.
cdo (str, optional) – The command to invoke CDO. Default is “cdo”.
cdo_icon_grids (str, optional) – Path to the ICON grid if applicable. Defaults to None.
cdo_download_path (str, optional) – Path to the grid download path if applicable. Defaults to None.
- areas(target=False)
Generate source areas or target areas
- weights(method='con', extrapolate=True, remap_norm='fracarea', remap_area_min=0.0, vert_coord=None, vertical_dim=None, nproc=1)
Generate weights for regridding using Climate Data Operators (CDO), accommodating both 2D and 3D grid cases.
- Parameters:
method (str, optional) – The remapping method to use. Default is “con” for conservative remapping. Other options may include ‘bil’, ‘nearest’, etc.
extrapolate (bool, optional) – Whether to allow extrapolation beyond the grid boundaries. Defaults to True.
remap_norm (str, optional) – The normalization method to apply when remapping. Default is “fracarea” which normalizes by fractional area.
remap_area_min (float, optional) – Minimum area for remapping. Defaults to 0.0.
nproc (int, optional) – Number of processes to use for parallel processing. Default is 1.
vertical_dim (str, optional) – Name of the vertical dimension in the source grid, if applicable. Defaults to None. Use if the grid is 3D.
vert_coord (str, optional) – Deprecated. Previously used to specify the vertical coordinate. Use vertical_dim instead.
- Returns:
- A dataset containing the generated weights
and a mask indicating which grid cells were successfully masked. The mask is stored in a variable named “dst_grid_masked”.
- Return type:
xarray.Dataset
- Raises:
KeyError – If the specified vertical dimension cannot be found in the source grid.
Warning – If deprecated arguments extra or vert_coord are used.
Notes
This function handles both 2D and 3D grid cases:
For 2D grids (when vertical_dim is None), it calls the _weights_2d method to generate weights. The weights are then masked based on a precomputed weights matrix.
For 3D grids (when vertical_dim is specified), it uses multiprocessing to generate weights for each vertical level. It requires the vertical dimension to be present in the source grid, and it will generate a mask indicating valid and invalid weights for each vertical level.
The function logs the progress of weight generation, including the length of vertical dimensions and each level being processed.
Deprecation Warning: The extra and vert_coord parameters are deprecated and will be removed in future versions. Users should migrate to using cdo_extra and vertical_dim, respectively.
- weightslist_to_3d(ds_list, vertical_dim='lev')
Combine a list of 2D CDO weights into a 3D one.
- class smmregrid.GridInspector(data, cdo_weights=False, extra_dims=None, clean=True, loglevel='warning')
Bases:
objectClass to investigate data and detect its GridType() object
GridInspector class to detect information on the data, based on GridType class
- Parameters:
data (xr.Datase or xr.DataArray) – The input dataset.
clean (bool) – apply the cleaning of grids which are assumed to be not relevant for regridding purposes (e.g. bounds)
cdo_weights (bool) – if the data provided are cdo weights instead of data to be regridded
extra_dims (dict) – Extra dimensions to be added and passed to GridType
loglevel – The loglevel that you want you use
- get_grid_info()
Returns detailed information about all the grids in the dataset.
- identify_variables(gridtype)
Identify variables in the provided data that match the defined dimensions.
- Parameters:
gridtype (GridType) – The Gridtype object of originally inspected from the data
- Raises:
TypeError – If the input data is neither an xarray Dataset nor DataArray.
- Updates:
self.variables: Updates the variables dictionary with identified variables and their coordinates. self.bounds: Updates the bounds list with identified bounds variables from the dataset.
- class smmregrid.GridType(dims, extra_dims=None, weights=None)
Bases:
objectFundamental GridType object
Initializes a GridType object carrying grid-specific information required by smmregrid.
- Parameters:
dims (list) – A list of default dimensions for the grid (e.g., [‘time’, ‘lat’, ‘lon’]).
extra_dims (dict, optional) – A dictionary including keys ‘vertical’, ‘time’, and ‘horizontal’ that can be used to extend the default dimensions. Defaults to None.
weights (any, optional) – CDO weights used in regridding. It will initiate the object in a different way assuming single-gridtype objects. Defaults to None.
- horizontal_dims
The identified horizontal dimensions from the input.
- Type:
list
- vertical_dim
The identified vertical dimension, if applicable.
- Type:
str or None
- dims
The dimensions defined for the grid. A combination of horizontal and vertical.
- Type:
list
- time_dims
The identified time dimensions from the input.
- Type:
list
- other_dims
The dimensions which are there but are not identified automatically.
- Type:
list
- variables
A dictionary holding identified variables and their coordinates.
- Type:
dict
- bounds
A list of bounds variables identified in the dataset.
- Type:
list
- masked
Placeholder for masked data (to be defined later).
- Type:
any
- weights
The weights associated with the grid, if provided.
- Type:
any
- weights_matrix
Placeholder for a weights matrix (to be defined later).
- Type:
any
- level_index
A string used to identify the index of the levels.
- Type:
str
- Raises:
ValueError – If multiple vertical dimensions are identified during initialization.
- class smmregrid.Regridder(source_grid=None, target_grid=None, weights=None, method='con', transpose=True, vert_coord=None, vertical_dim=None, space_dims=None, horizontal_dims=None, cdo_extra=None, cdo_options=None, cdo='cdo', loglevel='WARNING')
Bases:
objectMain smmregrid regridding class
Initialize the Regridder for performing regridding operations.
This class allows for regridding between two grids, either by providing source and target grids or by using pre-computed weights. For large grids, it is recommended to pre-calculate weights using CDO. If weights are not supplied, they will be calculated using CDO’s genbil function based on the provided source and target grids.
Pre-computed weights can be generated externally or by using
CdoGenerate().- Parameters:
source_grid (xarray.DataArray or str) – Source grid dataset or file path.
target_grid (xarray.DataArray) – Target grid dataset for regridding.
weights (xarray.Dataset) – Pre-computed interpolation weights.
vertical_dim (str) – Name of the vertical coordinate for 3D weights generation (default: None).
horizontal_dims (list) – List of spatial dimensions to interpolate (default: None).
method (str) – Interpolation method to use (default: ‘con’).
transpose (bool) – If True, transpose the output such that the vertical coordinate is placed just before the other spatial coordinates (default: True).
cdo (str) – Path to the CDO executable (default: ‘cdo’).
cdo_extra (str) – Extra command to be passed to CDO
cdo_options (str) – Extra options to be passed to CDO
loglevel (str) – Logging level for the operation (default: ‘WARNING’).
- Raises:
ValueError – If neither weights nor source and target grids are provided.
FileNotFoundError – If the specified source grid file does not exist.
KeyError – If no grid types are found in the data.
Warning
DeprecationWarning: If deprecated arguments ‘vert_coord’ or ‘space_dims’ are used.
- apply_weights(source_data, weights, weights_matrix=None, masked=True, horizontal_dims=None)
Apply CDO weights to the source data, performing the regridding operation.
This method multiplies the source data with the weights matrix to produce the regridded output.
- Parameters:
source_data (xarray.DataArray) – The source data to be regridded.
weights (xarray.DataArray) – The CDO weights for interpolation.
weights_matrix (xarray.DataArray, optional) – Pre-computed weights matrix (default: None).
masked (bool) – Indicates if the DataArray is masked (default: True).
horizontal_dims (list) – List of dimensions for interpolation (e.g., [‘lon’, ‘lat’]).
- Returns:
The regridded version of the source dataset.
- Return type:
xarray.DataArray
- Raises:
KeyError – If none of the specified horizontal dimensions are found in the DataArray.
- regrid(source_data)
Regrid the provided source data to match the target grid.
This method applies the regridding process to either a single data array or a dataset containing multiple data variables.
- Parameters:
source_data (xarray.DataArray or xarray.Dataset) – The source data to be regridded.
- Returns:
The regridded data, matching the target grid.
- Return type:
xarray.DataArray or xarray.Dataset
- Raises:
TypeError – If the provided source data is neither an xarray DataArray nor Dataset.
- regrid2d(source_data, datagridtype)
Regrid a 2D source data array to match the target grid.
This method applies the necessary weights for 2D data regridding.
- Parameters:
source_data (xarray.DataArray) – The 2D source data to be regridded.
datagridtype – The grid type information for the source data.
- Returns:
The regridded 2D data.
- Return type:
xarray.DataArray
- regrid3d(source_data, datagridtype)
Regrid a 3D source data array to match the target grid.
This method applies the necessary weights and handles vertical coordinates.
- Parameters:
source_data (xarray.DataArray) – The 3D source data to be regridded.
datagridtype – The grid type information for the source data.
- Returns:
The regridded 3D data.
- Return type:
xarray.DataArray
- Raises:
ValueError – If there are issues with transposing the output dimensions.
- regrid_array(source_data)
Perform regridding on a single 2D or 3D array.
This method decides whether to call the 2D or 3D regridding function based on the dimensions of the source data.
- Parameters:
source_data (xarray.DataArray) – The source data array to regrid.
- Returns:
The regridded array.
- Return type:
xarray.DataArray
- Raises:
ValueError – If the input data does not match expected dimensions.
- smmregrid.cdo_generate_weights(source_grid, target_grid, method='con', extrapolate=True, remap_norm='fracarea', remap_area_min=0.0, gridpath=None, icongridpath=None, extra=None, cdo_extra=None, cdo_options=None, vertical_dim=None, vert_coord=None, cdo='cdo', nproc=1, loglevel='warning')
Wrapper function for the new cdo class to provide the old access
- smmregrid.regrid(source_data, target_grid=None, weights=None, transpose=True, cdo='cdo')
A simple regrid. Inefficient if you are regridding more than one dataset to the target grid because it re-generates the weights each time you call the function.
To save the weights use
Regridder.- Parameters:
source_data (
xarray.DataArray) – Source variabletarget_grid (
coecms.grid.Gridorxarray.DataArray) – Target grid / sample variableweights (
xarray.Dataset) – Pre-computed interpolation weightstranspose (bool) – If True, transpose the output so that the vertical coordinate is just before the other spatial coordinates (default: True)
cdo (path) – path of cdo executable [“cdo”]
- Returns:
xarray.DataArraywith a regridded version of the source variable