TfvDomain

class tfv.xarray.TfvDomain(xarray_obj)

Xarray accessor object for working with TUFLOW FV domain (spatial) netcdf files.

Extends the functionality of native xarray to add methods that assist with typical analyses.

To use this, call .tfv on an xarray dataset based on a TUFLOW FV domain file.

get_cell_index(x: float | ndarray, y: float | ndarray) ndarray

Returns the cell index(s) containing coordinate(s) x and y.

Multiple cell indexes will be returned using this command if x/y are 1D.

Parameters:
  • x ([float, np.ndarray]) – x-coordinate

  • y ([float, np.ndarray]) – y-coordinate

Returns:

index of corresponding cell containing coordinates (x,y)

Return type:

cell_index (int)

get_cell_inpolygon(polygon: ndarray) ndarray

Returns cell indexes intersected by a polygon.

The polygon should be provided as either a 2D Numpy ndarray (i.e., Nx2 array), or if the Shapely package is available, a WKT String polygon or shapely Polygon object can be provided.

Parameters:

polygon ([np.ndarray, str, shapely.geometry.Polygon]) – A single polygon feature, provided as a 2D numpy array (Nx2). If shapely is available, polygon may also be provided as a wkt string, or a shapely Polygon feature.

Returns:

indexes of cells falling inside the provided polygon.

Return type:

cell_indexes (np.ndarray)

get_curtain(polyline: ndarray, variables: str | list, time: str | int | Timestamp | slice | None = None)

Extract a 2D curtain timeseries, returned as an Xarray dataset.

Note

This is a work-in-progress method, and is not directly used in any other methods currently. If you wish to view curtain plots, please use the plot_curtain or plot_curtain_interactive methods

Parameters:
  • polyline (np.ndarray) – a Nx2 array containing the X and Y coordinates to extract the curtain over.

  • variables ([str, list]) – single or list of variables to extract

  • time ([str, pd.Timestamp, int, slice], optional) – time indexer for extraction. Defaults to the entire dataset.

Returns:

Xarray dataset object

Return type:

xr.Dataset

get_longsection(polyline: ndarray, variables: str | list, time: str | int | Timestamp | slice | None = None, datum: Literal['sigma', 'height', 'depth', 'elevation'] = 'sigma', limits: tuple = (0, 1), agg: Literal['min', 'mean', 'max'] = 'mean')

Get a 2D Longsection of model data

Parameters:
  • polyline (np.ndarray) – a Nx2 array containing the X and Y coordinates to extract the curtain over.

  • variables ([str, list]) – single or list of variables to extract

  • time ([str, pd.Timestamp, int, slice], optional) – time indexer for extraction. Defaults to the entire dataset.

  • datum (['sigma', 'height', 'depth', 'elevation'], optional) – depth-averaging datum. Defaults to ‘sigma’. Choose from height, depth, elevation or sigma.

  • limits (tuple, optional) – depth-averaging limits. Defaults to (0,1).

  • agg (['min', 'mean', 'max'], optional) – depth-averaging aggregation function. Defaults to ‘mean’. Choose from min, mean, or max.

get_profile(point: tuple | dict, time: slice | None = None, variables: list[str] | None = None)

Extract profile timeseries at a single location

Simple method to extract a profile timeseries at a single location. This returns a native Xarray dataset, and does not have the methods available using the TfvTimeseries Xarray accessor.

NOTE - This method does not currently support adding “meta” variables like “V” in lieu of hypot(V_x, V_y).

Parameters:
  • point ([tuple, dict]) – Single location to extract profile as a tuple (X,Y) or dictionary dict(loc_01=(X,Y)).

  • time ([str, pd.Timestamp, int, slice], optional) – time indexer for extraction. Defaults to the entire dataset.

  • variables (list[str], optional) – List of variables. Defaults to all variables.

Returns:

a native Xarray dataset containing the profile timeseries.

Return type:

xr.Dataset

get_sheet(variables: str | list, time: str | int | Timestamp | slice | None = None, datum: Literal['sigma', 'height', 'depth', 'elevation'] = 'sigma', limits: tuple = (0, 1), agg: Literal['min', 'mean', 'max'] = 'mean')

Extract a 2D sheet timeseries

General purpose method for extracting 2D sheet data from a TfvDomain object. This will handle dimension reduction of 3D variables (by default will average over the depth column, i.e., depth-averaged), as well as handling single or multiple timesteps or slices.

