Gridded

Docstrings for the Gridded class

Objects

Gridded()
Gridded._setup_grid_obj()
Gridded.make_lonLat_2d()
Gridded.set_grid_vars()
Gridded.load_domain()
Gridded.merge_domain_into_dataset()
Gridded.set_grid_ref_attr()
Gridded.get_contour_complex()
Gridded.set_timezero_depths()
Gridded.calc_bathymetry()
Gridded.subset_indices()
Gridded.find_j_i()
Gridded.find_j_i_list()
Gridded.find_j_i_domain()
Gridded.transect_indices()
Gridded.interpolate_in_space()
Gridded.interpolate_in_time()
Gridded.construct_density()
Gridded.trim_domain_size()
Gridded.copy_domain_vars_to_dataset()
Gridded.differentiate()
Gridded.apply_doodson_x0_filter()
Gridded.get_e3_from_ssh()
Gridded.harmonics_combine()
Gridded.harmonics_convert()
Gridded.time_slice()
Gridded.calculate_vertical_mask()

Gridded class

Gridded()

class Gridded(Coast):
Words to describe the NEMO class

kwargs -- define addition keyworded arguemts for domain file. E.g. ln_sco=1
if using s-scoord in an old domain file that does not carry this flag.
Gridded._setup_grid_obj()

def Gridded._setup_grid_obj(self, chunks, multiple, **kwargs):

This is a helper method to reduce the size of def __init__

Args:
                chunks: This is a setting for xarray as to whether dask (parrell processing) should be on and how it works
                multiple: falg to tell if we are loading one or more files
                **kwargs: pass direct to loaded xarray dataset

Gridded.make_lonLat_2d()

def Gridded.make_lonLat_2d(self):

Expand 1D latitude and longitude variables to 2D.

Gridded.set_grid_vars()

def Gridded.set_grid_vars(self):

Define the variables to map from the domain file to the NEMO obj

Gridded.load_domain()

def Gridded.load_domain(self, fn_domain, chunks):

Loads domain file and renames dimensions with dim_mapping_domain

Gridded.merge_domain_into_dataset()

def Gridded.merge_domain_into_dataset(self, dataset_domain):

Merge domain dataset variables into self.dataset, using grid_ref

Gridded.set_grid_ref_attr()

def Gridded.set_grid_ref_attr(self):

None

Gridded.get_contour_complex()

def Gridded.get_contour_complex(self, var, points_x, points_y, points_z, tolerance=0.2):

None

Gridded.set_timezero_depths()

def Gridded.set_timezero_depths(self, dataset_domain, calculate_bathymetry=False):

Calculates the depths at time zero (from the domain_cfg input file)
for the appropriate grid.
The depths are assigned to domain_dataset.depth_0

Args:
                dataset_domain: a complex data object.
                calculate_bathymetry: Flag that will either calculate bathymetry (true) or load it from dataset_domain file
                (false).

Gridded.calc_bathymetry()

def Gridded.calc_bathymetry(self, dataset_domain):

NEMO approach to defining bathymetry by summing scale factors at various
grid locations.
Works with z-coordinates on u- and v- faces where bathymetry is defined
at the top of the cliff, not at the bottom

Args:
                dataset_domain: a complex data object.

Gridded.subset_indices()

def Gridded.subset_indices(self):

based on transect_indices, this method looks to return all indices between the given points.
This results in a 'box' (Quadrilateral) of indices.
consequently the returned lists may have different lengths.
:param start: A lat/lon pair
:param end: A lat/lon pair
:return: list of y indices, list of x indices,

Gridded.find_j_i()

def Gridded.find_j_i(self):

A routine to find the nearest y x coordinates for a given latitude and longitude
Usage: [y,x] = find_j_i(lat=49, lon=-12)

:param lat: latitude
:param lon: longitude
:return: the y and x coordinates for the NEMO object's grid_ref, i.e. t,u,v,f,w.

