NEDAS.grid.grid_2d_base module

class NEDAS.grid.grid_2d_base.Grid2DBase(proj, x, y, bounds=None, cyclic_dim=None, distance_type='cartesian', dst_grid=None)[source]

Bases: ABC

Base class to handle 2D fields defined on regular grids or unstructured meshes.

Parameters:
  • proj (pyproj.Proj, custom func, None) – Projection function mapping from longitude,latitude to x,y coordinates. If None, a default Mercator projection will be used.

  • x (np.ndarray) – X-coordinates for each grid point.

  • y (np.ndarray) – Y-coordinates for each grid point.

  • bounds (list, optional) – Grid boundary limits, [xmin, xmax, ymin, ymax], all float numbers. If not specified, will use min/max value of the coordinates.

  • regular (bool, optional) – Whether grid is regular or unstructured. Default is True (regular grid).

  • cyclic_dim (str, optional) – Cyclic dimension(s): 'x', 'y', 'xy', or None if noncyclic.

  • distance_type (str, optional) – Type of distance functions: cartesian (default) or spherical.

  • dst_grid (GridBase, optional) – Destination grid object to convert to.

Variables:
  • proj (pyproj.Proj or custom function) – Projection function.

  • proj_name (str) – Name of the projection, empty if not available.

  • bounds (list) – Grid boundary limits [xmin, xmax, ymin, ymax].

  • mask (np.ndarray) – Mask (bool) for points that are not participating the analysis,same shape as x, default is all False.

x_elem: ndarray
y_elem: ndarray
dx: float
dy: float
Lx: float
Ly: float
regular: bool
y: ndarray
cyclic_dim: str | None
x: ndarray
mask: ndarray
property mfx

Map scaling factors in x direction (mfx), since on the projection plane dx is not exactly the distance on Earth. The mfx is defined as ratio between dx and the actual distance.

property mfy

Map scaling factors in y direction (mfy), since on the projection plane dy is not exactly the distance on Earth. The mfy is defined as ratio between dy and the actual distance.

property dst_grid

Destination grid for convert, interp, rotate_vector methods once specified a dst_grid, the setter will compute corresponding rotation_matrix and interp_weights

set_destination_grid(grid)[source]

Set method for self.dst_grid the destination Grid object to convert to.

abstractmethod find_index(x_, y_) tuple[ndarray, ndarray | None, ndarray, ndarray, ndarray][source]

Find indices of self.x, self.y corresponding to the given x_, y_.

Parameters:
  • x (float or np.ndarray) – x-coordinates of target point(s).

  • y (float or np.ndarray) – y-coordinates of target point(s).

Outputs:
inside (np.ndarray of bool): Boolean array of shape (x_.size,) indicating whether

each x_, y_ point lies inside the grid.

indices (np.ndarray of int or None): Indices of grid elements containing the input points.
  • For regular grids, this is None since vertices suffice to locate the grid box.

  • For unstructured meshes, these are indices into tri.triangles, from tri_finder.

vertices (np.ndarray of int): Array of shape (inside_size, n), where

n = 4 for regular grid boxes or n = 3 for mesh triangles. These are indices into self.x, self.y (flattened) for the vertices of the grid element that each point falls in.

in_coords (np.ndarray of float): Array of shape (inside_size, n) giving internal coordinates

of each point within the containing element. Used to compute interpolation weights.

nearest (np.ndarray of int): Array of shape (inside_size,) with indices of the grid nodes

closest to each point.

Notes

  • This function assumes self.x, self.y define either a regular or triangular grid.

  • Internal coordinates are used for interpolation and vary in dimension based on the grid type.

rotate_vectors(vec_fld)[source]

Apply the rotate_matrix to a vector field

Parameters:

vec_fld (np.array) – The input vector field, shape (2, self.x.shape)

Returns:

The vector field rotated to the dst_grid.

abstractmethod interp(fld, x=None, y=None, method='linear') ndarray[source]

Interpolation of 2D field data (fld) from one grid (self or given x,y) to another (dst_grid). This can be used for grid refining (low->high resolution) or grid thinning (high->low resolution). This also converts between different grid geometries.

Parameters:
  • fld (np.array) – Input field defined on self, should have same shape as self.x

  • x (float or np.array) – Optional; If x,y are specified, the function computes the weights and apply them to fld If x,y are None, the self.dst_grid.x,y are used. Since their interp_weights are precalculated by dst_grid.setter it will be efficient to run interp for many different input flds quickly.

  • y (float or np.array) – Optional; If x,y are specified, the function computes the weights and apply them to fld If x,y are None, the self.dst_grid.x,y are used. Since their interp_weights are precalculated by dst_grid.setter it will be efficient to run interp for many different input flds quickly.

  • method (str) – Interpolation method, can be ‘nearest’ or ‘linear’

Returns:

The interpolated field defined on the destination grid

abstractmethod coarsen(fld) ndarray[source]

Coarse-graining is sometimes needed when the dst_grid is at lower resolution than self. Since many points of self.x,y falls in one dst_grid box/element, it is better to average them to represent the field on the low-res grid, instead of interpolating only from the nearest points that will cause representation errors.

Parameters:

fld (np.array) – Input field to perform coarse-graining on, it is defined on self.

Returns:

The coarse-grained field defined on self.dst_grid.

convert(fld, is_vector=False, method='linear', coarse_grain=False)[source]

Main method to convert from self.proj, x, y to dst_grid coordinate systems:

Notes

1. if projection changes and is_vector, rotate vectors from self.proj to dst_grid.proj 2.1 interpolate fld components from self.x,y to dst_grid.x,y 2.2 if dst_grid is low-res, coarse_grain=True will perform coarse-graining