Parameters:
  • variables ([str, list]) – variables to extract. (“V” or “VDir” may be requested if “V_x” and “V_y” are present)

  • time ([str, pd.Timestamp, int, slice], optional) – time indexer for extraction. Defaults to the entire dataset.

  • datum (['sigma', 'height', 'depth', 'elevation'], optional) – depth-averaging datum. Defaults to ‘sigma’. Choose from height, depth, elevation or sigma.

  • limits (tuple, optional) – depth-averaging limits. Defaults to (0,1).

  • agg (['min', 'mean', 'max'], optional) – depth-averaging aggregation function. Defaults to ‘mean’. Choose from min, mean, or max.

Returns:

new TfvDomain object with the requested timeseries variables

Return type:

TfvDomain

get_sheet_grid(variables: str | list | None = None, time: str | int | Timestamp | slice | None = None, bbox=None, dx=None, dy=None, nx=100, ny=100, method='nearest', crs=None, datum: Literal['sigma', 'height', 'depth', 'elevation'] = 'sigma', limits: tuple = (0, 1), agg: Literal['min', 'mean', 'max'] = 'mean')

Extract a 2D sheet grid timeseries

General purpose method for extracting 2D grid data from a TfvDomain object. This will handle dimension reduction of 3D variables (by default will average over the depth column, i.e., depth-averaged), as well as handling single or multiple timesteps or slices.

This method accepts either dx/dy (grid step in meters or degrees), or nx/ny (number of grid cells in x/y). Dx/dy are given higher priority.

There are three interpolation methods available: - (DEFAULT) ‘nearest’: takes the cell centered values onto the grid. Fastest method for extraction. - ‘linear’: Linear interpolation using Scipy’s LinearNDInterpolator - ‘cubic’: Cubic interpolation using Scipy’s CloughTocher2DInterpolator

If an optional EPSG CRS is supplied (crs), the output dataset will include CRS information. Requires pyproj to be available.

Parameters:
  • variables ([str, list], optional) – list of variables to extract. Defaults to all real variables.

  • time ([str, int, pd.Timestamp, slice], optional) – time indexer for extraction. Defaults to the entire dataset.

  • bbox ([tuple, list], optional) – Bounding box of the grid (xmin, ymin, xmax, ymax). Defaults to the entire model mesh.

  • dx (float, optional) – x grid step in mesh coordinates. If not supplied, variable nx will be used.

  • dy (float, optional) – y grid step in mesh coordinates. If not supplied, variable ny will be used.

  • nx (int, optional) – number of grid steps in x. Will be ignored if dx is supplied. Defaults to 1000.

  • ny (int, optional) – number of grid steps in y. Will be ignored if dy is supplied. Defaults to 1000.

  • method (str, optional) – Grid interpolation method. Defaults to ‘nearest’.

  • crs (int, optional) – epsg code of crs for attributes. must have pyproj library available. Defaults to None.

  • datum (['sigma', 'height', 'depth', 'elevation'], optional) – depth-averaging datum. Defaults to ‘sigma’. Choose from height, depth, elevation or sigma.

  • limits (tuple, optional) – depth-averaging limits. Defaults to (0,1).

  • agg (['min', 'mean', 'max'], optional) – depth-averaging aggregation function. Defaults to ‘mean’. Choose from min, mean, or max.

Returns:

Xarray grid dataset

Return type:

xr.Dataset

get_statistics(stats: list[str], variables: list | str, time: slice | None = None, datum: str = 'sigma', limits: tuple = (0, 1), agg: str = 'mean', fillna=None, skipna=True)

Extract statistics on 2D variables.

General purpose method for extracting statistics using typical statistic functions (e.g., ‘mean’, ‘max’…).

Percentiles can be obtained using the string format ‘pX’ (e.g., for 10th and 90th: stats = [‘p10’, ‘p90’]).

This function will first call get_sheet to obtain the data for calculating statistics on. All arguments for get_sheet can be passed through to this method.