Gridded.find_j_i_list()

def Gridded.find_j_i_list(self):

A routine to find the nearest y x coordinates for a list of latitude and longitude values
Usage: [y,x] = find_j_i(lat=[49,50,51], lon=[-12,-11,10])

:param lat: latitude
:param lon: longitude
:optional n_nn=1 number of nearest neighbours
:return: the j, i coordinates for the NEMO object's grid_ref, i.e. t,u,v,f,w. and a distance measure

Gridded.find_j_i_domain()

def Gridded.find_j_i_domain(self):

A routine to find the nearest y x coordinates for a given latitude and longitude
Usage: [y,x] = find_j_i_domain(lat=49, lon=-12, dataset_domain=dataset_domain)

:param lat: latitude
:param lon: longitude
:param dataset_domain: dataset domain
:return: the y and x coordinates for the grid_ref variable within the domain file

Gridded.transect_indices()

def Gridded.transect_indices(self, start, end):

This method returns the indices of a simple straight line transect between two
lat lon points defined on the NEMO object's grid_ref, i.e. t,u,v,f,w.

:type start: tuple A lat/lon pair
:type end: tuple A lat/lon pair
:return: array of y indices, array of x indices, number of indices in transect

Gridded.interpolate_in_space()
@staticmethod
def Gridded.interpolate_in_space(model_array, new_lon, new_lat, mask=None):

Interpolates a provided xarray.DataArray in space to new longitudes
and latitudes using a nearest neighbour method (BallTree).

Example Usage
----------
# Get an interpolated DataArray for temperature onto two locations
interpolated = nemo.interpolate_in_space(nemo.dataset.votemper,
                                                                                                                                                                [0,1], [45,46])
Parameters
----------
model_array (xr.DataArray): Model variable DataArray to interpolate
new_lons (1Darray): Array of longitudes (degrees) to compare with model
new_lats (1Darray): Array of latitudes (degrees) to compare with model
mask (2D array): Mask array. Where True (or 1), elements of array will
                                                not be included. For example, use to mask out land in
                                                case it ends up as the nearest point.

Returns
-------
Interpolated DataArray

Gridded.interpolate_in_time()
@staticmethod
def Gridded.interpolate_in_time(model_array, new_times, interp_method=nearest, extrapolate=True):

Interpolates a provided xarray.DataArray in time to new python
datetimes using a specified scipy.interpolate method.

Example Useage
----------
# Get an interpolated DataArray for temperature onto altimetry times
new_times = altimetry.dataset.time
interpolated = nemo.interpolate_in_space(nemo.dataset.votemper,
                                                                                                                                                                new_times)
Parameters
----------
model_array (xr.DataArray): Model variable DataArray to interpolate
new_times (array): New times to interpolate to (array of datetimes)
interp_method (str): Interpolation method

Returns
-------
Interpolated DataArray

Gridded.construct_density()

def Gridded.construct_density(self, eos=EOS10, rhobar=False, Zd_mask=unknown, CT_AS=False, pot_dens=False, Tbar=True, Sbar=True):

                Constructs the in-situ density using the salinity, temperture and
                depth_0 fields and adds a density attribute to the t-grid dataset

                Requirements: The supplied t-grid dataset must contain the
                Practical Salinity and the Potential Temperature variables. The depth_0
                field must also be supplied. The GSW package is used to calculate
                The Absolute Pressure, Absolute Salinity and Conservate Temperature.

                Note that currently density can only be constructed using the EOS10
                equation of state.

Parameters
----------
eos : equation of state, optional
                DESCRIPTION. The default is 'EOS10'.

rhobar : Calculate density with depth mean T and S
                DESCRIPTION. The default is 'False'.
Zd_mask : Provide a 3D mask for rhobar calculation
                Calculate using calculate_vertical_mask
                DESCRIPTION. The default is empty.

CT_AS : Conservative Temperature and Absolute Salinity already provided
                DESCRIPTION. The default is 'False'.