Parameters:
  • fld (np.array) – Input field to perform convertion on.

  • is_vector (bool, optional) – If False (default) the input fld is a scalar field, otherwise the input fld is a vector field.

  • method (str, optional) – Interpolation method, ‘linear’ (default) or ‘nearest’

  • coarse_grain (bool, optional) – If True, the coarse-graining will be applied using self.coarsen(). The default is False.

Returns:

The converted field defined on the destination grid self.dst_grid.

distance(ref_x, x, ref_y, y, p=2, type='cartesian')[source]

Compute distance for points (x,y) to the reference point

Parameters:
  • ref_x (float) – reference point x,y coordinates

  • ref_y (float) – reference point x,y coordinates

  • x (np.array) – points whose distance to the reference points will be computed

  • y (np.array) – points whose distance to the reference points will be computed

  • p (int, optional) – Minkowski p-norm order, default is 2

  • type (str, optional) – distance type, ‘cartesian’ (default) or ‘spherical’

Returns:

Distances between x,y and the reference point ref_x, ref_y.

property land_data[source]

prepare data to show the land area, the shp file ne_50m_coastlines is downloaded from https://www.naturalearthdata.com

property river_data[source]

prepare data to show river features

property lake_data[source]

prepare data to show lake features

llgrid_xy(dlon: float, dlat: float)[source]

Prepare a lon/lat grid to plot as reference lines

Args: - dlon, dlat: spacing of lon/lat grid in degrees

abstractmethod plot_field(ax, fld, vmin=None, vmax=None, cmap='viridis', **kwargs)[source]

Plot a scalar field using pcolor/tripcolor

Parameters:
  • ax (matplotlib.pyplot.Axes) – Axes handle for plotting

  • fld (np.array) – The scalar field for plotting

  • vmin (float, optional) – The minimum and maximum value range for the colormap, if not specified (None) the np.min, np.max of the input fld will be used.

  • vmax (float, optional) – The minimum and maximum value range for the colormap, if not specified (None) the np.min, np.max of the input fld will be used.

  • cmap (matplotlib colormap, or str, optional) – Colormap used in the plot, default is ‘viridis’

plot_vectors(ax, vec_fld, V=None, L=None, spacing=0.5, num_steps=10, linecolor='k', linewidth=1, showref=False, ref_xy=(0.95, 0.95), refcolor='w', ref_units='', showhead=True, headwidth=0.1, headlength=0.3)[source]

Plot vector fields (improved version of matplotlib quiver)

Parameters:
  • ax (matplotlib.pyplot.Axes) – Axes handle for plotting

  • vec_fld (np.array) – The vector field for plotting

  • V (float, optional) – Velocity scale, typical velocity value in vec_fld units. If not specified (None) a typical value 0.33*max(abs(vec_fld[0,:])) will be used.

  • L (float, optional) – Length scale, how long in x,y units do vectors with velocity V show in the plot If not specified (None), a typical value 0.05*self.Lx will be used.

  • spacing (float, optional) – Distance between vectors in both directions is given by spacing*L. Default is 0.5. This controls the density of vectors in the plot. You can provide a tuple (float, float) for spacings in (x, y) if you want them to be set differently.

  • num_steps (int, optional) – Default is 10. If num_steps=1, straight vectors (as in quiver) will be displayed. num_steps>1 lets you display curved trajectories, at each sub-step the velocity is re-interpolated at the new position along the trajectories. As num_steps get larger the trajectories are more detailed.

  • linecolor (str or matplotlib color, optional) – Line color for the vector lines, default is ‘k’

  • linewidth (float, optional) – Line width for the vector lines, default is 1.

  • showref (bool, optional) – If True, show a legend box with a reference vector (size L) inside. Default is False.

  • ref_xy (tuple, optional) – The x,y relative coordinates (0-1) for the reference vector box, default is upper right corner.

  • ref_color (str or matplotlib color, optional) – Background color for the reference vector box, default is ‘w’ (white).

  • ref_units (str, optional) – Units to be included in the reference vector box, default is ‘’.

  • showhead (bool, optional) – If True (default), show the arrow head of the vectors

  • headwidth (float, optional) – Width of arrow heads relative to L, default is 0.1.

  • headlength (float, optional) – Length of arrow heads relative to L, default is 0.3.

plot_scatter(ax, fld, vmin=None, vmax=None, nlevels=20, cmap='viridis', markersize=10, x=None, y=None, L=None, is_vector=False, **kwargs)[source]

Same as plot_field/vectors, but showing individual scattered points instead This is more suitable for plotting observations in space

plot_land(ax, color=None, linecolor='k', linewidth=1, showriver=False, rivercolor='c', showgrid=True, dlon=20, dlat=5)[source]

Shows the map (coastline, rivers, lakes) and lon/lat grid for reference

Parameters:
  • ax (matplotlib.pyplot.Axes) – Axes handle for plotting

  • color (matplotlib color, optional) – Face color of the landmass polygon, default is None (transparent).

  • linecolor (matplotlib color, optional) – Line color of the coastline, default is ‘k’ (black).

  • linewidth (float, optional) – Line width of the coastline, default is 1.

  • showriver (bool, optional) – If True, show the rivers and lakes over the landmass. Default is False.

  • rivercolor (matplotlib color, optional) – Color of the rivers and lakes, default is ‘c’ (cyan).

  • showgrid (bool, optional) – If True (default), show the reference lat/lon grid.

  • dlon (float, optional) – The interval of longitude lines in the reference grid. Default is 20 degrees.

  • dlat (float, optional) – The interval in latitude lines in the reference grid. Default is 5 degress.

set_xylim(ax)[source]