Parameters:
  • stats (list[str]) – list of statistics, e.g., [‘min’, ‘mean’, ‘p50’, ‘p95’]

  • variables ([list, str]) – variables to do statistics on

  • time ([list, slice], optional) – time indexer (e.g., slice(50) for the first 50 timesteps, or slice(‘2012-01-01’, ‘2012-02-01’))

  • datum (['sigma', 'height', 'depth', 'elevation'], optional) – depth-averaging datum. Defaults to ‘sigma’. Choose from height, depth, elevation or sigma.

  • limits (tuple, optional) – depth-averaging limits. Defaults to (0,1).

  • agg (['min', 'mean', 'max'], optional) – depth-averaging aggregation function. Defaults to ‘mean’. Choose from min, mean, or max.

  • fillna (float, optional) – Fill nan values (e.g., dried out cells) with this value before doing statistics. Defaults to None.

  • skipna (bool, optional) – Skip nan values. Defaults to True.

Returns:

new TfvDomain object with the requested timeseries variables

Return type:

TfvDomain

get_timeseries(variables: str | list, points: tuple | dict, time: str | int | Timestamp | slice | None = None, datum: Literal['sigma', 'height', 'depth', 'elevation'] = 'sigma', limits: tuple = (0, 1), agg: Literal['min', 'mean', 'max'] = 'mean')

Get timeseries at point location(s) in the model

Parameters:
  • variables ([str, list]) – variables to extract.

  • points ([tuple, dict]) – locations to extract (e.g., a tuple (x,y) or a dict {‘name’: (x,y), …})

  • time ([str, pd.Timestamp, int, slice], optional) – time indexer for extraction. Defaults to the entire dataset.

  • datum (['sigma', 'height', 'depth', 'elevation'], optional) – depth-averaging datum. Defaults to ‘sigma’. Choose from height, depth, elevation or sigma.

  • limits (tuple, optional) – depth-averaging limits. Defaults to (0,1).

  • agg (['min', 'mean', 'max'], optional) – depth-averaging aggregation function. Defaults to ‘mean’. Choose from min, mean, or max.

Returns:

A timeseries dataset in xarray format

Return type:

xr.Dataset

plot(variable: str | None = None, time: str | Timestamp | int = 0, colorbar=True, shading='patch', ax: Axes | None = None, **kwargs)

General 2D sheet plot method

By default, this function will plot the first variable and timestep.

This function is a general wrapper around the tfv.visual “Sheet” methods. Kwargs will be supplied through to the underlying matplotlib function.

Depth-averaging logic can be handled by passing through the optional keywords datum, limits, agg as required.

Several magic “variables” are available via this method including:
  • Plot bed elevation using variable ‘Zb’

  • Plot current speed or direction using either ‘V’ or ‘VDir’ respectively

Parameters:
  • variable (str, optional) – variable to plot. Defaults to alphabetical first.

  • time ([str, pd.Timestamp, int], optional) – Timestep to plot, provided as str (e.g., ‘2010-01-01’), int, Timestamp object, etc. Defaults to 0.

  • colorbar (bool, optional) – Show colorbar (best to turn off if making subplots). Defaults to True.

  • shading (str, optional) –

    Figure shading type, which changes the underlying matplotlib function. Options include:

    ”patch” that calls tfv.visual.SheetPatch and Matplotlib’s PolyCollection “interp” that calls tfv.visual.SheetPatch and Matplotlib’s TriMesh “contour” that calls tfv.visual.SheetContour and Matplotlib’s TriContourSet

    Defaults to “patch”.

  • ax (plt.Axes, optional) – Matplotlib axis to draw on. Default will create a new figure and axis.

  • kwargs (dict, optional) – Keyword arguments. These are passed to the underlying matplotlib method if not a tfv specific method (e.g., depth averaging kwargs). Common examples include: cmap, clim, levels, norm, datum, limits, agg

Returns:

tfv.visual.Sheet<X> Object, depending on the shading option.

Return type:

Sheet

plot_curtain(polyline: ndarray, variable: str | None = None, time: str | Timestamp | int = 0, ax: Axes | None = None, colorbar=True, crs=None, **kwargs)

General 2D curtain plot method

By default, this function will plot the first variable and timestep. A polyline is always required.

This function is a general wrapper around the tfv.visual.CurtainPatch method. kwargs will be supplied through to the underlying matplotlib function.

A polyline (Nx2 numpy.ndarray) needs to be supplied containing the X and Y coordinates in columns 0 and 1 respectively.