pot_dens :Calculation at zero pressure
                DESCRIPTION. The default is 'False'.
Tbar and Sbar : If rhobar is True then these can be switch to False to allow one component to
                                                                remain depth varying. So Tbar=Flase gives temperature component, Sbar=Flase gives Salinity component
                DESCRIPTION. The default is 'True'.

Returns
-------
None.
adds attribute NEMO.dataset.density

Gridded.trim_domain_size()

def Gridded.trim_domain_size(self, dataset_domain):

Trim the domain variables if the dataset object is a spatial subset

Note: This breaks if the SW & NW corner values of nav_lat and nav_lon
are masked, as can happen if on land...

Gridded.copy_domain_vars_to_dataset()

def Gridded.copy_domain_vars_to_dataset(self, dataset_domain, grid_vars):

Map the domain coordinates and metric variables to the dataset object.
Expects the source and target DataArrays to be same sizes.

Gridded.differentiate()

def Gridded.differentiate(self, in_var_str, config_path=None, dim=z_dim, out_var_str=None, out_obj=None):

Derivatives are computed in x_dim, y_dim, z_dim (or i,j,k) directions
wrt lambda, phi, or z coordinates (with scale factor in metres not degrees).

Derivatives are calculated using the approach adopted in NEMO,
specifically using the 1st order accurate central difference
approximation. For reference see section 3.1.2 (sec. Discrete operators)
of the NEMO v4 Handbook.

Currently the method does not accomodate all possible eventualities. It
covers:
1) d(grid_t)/dz --> grid_w

Returns an object (with the appropriate target grid_ref) containing
derivative (out_var_str) as xr.DataArray

This is hardwired to expect:
1) depth_0 and e3_0 fields exist
2) xr.DataArrays are 4D
3) self.filename_domain if out_obj not specified
4) If out_obj is not specified, one is built that is the size of
                self.filename_domain. I.e. automatic subsetting of out_obj is not
                supported.

Example usage:
--------------
# Initialise DataArrays
nemo_t = coast.NEMO( fn_data, fn_domain, grid_ref='t-grid' )
# Compute dT/dz
nemo_w_1 = nemo_t.differentiate( 'temperature', dim='z_dim' )

# For f(z)=-z. Compute df/dz = -1. Surface value is set to zero
nemo_t.dataset['depth4D'],_ = xr.broadcast( nemo_t.dataset['depth_0'], nemo_t.dataset['temperature'] )
nemo_w_4 = nemo_t.differentiate( 'depth4D', dim='z_dim', out_var_str='dzdz' )

Provide an existing target NEMO object and target variable name:
nemo_w_1 = nemo_t.differentiate( 'temperature', dim='z_dim', out_var_str='dTdz', out_obj=nemo_w_1 )


Parameters
----------
in_var_str : str, name of variable to differentiate
config_path : str, path to the w grid config file
dim : str, dimension to operate over. E.g. {'z_dim', 'y_dim', 'x_dim', 't_dim'}
out_var_str : str, (optional) name of the target xr.DataArray
out_obj : exiting NEMO obj to store xr.DataArray (optional)

Gridded.apply_doodson_x0_filter()

def Gridded.apply_doodson_x0_filter(self, var_str):

Applies Doodson X0 filter to a variable.

Input variable is expected to be hourly.
Output is saved back to original dataset as {var_str}_dxo

!!WARNING: Will load in entire variable to memory. If dataset large,
then subset before using this method or ensure you have enough free
RAM to hold the variable (twice).

DB:: Currently not tested in unit_test.py

Gridded.get_e3_from_ssh()
@staticmethod
def Gridded.get_e3_from_ssh(nemo_t, e3t=True, e3u=False, e3v=False, e3f=False, e3w=False, dom_fn=None):