Parameters:
  • polyline (np.ndarray) – a Nx2 array containing the X and Y coordinates to extract the curtain over.

  • variable (str, optional) – variable to plot. Defaults to ‘V’ if available, otherwise the first variable alphabetically.

  • time ([str, pd.Timestamp, int], optional) – Timestep to plot, provided as str (e.g., ‘2010-01-01’), int, Timestamp object, etc. Defaults to 0.

  • ax (plt.Axes, optional) – Matplotlib axis to draw on. Default will create a new figure and axis.

  • colorbar (bool, optional) – Show colorbar (best to turn off if making subplots). Defaults to True.

  • crs (int, optional) – EPSG Code for accurate coordinate transformation for spherical models. Requires pyproj to be installed

Returns:

tfv.visual.CurtainPatch object

Return type:

CurtainPatch

plot_curtain_interactive(polyline: ndarray, variable: str, ax: Axes | None = None, vectors: bool = False, vector_kwargs={}, widget=None, **kwargs)

2D interactive matplotlib method for fast curtain viewing.

This function wraps the .plot_curtain and .plot_curtain_vector methods, with kwargs passed directly through to these methods. (see TfvDomain.plot_curtain e.g., ds.tfv.plot and TfvDomain.plot_curtain_vector e.g., ds.tfv.plot_curtain_vector).

A polyline (Nx2 numpy.ndarray) needs to be supplied containing the X and Y coordinates in columns 0 and 1 respectively.

This function requires matplotlib to be using an ipympl backend, typically in a Jupyter lab/notebook environment. Please first run %matplotlib widget before using this function.

Parameters:
  • polyline (np.ndarray) – a Nx2 array containing the X and Y coordinates to extract the curtain over.

  • variable (str) – Variable to plot

  • ax (plt.Axes, optional) – Matplotlib axis to draw on. Default will create a new figure and axis.

  • vectors ([bool, list, tuple], optional) – Flag to draw vectors. If True, the vectors will represent projected velocity (V_x, V_y projected to the curtain plane). Vertical velocity, W, will be included automatically if available in the model.

  • vector_kwargs (dict, optional) – a dictionary of kwargs that is passed directly through to the TfvDomain.plot_curtain_vector object.

  • widget (tuple, optional) – A pre-initalised ipympl widget box, generated using TfvDomain.prep_interactive_slider. This can be used to control multiple subplots using the single widget controller. Defaults to None.

  • kwargs (dict, optional) – Keyword arguments passed directly to TfvDomain.plot_curtain

plot_curtain_vector(polyline: ndarray, time: str | Timestamp | int = 0, variables: list | tuple | None = None, ax: Axes | None = None, tangential=True, **kwargs)

General 2D curtain vector plot method

This method is designed to draw velocity vectors over a curtain. If W (vertical velocity) is available in the TUFLOW FV dataset, these vectors will be scaled to show vertical motion as well. To avoid vertical velocity scaling of the vectors, specify tangential=False as well.

Note

This method accepts a variables kwarg so that custom variables can be supplied, which will be scaled with vertical velocity W if present. To avoid this behaviour, also specify tangential=False.

This function is a general wrapper around the tfv.visual.CurtainVector method. kwargs will be supplied through to the underlying matplotlib function.

A polyline (Nx2 numpy.ndarray) needs to be supplied containing the X and Y coordinates in columns 0 and 1 respectively.

Parameters:
  • polyline (np.ndarray) – a Nx2 array containing the X and Y coordinates to extract the curtain over.

  • time ([str, pd.Timestamp, int], optional) – Timestep to plot, provided as str (e.g., ‘2010-01-01’), int, Timestamp object, etc. Defaults to 0.

  • variables ([list, tuple], optional) – Variables to create vector (X-comp, Y-comp). Defaults to None.

  • ax (plt.Axes, optional) – Matplotlib axis to draw on. Default will create a new figure and axis.

  • tangential (bool, optional) – Flag to scale vectors vertically using W, if present. Defaults to True.

Returns:

tfv.visual.CurtainVector object.

Return type:

CurtainVector

plot_interactive(variable: str, ax: Axes | None = None, vectors: bool | list | tuple = False, vector_kwargs={}, widget=None, **kwargs)

2D interactive matplotlib plotting method for fast result viewing.

This function wraps the .plot and .plot_vector methods, with kwargs passed directly through to these methods. (see TfvDomain.plot e.g., ds.tfv.plot and TfvDomain.plot_vector e.g., ds.tfv.plot_vector).

This function requires matplotlib to be using an ipympl backend, typically in a Jupyter lab/notebook environment. Please first run %matplotlib widget before using this function.

Parameters:
  • variable (str) – Variable to plot

  • ax (plt.Axes, optional) – Matplotlib axis to draw on. Default will create a new figure and axis.

  • vectors ([bool, list, tuple], optional) – Flag to draw vectors. If a boolean (True) is supplied, the vectors will be velocity (V_x, V_y). A list/tuple of variable names can be supplied as required (E.g., W10_x, W10_y). Defaults to False.

  • vector_kwargs (dict, optional) – a dictionary of kwargs that is passed directly through to the TfvDomain.plot_vector object.

  • widget (tuple, optional) – A pre-initalised ipympl widget box, generated using TfvDomain.prep_interactive_slider. This can be used to control multiple subplots using the single widget controller. Defaults to None.

  • kwargs (dict, optional) – Keyword arguments passed directly to TfvDomain.plot

plot_vector(variables: list | tuple | None = None, time: str | Timestamp | int = 0, plot_type: Literal['quiver'] = 'quiver', ax: Axes | None = None, convention: Literal['cartesian', 'polar'] = 'cartesian', convention_base: Literal['north', 'east'] = 'east', convention_heading: Literal['CW', 'CCW'] = 'CCW', **kwargs)

General 2D vector plot method

Generic method to call tfv.visual’s SheetVector. This can be used to overlay vector plots on other figures. By default, this method will plot vectors using V_x and V_y to give velocity vectors, however a list/tuple of an x/y component can be provided.

kwargs passed to this function are supplied to the underlying matplotlib function (e.g., Quiver or Streamplot). The default vector scaling for velocity is usually ok; however in some cases you may need to scale the vectors (e.g., scale=100).

Vectors can also be set to a uniform length using normalised=True.

Depth-averaging logic can be handled by passing through the optional keywords datum, limits, agg as required.

Parameters:
  • variables ([list, tuple], optional) – Variables to create vector (X-comp, Y-comp). Defaults to None.

  • time ([str, pd.Timestamp, int], optional) – Timestep to plot, provided as str (e.g., ‘2010-01-01’), int, Timestamp object, etc. Defaults to 0.

  • plot_type (['quiver'], optional) – Plot type {‘quiver’}. Defaults to “quiver”.

  • ax (plt.Axes, optional) – Matplotlib axis to draw on. Default will create a new figure and axis.

  • convention (["cartesian", "polar"], optional) – Convention basis upon which to calculate vectors. Defaults to ‘cartesian’.

  • convention_base (["north", "east"]) – Base from which angles are measured from. Defaults to ‘east’

  • convention_heading (["CW", "CCW"]) – Direction which the angles are measured along. Defaults to ‘CCW’

  • kwargs (dict, optional) – Keyword arguments. These are passed to the underlying matplotlib method if not a tfv specific method (e.g., depth averaging kwargs). Common examples include: scale, normalised, datum, limits, agg.

Returns:

tfv.visual.SheetVector object.

Return type:

SheetVector

prep_interactive_slider()

Prepare an interactive ipympl widget box for controlling TfvDomain.plot_interactive

This method pre-initialises a widget box that can be used to control the interactive jupyter plotting method, and is called by default from the plot_interactive method.

To control multiple interactive plots using the one widget box, first call this method, e.g. widget=ds.tfv.prep_interactive_slider(), and then pass this widget through to the plot_interactive method.

tfv.xarray.convert_grid_to_tfv(ds, x='longitude', y='latitude', time='time', z='depth', flipz=True, spherical=True, use_tfv_naming=True)

Convert / cast an ordinary Xarray Model Dataset as a TfvDomain object

Tool to cast an typical model xarray dataset, with at minimum time, x and y, coordinates, to a TfvDomain file.

This function is dask enabled, and it is advisable to use this method with time chunked by 1 where possible. (E.g., chunks=dict(time=1))

Parameters:
  • ds (xr.Dataset) – Xarray model dataset

  • x (str, optional) – Name of the x coordinate. Defaults to ‘longitude’.

  • y (str, optional) – Name of the y coordinate. Defaults to ‘latitude’.

  • time (str, optional) – Name of the time coordinate. Defaults to ‘time’.

  • z (str, optional) – Name of the z coordinate, if available. Defaults to ‘depth’.

  • flipz (bool, optional) – Flag to flip the z-coordinate (e.g., depth to elevation). Defaults to True.

  • spherical (bool, optional) – Flag for whether the x/y coords are in degrees. Defaults to True.

  • use_tfv_naming (bool, optional) – Flag to rename common variables to standard TUFLOW FV names. Defaults to True.