Where the model has been run with a nonlinear free surface
and z* variable volumne (ln_vvl_zstar=True) then the vertical scale factors
will vary in time (and space). This function will compute the vertical
scale factors e3t, e3u, e3v, e3f and e3w by using the sea surface height
field (ssh variable) and initial scale factors from the domain_cfg file.
The vertical scale factors will be computed at the same model time as the
ssh and if the ssh field is averaged in time then the scale factors will
also be time averages.

A t-grid NEMO object containing the ssh variable must be passed in. Either
the domain_cfg path must have been passed in as an argument when the NEMO
object was created or it must be passed in here using the dom_fn argument.

e.g. e3t,e3v,e3f = coast.NEMO.get_e3_from_ssh(nemo_t,true,false,true,true,false)

Parameters
----------
nemo_t : (Coast.NEMO), NEMO object on the t-grid containing the ssh variable
e3t : (boolean), true if e3t is to be returned. Default True.
e3u : (boolean), true if e3u is to be returned. Default False.
e3v : (boolean), true if e3v is to be returned. Default False.
e3f : (boolean), true if e3f is to be returned. Default False.
e3w : (boolean), true if e3w is to be returned. Default False.
dom_fn : (str), Optional, path to domain_cfg file.

Returns
-------
Tuple of xarray.DataArrays
(e3t, e3u, e3v, e3f, e3w)
Only those requested will be returned, but the ordering is always the same.

Gridded.harmonics_combine()

def Gridded.harmonics_combine(self, constituents, components=unknown):

Contains a new NEMO object containing combined harmonic information
from the original object.

NEMO saves harmonics to individual variables such as M2x, M2y... etc.
This routine will combine these variables (depending on constituents)
into a single data array. This new array will have the new dimension
'constituent' and a new data coordinate 'constituent_name'.

Parameters
----------
constituents : List of strings containing constituent names to combine.
                                                The case of these strings should match that used in
                                                NEMO output. If a constituent is not found, no problem,
                                                it just won't be in the combined dataset.
components : List of strings containing harmonic components to look
                                                for. By default, this looks for the complex components
                                                'x' and 'y'. E.g. if constituents = ['M2'] and
                                                components is left as default, then the routine looks
                                                for ['M2x', and 'M2y'].

Returns
-------
NEMO() object, containing combined harmonic variables in a new dataset.

Gridded.harmonics_convert()

def Gridded.harmonics_convert(self, direction=cart2polar, x_var=harmonic_x, y_var=harmonic_y, a_var=harmonic_a, g_var=harmonic_g, degrees=True):

Converts NEMO harmonics from cartesian to polar or vice versa.
Make sure this NEMO object contains combined harmonic variables
obtained using harmonics_combine().

*Note:

Parameters
----------
direction (str) : Choose 'cart2polar' or 'polar2cart'. If 'cart2polar'
                                                                Then will look for variables x_var and y_var. If
                                                                polar2cart, will look for a_var (amplitude) and
                                                                g_var (phase).
x_var (str)                : Harmonic x variable name in dataset (or output)
                                                                default = 'harmonic_x'.
y_var (str)                : Harmonic y variable name in dataset (or output)
                                                                default = 'harmonic_y'.
a_var (str)                : Harmonic amplitude variable name in dataset (or output)
                                                                default = 'harmonic_a'.
g_var (str)                : Harmonic phase variable name in dataset (or output)
                                                                default = 'harmonic_g'.
degrees (bool) : Whether input/output phase are/will be in degrees.
                                                                Default is True.

Returns
-------
Modifies NEMO() dataset in place. New variables added.

Gridded.time_slice()

def Gridded.time_slice(self, date0, date1):

Return new Gridded object, indexed between dates date0 and date1

Gridded.calculate_vertical_mask()

def Gridded.calculate_vertical_mask(self, Zmax):

Calculates a 3D mask to a specified level Zmax. 1 for sea; 0 for below sea bed
and linearly ramped for last level


Last modified November 23, 2022: Updated docstrings from coast repo. (9daee18)