mom6_forge package
Submodules
mom6_forge.chl module
- mom6_forge.chl.gen_chl_empty_dataset(output_path, lon, lat, fill_value=-1e+34, no_leap=True)
Generate an empty NetCDF dataset for SeaWiFS chlorophyll climatology and save it to disk.
This function assumes a NO_LEAP calendar.
This function creates a synthetic xarray dataset with a CHL_A variable (monthly mean chlorophyll) initialized entirely with fill values. The dataset uses the provided longitude and latitude arrays to define the spatial grid and includes a fixed climatological time axis.
- Parameters:
output_path (str or Path) – Path to save the output NetCDF file.
lon (array-like) – 1D array of longitude values (in degrees east) defining the spatial X-axis.
lat (array-like) – 1D array of latitude values (in degrees north) defining the spatial Y-axis.
- Returns:
ds – The generated empty dataset containing the CHL_A variable and coordinate metadata.
- Return type:
xarray.Dataset
Notes
The CHL_A variable is filled with the placeholder value -1e34.
The TIME dimension is fixed and marked as unlimited in the NetCDF file.
TIME values represent the approximate midpoint of each month in a climatological year.
This dataset structure mimics that of SeaWiFS chlorophyll climatology products and is intended as a template or placeholder.
- mom6_forge.chl.interpolate_and_fill_seawifs(grid: Grid, topo: Topo, processed_seawifs_path: Path | str, output_path: Path | str = None)
Interpolate and fill SeaWiFS chlorophyll data to a model grid and save to NetCDF.
This function assumes a NO_LEAP calendar.
This function takes gridded SeaWiFS chlorophyll data, interpolates it onto a super-sampled model grid, applies ocean masking, fills missing values, and writes the processed data to a NetCDF file. Global attributes are added to the output dataset to document provenance and authorship.
- Parameters:
grid (Grid) – Model grid object containing tracer longitude and latitude arrays (grid.tlon, grid.tlat) and other grid arrays (grid.qlon, grid.qlat, grid.nx, grid.ny).
topo (Topo) – Topography object containing the ocean mask (topo.tmask).
processed_seawifs_path (Path or str) – Path to the preprocessed SeaWiFS chlorophyll dataset.
output_path (Path or str, optional) – Path to save the output NetCDF file. If not provided, it is created in the same directory as processed_seawifs_path using the grid name.
- Returns:
A dataset containing the interpolated and filled chlorophyll concentration with appropriate global attributes and coordinate variables.
- Return type:
xarray.Dataset
mom6_forge.command_manager module
- class mom6_forge.command_manager.CommandManager(directory, command_registry)
Bases:
ABC- add_to_history(sha, command_data: str)
Ensure the command unoffical history file exists (true history is generated from commit messages), append a line to it.
- commit(command, cmd_type: CommandType, command_message=None)
Add a command to the history.
- create_branch(branch)
- abstractmethod execute(cmd, message=None)
Execute a command, push it onto the undo stack, and clear the redo stack.
- get_current_branch()
- get_tag_names()
- list_branches()
- load_history()
Load the history dictionary from the history file.
- parse_commit_message(sha)
Parse a commit message to extract command type and data. Expected format: “<CommandType>”
- abstractmethod redo()
Redo the last undone command.
- touch_history()
make a change to the history for commit purposes
- abstractmethod undo()
Undo the last command.
- write_history()
Write the current history dictionary to the history file.
- class mom6_forge.command_manager.CommandType(*values)
Bases:
EnumEnumeration for command types in the history.
- COMMAND = 'COMMAND'
- INITIAL = 'INITIAL'
- REDO = 'REDO'
- UNDO = 'UNDO'
- class mom6_forge.command_manager.TopoCommandManager(topo, command_registry)
Bases:
CommandManagerThe unique part here is we need to handle the topo object seperately!
- checkout(branch_name)
Switch to a branch, loading the topo state from that branch.
- execute(cmd, cmd_type: CommandType = CommandType.COMMAND, message=None)
Execute a command object. If it’s a user edit, push to history and clear redo. For system commands (undo, redo, save, load, reset), the command object handles everything.
- reapply_changes()
Reapply all changes from history to the topo.
- redo(check_only=False)
Redo the last undone command.
- reset()
Reset the bathymetry to its original state by replaying commands from end to beginning.
- save(file_name='topog.nc')
Save the current topo state, and make history permanent as a git tag with the given name.
- tag(tag_name)
Tag the current state of the topo.
- undo(check_only=False)
Undo the last command.
mom6_forge.edit_command module
- class mom6_forge.edit_command.ClearMaskCommand(topo, message='Clear Manual Mask')
Bases:
EditCommandClears the manual mask, reverting to depth_raw_mask derived mask.
- classmethod deserialize(data)
Deserialize the command from a dictionary format.
Parameters: Dictionary containing serialized command data. Returns an instance of the command class.
Notes: Derived classes should override this method to reconstruct their specific attributes. The input dictionary should match the output of the corresponding serialize method.
- classmethod reverse_deserialize(data)
Undo a clear by restoring the old mask via MaskEditCommand.
- serialize()
Serialize the command to a dictionary format suitable for JSON encoding.
Returns a dictionary with the command type and necessary data.
Notes: Derived classes should override this method to include their specific attributes. Output should be compatible with corresponding deserialize method.
- class mom6_forge.edit_command.DepthEditCommand(topo, affected_indices, new_values, old_values=None, message='Depth Edit')
Bases:
EditCommandDefine any edit that affects one or more elements of an array
- classmethod deserialize(data)
Deserialize the command from a dictionary format.
Parameters: Dictionary containing serialized command data. Returns an instance of the command class.
Notes: Derived classes should override this method to reconstruct their specific attributes. The input dictionary should match the output of the corresponding serialize method.
- classmethod reverse_deserialize(data)
Deserialize a command for undoing purposes.
This method creates a command instance that can revert the changes made by the original command.
Parameters: Dictionary containing serialized command data. Returns an instance of the command class configured for undoing the original action.
- serialize()
Serialize the command to a dictionary format suitable for JSON encoding.
Returns a dictionary with the command type and necessary data.
Notes: Derived classes should override this method to include their specific attributes. Output should be compatible with corresponding deserialize method.
- class mom6_forge.edit_command.EditCommand
Bases:
ABC- abstractmethod classmethod deserialize(data: dict)
Deserialize the command from a dictionary format.
Parameters: Dictionary containing serialized command data. Returns an instance of the command class.
Notes: Derived classes should override this method to reconstruct their specific attributes. The input dictionary should match the output of the corresponding serialize method.
- abstractmethod classmethod reverse_deserialize(data: dict)
Deserialize a command for undoing purposes.
This method creates a command instance that can revert the changes made by the original command.
Parameters: Dictionary containing serialized command data. Returns an instance of the command class configured for undoing the original action.
- abstractmethod serialize() dict
Serialize the command to a dictionary format suitable for JSON encoding.
Returns a dictionary with the command type and necessary data.
Notes: Derived classes should override this method to include their specific attributes. Output should be compatible with corresponding deserialize method.
- class mom6_forge.edit_command.MaskEditCommand(topo, affected_indices, new_values, old_values=None, message='Mask Edit')
Bases:
EditCommandDefine any edit that affects one or more elements of the binary ocean/land mask array
- classmethod deserialize(data)
Deserialize the command from a dictionary format.
Parameters: Dictionary containing serialized command data. Returns an instance of the command class.
Notes: Derived classes should override this method to reconstruct their specific attributes. The input dictionary should match the output of the corresponding serialize method.
- classmethod reverse_deserialize(data)
Deserialize a command for undoing purposes.
This method creates a command instance that can revert the changes made by the original command.
Parameters: Dictionary containing serialized command data. Returns an instance of the command class configured for undoing the original action.
- serialize()
Serialize the command to a dictionary format suitable for JSON encoding.
Returns a dictionary with the command type and necessary data.
Notes: Derived classes should override this method to include their specific attributes. Output should be compatible with corresponding deserialize method.
- class mom6_forge.edit_command.MinDepthEditCommand(topo, attr, new_value, old_value=None, message='Min Depth Edit')
Bases:
EditCommandDefine any edit that affects a single scalar attribute of an object
- classmethod deserialize(data)
Deserialize the command from a dictionary format.
Parameters: Dictionary containing serialized command data. Returns an instance of the command class.
Notes: Derived classes should override this method to reconstruct their specific attributes. The input dictionary should match the output of the corresponding serialize method.
- classmethod reverse_deserialize(data)
Deserialize a command for undoing purposes.
This method creates a command instance that can revert the changes made by the original command.
Parameters: Dictionary containing serialized command data. Returns an instance of the command class configured for undoing the original action.
- serialize()
Serialize the command to a dictionary format suitable for JSON encoding.
Returns a dictionary with the command type and necessary data.
Notes: Derived classes should override this method to include their specific attributes. Output should be compatible with corresponding deserialize method.
- mom6_forge.edit_command.register_command(cls)
- mom6_forge.edit_command.to_native(val)
- mom6_forge.edit_command.to_native_tuple(t)
mom6_forge.git_utils module
- mom6_forge.git_utils.get_domain_dir(grid, base_dir='TopoLibrary')
Returns a unique directory path for a given grid object. Works for both rectilinear and curvilinear grids.
- mom6_forge.git_utils.get_repo(path)
Ensure a git repository exists at the given path. If not, initialize one. Returns the repo object.
mom6_forge.grid module
- class mom6_forge.grid.Grid(lenx: float, leny: float, nx: int = None, ny: int = None, resolution: float | None = None, xstart: float = 0.0, ystart: float | None = None, cyclic_x: bool = False, name: str | None = None, type: str = 'uniform_spherical')
Bases:
objectHorizontal MOM6 grid. The first step of constructing a MOM6 grid within the CESM simpler models framework is to create a Grid instance.
- tlon
array of t-grid longitudes
- Type:
xr.DataArray
- tlat
array of t-grid latitudes
- Type:
xr.DataArray
- ulon
array of u-grid longitudes
- Type:
xr.DataArray
- ulat
array of u-grid latitudes
- Type:
xr.DataArray
- vlon
array of v-grid longitudes
- Type:
xr.DataArray
- vlat
array of v-grid latitudes
- Type:
xr.DataArray
- qlon
array of corner longitudes
- Type:
xr.DataArray
- qlat
array of corner latitudes
- Type:
xr.DataArray
- dxt
x-distance between U points, centered at t
- Type:
xr.DataArray
- dyt
y-distance between V points, centered at t
- Type:
xr.DataArray
- dxCv
x-distance between q points, centered at v
- Type:
xr.DataArray
- dyCu
y-distance between q points, centered at u
- Type:
xr.DataArray
- dxCu
x-distance between y points, centered at u
- Type:
xr.DataArray
- dyCv
y-distance between t points, centered at v
- Type:
xr.DataArray
- angle
angle grid makes with latitude line
- Type:
xr.DataArray
- angle_q
angle q-grid makes with latitude line
- Type:
xr.DataArray
- tarea
T-cell area
- Type:
xr.DataArray
Grid instance constructor.
- Parameters:
lenx (float) – grid length in x direction, e.g., 360.0 (degrees)
leny (float) – grid length in y direction, e.g., 160.0 (degrees)
nx (int, optional) – Number of grid points in x direction
ny (int, optional) – Number of grid points in y direction
resolution (float, optional) – grid resolution in degrees. If provided, the grid dimensions are computed based on the resolution: nx = int(lenx / resolution) and ny = int(leny / resolution)
xstart (float, optional) – starting x coordinate. 0.0 by default.
ystart (float, optional) – starting y coordinate. -0.5*leny by default.
cyclic_x (bool, optional) – flag to make the grid cyclic in x direction. False by default.
name (str, optional) – name of the grid. None by default.
type (str, optional) – If not specified, creates an uniform_degree grid. Options are uniform_degree or rectilinear_cartesian
- static check_supergrid(supergrid: Dataset) None
Check if a given supergrid contains the necessary attributes and has consistent units.
- Parameters:
supergrid (xarray.Dataset) – MOM6 Supergrid dataset
- classmethod from_supergrid(path: str, name: str | None = None) Grid
Create a Grid instance from a supergrid file.
- Parameters:
path (str) – Path to the supergrid file to be written
name (str, optional) – Name of the new grid. If provided, it will be used as the name of the grid. If not provided, the name will be derived from the file name.
- Returns:
The Grid instance created from the supergrid file.
- Return type:
- classmethod from_supergrid_ds(ds: Dataset, name: str | None = None) Grid
Create a Grid instance from a supergrid file.
- Parameters:
ds (xr.Dataset) – xarray Dataset of the supergrid file to be written
name (str, optional) – Name of the new grid. If provided, it will be used as the name of the grid.
- Returns:
The Grid instance created from the supergrid file.
- Return type:
- classmethod get_bounding_boxes_of_rectangular_grid(hgrid)
Extract lat/lon bounding boxes for each edge of a rectangular regional MOM6 grid. This function is used when subsetting global datasets (e.g. GLORYS) down to the lat/lon ranges required for efficient regridding:
north, south, east, west boundaries
Entire domain initial condition files
- Parameters:
hgrid (Grid or xarray.Dataset in the supergrid format)
- Returns:
- A dictionary containing bounding boxes for:
”east”
”west”
”north”
”south”
”ic” (full domain for initial conditions)
- Return type:
dict
- get_indices(tlat: float, tlon: float) tuple[int, int]
Get the i, j indices of a given tlat and tlon pair.
- Parameters:
tlat (float) – The latitude value.
tlon (float) – The longitude value.
- Returns:
The j, i indices of the given tlat and tlon pair.
- Return type:
Tuple[int, int]
- static is_cyclic_x(supergrid) bool
Check if a given supergrid x coordinate array is cyclic along the x-axis.
- Parameters:
supergrid (xr.DataArray or np.array or SupergridBase) – Supergrid to check for cyclic x.
- is_rectangular(rtol=0.001) bool
Check if the grid is a rectangular lat-lon grid by comparing the first and last rows and columns of the tlon and tlat arrays.
- static is_tripolar(supergrid) bool
Check if the given supergrid x coordinates form a tripolar grid.
- Parameters:
supergrid (xr.DataArray or np.array or SupergridBase) – Supergrid to check if tripolar.
- property kdtree: cKDTree
KDTree for fast nearest neighbor search.
- property lenx: float
Length of the grid in the x-direction.
- property leny: float
Length of the grid in the y-direction.
- property name: str
Name of the grid.
- property nx
Number of cells in x-direction.
- property ny
Number of cells in y-direction.
- plot(property_name)
Plot a given grid property using cartopy. Warning: cartopy module must be installed seperately
- Parameters:
property_name (str) – The name of the grid property to plot, e.g., ‘tlat’.
- plot_cross_section(property_name, iy=None, ix=None)
Plot the cross-section of a given grid metric.
- Parameters:
property_name (str) – The name of the grid property to plot, e.g., ‘tlat’.
iy (int) – y-index of the cross section
ix (int) – x-inted of the cross section
- classmethod subgrid_from_supergrid(path: str, llc: tuple[float, float], urc: tuple[float, float], name: str) Grid
Create a Grid instance from a subset of a supergrid file.
- Parameters:
path (str) – Path to the full supergrid file to be carved out.
llc (tuple[float, float]) – Lower left corner coordinates (lat, lon) of the subdomain to extract
urc (tuple[float, float]) – Upper right corner coordinates (lat, lon) of the subset to extract
name (str) – Name of the subgrid
- Returns:
The Grid instance created from the supergrid file.
- Return type:
- property supergrid: SupergridBase
MOM6 supergrid contains the grid metrics and the areas at twice the nominal resolution (by default) of the actual computational grid.
- update_supergrid(xdat: array, ydat: array) None
Update the supergrid x and y coordinates. Running this method also updates the nominal grid coordinates and metrics.
- Parameters:
xdat (np.array) – 2-dimensional array of the new x coordinates.
ydat (np.array) – 2-dimensional array of the new y coordinates.
- write_supergrid(path: str | None = None, author: str | None = None) None
Write supergrid to a netcdf file. The supergrid file is to be read in by MOM6 during runtime.
- Parameters:
path (str, optional) – Path to the supergrid file to be written.
author (str, optional) – Name of the author. If provided, the name will appear in files as metadata.
mom6_forge.grid_creator module
- class mom6_forge.grid_creator.GridCreator(*args: t.Any, **kwargs: t.Any)
Bases:
HBoxPublic constructor
- construct_control_panel()
- construct_observances()
- load_grid(b=None)
- plot_grid()
- refresh_commit_dropdown()
- reset_grid(b=None)
- save_grid(_btn=None)
- sync_sliders_to_grid()
- update_commit_details(change=None)
mom6_forge.mapping module
- mom6_forge.mapping.compute_smoothing_weights(mesh_ds, rmax, fold=1.0, xv_data=None, yv_data=None)
Compute smoothing weights for a given mesh dataset, using a radius in kilometers.
- Parameters:
mesh_ds (xr.Dataset) – The ESMF mesh dataset.
rmax (float) – Maximum distance for smoothing weights, in kilometers.
fold (float) – Fold factor (km) determining the strength of smoothing based on distance.
xv_data (np.ndarray, optional) – The x-coordinates of the vertices. If not provided, they will be computed from the mesh dataset.
yv_data (np.ndarray, optional) – The y-coordinates of the vertices. If not provided, they will be computed from the mesh dataset.
- Returns:
weights – The computed smoothing weights in coordinate (COO) format.
- Return type:
scipy.sparse.coo_matrix
- mom6_forge.mapping.extract_coastline_mask(horiz_grid)
Given a 2D horizontal grid dataset, extract the coastline mask.
- Parameters:
horiz_grid (xr.Dataset) – A 2D horizontal grid dataset containing the longitude, latitude, and mask of the grid points. This dataset may be obtained from the grid_from_esmf_mesh function by passing an ESMF mesh.
- Returns:
da_coastline_mask – A 2D DataArray containing the coastline mask.
- Return type:
xr.DataArray
- mom6_forge.mapping.gen_rof_maps(rof_mesh_path, ocn_mesh_path, output_dir, mapping_file_prefix, rmax=None, fold=None)
Generate (1) nearest neighbor and (2) smoothed nearest neighbor mapping files from a runoff mesh to an ocean mesh.
- Parameters:
rof_mesh_path (str or Path) – Path to the ROF ESMF mesh file.
ocn_mesh_path (str or Path) – Path to the OCN ESMF mesh file.
output_dir (str or Path) – Directory where the mapping files will be saved.
mapping_file_prefix (str) – Prefix for the mapping files to be created. Example: “rx1_to_t232” will create files “rx1_to_t232_nn.nc” and “rx1_to_t232_nnsm.nc”.
rmax (float, optional) – Maximum distance for smoothing weights, in kilometers. If None, no smoothing is applied.
fold (float, optional) – Fold factor (km) determining the strength of smoothing based on distance. If None, no smoothing is applied.
- mom6_forge.mapping.generate_ESMF_map_via_esmpy(src_mesh_path, dst_mesh_path, mapping_file, method, area_normalization)
Generate an ESMF mapping file using esmpy.
- Parameters:
src_mesh_path (str or Path) – Path to the source ESMF mesh file.
dst_mesh_path (str or Path) – Path to the destination ESMF mesh file.
mapping_file (str or Path) – Path to the output ESMF mapping file to be created.
method (str) – Regridding method to use. Options are ‘nearest_d2s’, ‘nearest_s2d’, ‘bilinear’, ‘conservative’.
area_normalization (bool) – Whether to apply area normalization to the weights.
- mom6_forge.mapping.generate_ESMF_map_via_xesmf(src_mesh_path, dst_mesh_path, mapping_file, method, area_normalization=False, map_overlap=True)
Generate an ESMF mapping file using xesmf.
- Parameters:
src_mesh_path (str or Path) – Path to the source ESMF mesh file.
dst_mesh_path (str or Path) – Path to the destination ESMF mesh file.
mapping_file (str or Path) – Path to the output ESMF mapping file to be created.
method (str) – Regridding method to use. Options are ‘nearest_d2s’, ‘nearest_s2d’, ‘bilinear’, ‘conservative’.
area_normalization (bool) – Whether to apply area normalization to the weights.
map_overlap (bool) – If True, only map the overlapping area between the source and destination meshes, i.e., zero out the mask in the source mesh that falls outside the rectangle defined by the destination mesh.
- mom6_forge.mapping.get_nn_map_filepath(mapping_file_prefix, output_dir)
Get the standardized runoff to ocean nearest neighbor mapping file path based on the prefix and output directory.
- Parameters:
mapping_file_prefix (str) – Prefix for the mapping files to be created.
output_dir (str or Path) – Directory where the mapping files will be saved.
- Returns:
nn_map_filepath – Path to the nearest neighbor mapping file.
- Return type:
Path
- mom6_forge.mapping.get_smoothed_map_filepath(mapping_file_prefix, output_dir, rmax, fold)
Get the standardized runoff to ocean smoothed nearest neighbor mapping file name based on the prefix, output directory, rmax, and fold.
- Parameters:
mapping_file_prefix (str) – Prefix for the mapping files to be created.
output_dir (str or Path) – Directory where the mapping files will be saved.
rmax (float) – Maximum distance for smoothing weights, in kilometers.
fold (float) – Fold factor (km) determining the strength of smoothing based on distance.
- Returns:
nnsm_map_filepath – Path to the smoothed nearest neighbor mapping file.
- Return type:
Path
- mom6_forge.mapping.get_suggested_smoothing_params(ocn_mesh_path)
Given an ocean mesh path, suggest RMAX and FOLD values for smoothed runoff to ocean mapping generation.
- Parameters:
rof_mesh_path (str or Path) – Path to the runoff ESMF mesh file.
ocn_mesh_path (str or Path) – Path to the ocean ESMF mesh file.
- Returns:
suggested_rmax (int) – Suggested RMAX value in kilometers.
suggested_fold (int) – Suggested FOLD value in kilometers.
- mom6_forge.mapping.grid_from_esmf_mesh(mesh: Dataset | str | Path) Grid
Given an ESMF mesh where the grid metrics are stored in 1D (flattened) arrays, compute the dimensions of the 2D grid and return a 2D horizontal grid dataset containing the longitude, latitude, and mask of the grid points which are all that is needed to create a regridder.
- Parameters:
mesh (xr.Dataset or str or Path) – The ESMF mesh dataset or the path to the mesh file.
- Returns:
ds – A 2D horizontal grid dataset containing the longitude, latitude, and mask of the grid points.
- Return type:
xr.Dataset
- mom6_forge.mapping.main(args)
- mom6_forge.mapping.rank()
- mom6_forge.mapping.regrid_dataset_via_xesmf(input_dataset, output_dataset, regridding_method=None, write_to_file=True, output_path=PosixPath('regridded_dataset.nc'))
Regrids the dataset given
input_datasetwhich contains the original dataset andoutput_datasetwhich is a template for the regridded product. Uses xESMF for regridding.- Parameters:
input_dataset (Xarray Dataset) – original dataset with proper metadata and structure for ESMF regridding.
output_dataset (Xarray Dataset) – Template for the regridded dataset regridding_method: (Optional[str]) The type of regridding method to use. Defaults to bilinear
write_to_file (Optional[bool]) – Files saved to
output_dirDefaults toTrue. Must be set to true if using manual regridding methods with ESMF_regrid.
- Return type:
regridded_dataset (Xarray.Dataset)
- mom6_forge.mapping.sum_weights(regridder, stride=1)
- mom6_forge.mapping.write_mapping_file(src_mesh, dst_mesh, filename, weights=None, weights_esmpy=None, weights_coo=None, area_normalization=False)
Based on a given source mesh, destination mesh, and weights, write out an ESMF map file.
- Parameters:
src_mesh (str, xr.Dataset) – ESMF mesh object or path to the source ESMF mesh file.
dst_mesh (str, xr.Dataset) – ESMF mesh object or path to the destination ESMF mesh file.
filename (str) – Path to the output ESMF map file.
weights (xr.DataArray) – xESMF-generated weights to be used for the regridding.
weights_esmpy – esmpy-generated weights to be used for the regridding.
weights_coo (scipy.sparse.coo_matrix) – COO format sparse matrix containing the weights.
regrid_method (str, optional) – Regridding method, by default ‘bilinear’.
area_normalization (bool, optional) – Whether to multiply the weights by (area_source / area_destination), by default False.
- Return type:
None
mom6_forge.plotting module
- mom6_forge.plotting.plot_esmf_mesh(mesh_ds, field=None, cells_to_mark=None, figsize=None, xlim=None, ylim=None, index_axes=False, **kwargs)
Plot the mesh using matplotlib.
- Parameters:
mesh_ds (xarray.Dataset) – The ESMF mesh dataset containing the mesh information.
field (np.ndarray, optional) – The field to plot on the mesh. If None, the mesh mask will be plotted.
cells_to_mark (dict of {int: str}) – A dictionary where keys are (flattened) cell indices and values are colors to mark the cells.
figsize (tuple, optional) – The size of the figure. Default is (10, 8).
xlim (tuple, optional) – The x-axis limits. Default is None.
ylim (tuple, optional) – The y-axis limits. Default is None.
index_axes (bool, optional) – If True, the mesh will be indexed from 0 to nx-1 and 0 to ny-1. If False, geographical coordinates will be used as axes. Default is False.
**kwargs (keyword arguments) – Additional keyword arguments to pass to the plot function.
- Returns:
The axes with the plotted mesh.
- Return type:
matplotlib.axes.Axes
mom6_forge.topo module
- class mom6_forge.topo.Topo(grid, min_depth, version_control_dir='TopoLibrary', git=True)
Bases:
objectBathymetry Generator for MOM6 grids (mom6_forge.grid.Grid).
MOM6 Simpler Models bathymetry constructor.
- Parameters:
grid (mom6_forge.grid.Grid) – horizontal grid instance for which the bathymetry is to be created.
min_depth (float) – Minimum water column depth. Columns with shallow depths are to be masked out.
version_control_dir (str, optional) – Directory in which to store version-controlled bathymetry data. Defaults to “TopoLibrary”. Ignored if git is False (version control is no longer used)
git (bool, optional) – If True (default), initialize a git repository for version control and undo/redo support. If False, skip all git and filesystem side-effects; note that undo(), redo(), branch, and tag operations will be unavailable. TopoEditor also requires git=True.
- apply_edit(cmd, skip_version_control=False, cmd_type=CommandType.COMMAND)
Apply an edit command aware of version control. If version control is enabled, the command is executed through the TopoCommandManager (TCM) to ensure it is recorded in the version history and can be undone/redone. If version control is disabled, the command is executed directly without recording.
- Parameters:
cmd (Command) – The command to be applied.
skip_version_control (bool) – If True, the command will be executed without recording in version control even if version control is enabled. This can be useful for programmatic changes that should not be part of the user-facing version history.
cmd_type (CommandType) – The type of the command, used for version control categorization. Ignored if skip_version_control is True or if version control is disabled.
- apply_ridge(height, width, lon, ilat)
Apply a ridge to the bathymetry.
- Parameters:
height (float) – Height of the ridge to be added.
width (float) – Width of the ridge to be added.
lon (float) – Longitude where the ridge is to be centered.
ilat (pair of integers) – Initial and final latitude indices for the ridge.
- property basintmask
Ocean domain mask at T grid. Seperate number for each connected water cell, 0 if land.
- clear_user_mask()
- config_dataset(bathymetry_path, longitude_coordinate_name, latitude_coordinate_name, vertical_coordinate_name, fill_channels=False, positive_down=False, output_dir=PosixPath('.'), write_to_file=True)
Sets up necessary objects/files for regridding bathymetry. Can be flexibly used with mapping.regrid_bathy_dataset() or user can manually regrid with ESMF_regrid.
If manual regridding is necessary, write_to_file must be set to True.
- Parameters:
bathymetry_path (str) – Path to netCDF file with bathymetry data.
longitude_coordinate_name (Optional[str]) – The name of the longitude coordinate in the bathymetry dataset at
bathymetry_path. For example, for GEBCO bathymetry:'lon'(default).latitude_coordinate_name (Optional[str]) – The name of the latitude coordinate in the bathymetry dataset at
bathymetry_path. For example, for GEBCO bathymetry:'lat'(default).vertical_coordinate_name (Optional[str]) – The name of the vertical coordinate in the bathymetry dataset at
bathymetry_path. For example, for GEBCO bathymetry:'elevation'(default).output_dir – str | Path The str or Path the write to file should write to. Defaults to the directory the script is running in.
write_to_file (Optional[bool]) – Files saved to
output_dir. Defaults toTrue. Must be set to true if using manual regridding methods with ESMF_regrid.
- Returns:
where
bathymetry_outputis the original bathymetry data with proper metadata and attributes andempty_bathyis a template for the regridder.- Return type:
(
bathymetry_output,``empty_bathy``) (tuple of Datasets)
- property depth
- edit_depth(indices, values)
Edit depth at specific indices with version control.
- Parameters:
indices (list of tuples) – List of (j, i) indices to modify.
values (list or array-like) – New depth values for each index.
- erase_disconnected_basin(i, j)
- erase_selected_basin(i, j)
- classmethod from_topo_file(grid, topo_file_path, min_depth=0.0, varname='depth', version_control_dir='TopoLibrary', git=True)
Create a bathymetry object from an existing topog file.
- Parameters:
grid (mom6_forge.grid.Grid) – horizontal grid instance for which the bathymetry is to be created.
topo_file_path (str) – Path to an existing MOM6 topog file.
min_depth (float, optional) – Minimum water column depth (m). Columns with shallower depths are to be masked out.
varname (str, optional) – Name of the variable representing ocean depth in the dataset. Default is “depth”.
git (bool, optional) – Passed through to Topo.__init__. See Topo docstring for details.
- classmethod from_version_control(folder_path: str | Path)
Create a bathymetry object from an existing version-controlled bathymetry folder.
- Parameters:
folder_path (str | Path) – Path to an existing bathymetry folder created by mom6_forge with version control enabled.
- gen_topo_ds(title=None)
Write the TOPO_FILE (bathymetry file) in xarray Dataset.
- Parameters:
title (str, optional) – File title.
- generate_mask_from_landfrac_file(landfrac_filepath, landfrac_name, xcoord_name, ycoord_name, cutoff_frac=0.5, method='bilinear')
Given a dataset containing land fraction, generate and apply ocean mask.
- Parameters:
landfrac_filepath (str) – Path the netcdf file containing the land fraction field.
landfrac_name (str) – The field name corresponding to the land fraction (e.g., “landfrac”).
xcoord_name (str) – The name of the x coordinate of the landfrac dataset (e.g., “lon”).
ycoord_name (str) – The name of the y coordinate of the landfrac dataset (e.g., “lat”).
cutoff_frac (float) – Cells with landfrac > cutoff_frac are deemed land cells.
method (str) – Mapping method for determining the ocean mask (lnd -> ocn)
- generate_mask_from_naturalearth(resolution='10', version='v5_1_2')
Generate and apply a land mask using regionmask’s Natural Earth dataset. (Recommended by Fred Castruccio)
- Parameters:
resolution (str) – Resolution of the Natural Earth land dataset. One of “10”, “50”, “110” (minutes).
version (str) – Version of the Natural Earth dataset in regionmask. e.g. “v5_1_2”.
- property has_version_control
- property land_fillval
Depth value assigned to land cells when mask is applied. Default is 0.0 (dry).
- property masked_depth
Computed depth array with masking applied (m). Positive below MSL.
This is a computed property that applies land/ocean masking on-the-fly. When a user mask is set, returns masked depth: ocean cells enforced to at least min_depth+0.1, land cells set to _land_fillval. When mask is None, derives mask from raw depth (cells > min_depth are ocean).
Note: Index-based assignment like topo.masked_depth[j, i] = value will not persist because this property is computed on-the-fly. To modify depth, use topo.depth = new_array or topo.edit_depth().
- property max_depth
Maximum water column depth.
- property min_depth
Minimum water column depth. Columns with shallow depths are to be masked out.
- mpi_set_from_dataset(*, bathymetry_path, longitude_coordinate_name, latitude_coordinate_name, vertical_coordinate_name, fill_channels=False, positive_down=False, output_dir=PosixPath('.'), write_to_file=True, verbose=True)
- point_is_ocean(lons, lats)
Given a list of coordinates, return a list of booleans indicating if the coordinates are in the ocean (True) or land (False)
- property qmask
Ocean domain mask on Q grid. 1 if ocean, 0 if land.
- send_entire_depth_change_to_tcm(depth, skip_version_control=False)
This function takes an entire depth change and adds it through the TopoCommandManager (TCM) or directly if skip_version_control is enabled. Modifies _depth, preserves mask.
- set_bowl(max_depth, dedge, rad_earth=6378000.0, expdecay=400000.0)
Create a bowl-shaped bathymetry. Same effect as setting the TOPO_CONFIG parameter to “bowl”.
- Parameters:
max_depth (float) – Maximum depth of model in the units of D.
dedge (float) – The depth [Z ~> m], at the basin edge
rad_earth (float, optional) – Radius of earth
expdecay (float, optional) – A decay scale of associated with the sloping boundaries [m]
- set_depth_via_topog_file(topog_file_path, varname='depth', skip_version_control=False)
Apply a bathymetry read from an existing topog file
- Parameters:
topog_file_path (str) – absolute path to an existing MOM6 topog file
varname (str) – Name of the variable representing ocean depth in the dataset.
- set_flat(D)
Create a flat bottom bathymetry with a given depth D.
- Parameters:
D (float) – Bathymetric depth of the flat bottom to be generated.
- set_from_dataset(bathymetry_path, longitude_coordinate_name, latitude_coordinate_name, vertical_coordinate_name, fill_channels=False, positive_down=False, output_dir=PosixPath('.'), write_to_file=True, regridding_method='bilinear', run_config_dataset=True, run_regrid_dataset=True, run_tidy_dataset=True)
This code was originally written by Ashley Barnes in regional_mom6(https://github.com/COSIMA/regional-mom6) and adapted for this package.
Cut out and interpolate the chosen bathymetry and then fill inland lakes.
Users can optionally fill narrow channels (see
fill_channelskeyword argument below). Note, however, that narrow channels are less of an issue for models that are discretized on an Arakawa C grid, like MOM6.Output is saved in the output_dir.
- Parameters:
bathymetry_path (str) – Path to the netCDF file with the bathymetry.
longitude_coordinate_name (Optional[str]) – The name of the longitude coordinate in the bathymetry dataset at
bathymetry_path. For example, for GEBCO bathymetry:'lon'(default).latitude_coordinate_name (Optional[str]) – The name of the latitude coordinate in the bathymetry dataset at
bathymetry_path. For example, for GEBCO bathymetry:'lat'(default).vertical_coordinate_name (Optional[str]) – The name of the vertical coordinate in the bathymetry dataset at
bathymetry_path. For example, for GEBCO bathymetry:'elevation'(default).fill_channels (Optional[bool]) – Whether or not to fill in diagonal channels. This removes more narrow inlets, but can also connect extra islands to land. Default:
False.positive_down (Optional[bool]) – If
True, it assumes that the bathymetry vertical coordinate is positive downwards. Default:False.write_to_file (Optional[bool]) – Whether to write the bathymetry to a file. Default:
True.regridding_method (Optional[str]) – The type of regridding method to use. Defaults to self.regridding_method
run_* (Optional[bool]) – Whether to run the respective step in the bathymetry processing. Default:
True.
- set_spoon(max_depth, dedge, rad_earth=6378000.0, expdecay=400000.0)
Create a spoon-shaped bathymetry. Same effect as setting the TOPO_CONFIG parameter to “spoon”.
- Parameters:
max_depth (float) – Maximum depth of model in the units of D.
dedge (float) – The depth [Z ~> m], at the basin edge
rad_earth (float, optional) – Radius of earth
expdecay (float, optional) – A decay scale of associated with the sloping boundaries [m]
- property supergridmask
Ocean domain mask on supergrid. 1 if ocean, 0 if land.
- tidy_dataset(fill_channels=False, positive_down=False, vertical_coordinate_name='depth', bathymetry=None, output_dir=PosixPath('.'), write_to_file=True, longitude_coordinate_name='lon', latitude_coordinate_name='lat')
An auxiliary method for bathymetry used to fix up the metadata and remove inland lakes after regridding the bathymetry. Having
tidy_dataset()as a separate method fromsetup_bathymetry()allows for the regridding to be done separately, since regridding can be really expensive for large domains.If the bathymetry is already regridded and what is left to be done is fixing the metadata or fill in some channels, then
tidy_dataset()directly can read the existingbathymetry_unfinished.ncfile that should be in the input directory.- Parameters:
fill_channels (Optional[bool]) – Whether to fill in diagonal channels. This removes more narrow inlets, but can also connect extra islands to land. Default:
False.positive_down (Optional[bool]) – If
False(default), assume that bathymetry vertical coordinate is positive down, as is the case in GEBCO for example.bathymetry (Optional[xr.Dataset]) – The bathymetry dataset to tidy up. If not provided, it will read the bathymetry from the file
bathymetry_unfinished.ncin the input directory that was created byconfig/regrid_dataset().
- property tmask
Ocean domain mask at T grid. 1 if ocean, 0 if land.
This is a derived mask computed from the depth property. The computation depends on whether a user mask has been set:
If _user_mask is None: Returns a mask derived from raw depth (_depth). Cells with depth > min_depth are marked as ocean (1), otherwise land (0).
If _user_mask is set: Returns a mask set by the user. The depth property will apply this mask to the raw depth, ensuring that ocean cells are at least min_depth+0.1 and land cells are set to 0.
This design means tmask is always consistent with the current depth state, whether driven by raw bathymetry or by a manually applied mask.
- property umask
Ocean domain mask on U grid. 1 if ocean, 0 if land.
- property user_mask
Optional binary ocean/land mask. 1 if ocean, 0 if land. When set, the depth property applies masking: ocean cells enforced greater than min_depth+0.1, land cells set to _land_fillval.
- property vmask
Ocean domain mask on V grid. 1 if ocean, 0 if land.
- write_cice_grid(file_path)
Write the CICE grid file in netcdf format. The written file is to be read in by CICE during runtime.
- Parameters:
file_path (str) – Path to CICE grid file to be written.
- write_esmf_mesh(file_path, title=None)
Write the ESMF mesh file
- Parameters:
file_path (str) – Path to ESMF mesh file to be written.
title (str, optional) – File title.
- write_scrip_grid(file_path, title=None)
Write the SCRIP grid file. In latest CESM versions, SCRIP grid files are no longer required and are replaced by ESMF mesh files. However, SCRIP files are still needed to generate custom ocean-runoff mapping files.
- Parameters:
file_path (str) – Path to SCRIP file to be written.
title (str, optional) – File title.
- write_topo(file_path, title=None)
Write the TOPO_FILE (bathymetry file) in netcdf format. The written file is to be read in by MOM6 during runtime.
- Parameters:
file_path (str) – Path to TOPO_FILE to be written.
title (str, optional) – File title.
mom6_forge.topo_editor module
- class mom6_forge.topo_editor.TopoEditor(*args: t.Any, **kwargs: t.Any)
Bases:
HBoxPublic constructor
- apply_edit(cmd)
Apply an edit command, update the UI, and autosave the working state.
- construct_control_panel()
Construct the control panel widgets for the topography editor.
This includes controls for display mode, cell editing, undo/redo, snapshots, and git/domain management. The controls are grouped into logical sections for clarity.
- construct_interactive_plot()
Construct the interactive matplotlib plot for the topography editor.
This sets up the main map display, colorbar, and coordinate formatting. The plot is embedded in a widget for use in the Jupyter interface.
- construct_observances()
Attach event observers and callbacks to all interactive widgets and plot elements.
- erase_disconnected_basin(b)
Erase all disconnected basins in the topography.
- erase_selected_basin(b)
Erase the basin associated with the currently selected cell.
- property has_version_control
Check if the topo’s has version control.
- on_depth_change(change)
Handle changes to the depth specifier for the selected cell.
- on_double_click(event)
Handle double-click events on the plot to select a cell.
- on_git_checkout(b)
Checkout the specified git branch.
- on_git_create_branch(b)
Create a new git branch
- on_min_depth_change(change)
Handle changes to the minimum depth specifier.
- on_tag(_btn=None)
Save the current state as a snapshot and commit it to the repository.
- redo_last_edit(b=None)
Redo the last undone edit command and update the UI.
- refresh_display_mode(change)
Refresh the display mode of the topography plot based on the selected mode.
- reset(change)
Reset the topo to its original state and update the UI.
- trigger_refresh()
Trigger a refresh of the interactive plot and min depth specifier.
- undo_last_edit(b=None)
Undo the last edit command and update the UI.
- update_undo_redo_buttons()
Enable or disable the undo/redo buttons based on command history.
mom6_forge.utils module
Auxiliary functions for grid property computations.
- mom6_forge.utils.cell_area_rad(xv_coords, yv_coords)
Compute the area of cell(s) using spherical polygons.
- Parameters:
xv_coords (np.ndarray) – X-coordinate(s) of cell vertices in degrees.
yv_coords (np.ndarray) – Y-coordinate(s) of cell vertices in degrees.
- Returns:
area – Area of the cell(s) in square radians.
- Return type:
np.ndarray
- mom6_forge.utils.fill_missing_data(idata, mask, maxiter=0, stabilizer=1e-14, tripole=False)
Returns data with masked values “objectively interpolated” except where values exist or is over land. Does not work for periodic grids.
Arguments: data - numpy array with nan values where there is missing data or land. mask - np.array of 0 or 1, 0 for land, 1 for ocean.
Returns an array.
- mom6_forge.utils.get_avg_resolution(mesh)
Calculate the average resolution of the mesh.
- Parameters:
mesh (xr.Dataset or str or Path) – The ESMF mesh dataset or the path to the mesh file.
- Returns:
avg_resolution – Average resolution of the mesh in degrees.
- Return type:
float
- mom6_forge.utils.get_avg_resolution_km(mesh)
Calculate the average resolution of the mesh in kilometers.
- Parameters:
mesh (xr.Dataset or str or Path) – The ESMF mesh dataset or the path to the mesh file.
- Returns:
avg_resolution_km – Average resolution of the mesh in kilometers.
- Return type:
float
- mom6_forge.utils.get_mesh_dimensions(mesh)
Given an ESMF mesh where the grid metrics are stored in 1D (flattened) arrays, compute the dimensions of the 2D grid and return them as nx, ny.
- Parameters:
mesh (xr.Dataset or str or Path) – The ESMF mesh dataset or the path to the mesh file.
- Returns:
nx (int) – Number of points in the x-direction.
ny (int) – Number of points in the y-direction.
- mom6_forge.utils.is_mesh_cyclic_x(mesh)
Check if the mesh is cyclic in the x-direction.
- Parameters:
mesh (xr.Dataset or str or Path) – The ESMF mesh dataset or the path to the mesh file.
- Returns:
True if the mesh is cyclic in the x-direction, False otherwise.
- Return type:
bool
- mom6_forge.utils.longitude_slicer(data, longitude_extent, longitude_coords)
Slices longitudes while handling periodicity and the ‘seams’, that is the longitude values where the data wraps around in a global domain (for example, longitudes are defined, usually, within domain [0, 360] or [-180, 180]).
The algorithm works in five steps:
Determine whether we need to add or subtract 360 to get the middle of the
longitude_extentto lie withindata’s longitude range (herebyold_lon).Shift the dataset so that its midpoint matches the midpoint of
longitude_extent(up to a multiple of 360). Now, the modifiedold_londoes not increase monotonically from West to East since the ‘seam’ has moved.Fix
old_lonto make it monotonically increasing again. This uses the information we have about the way the dataset was shifted/rolled.Slice the
dataindex-wise. We know that|longitude_extent[1] - longitude_extent[0]| / 360multiplied by the number of discrete longitude points in the global input data gives the number of longitude points in our slice, and we’ve already set the midpoint to be the middle of the target domain.Add back the correct multiple of 360 so the whole domain matches the target.
- Parameters:
data (xarray.Dataset) – The global data you want to slice in longitude.
longitude_extent (Tuple[float, float]) – The target longitudes (in degrees) we want to slice to. Must be in increasing order.
longitude_coords (Union[str, list[str]) – The name or list of names of the longitude coordinates(s) in
data.
- Returns:
The sliced
data.- Return type:
xarray.Dataset
- mom6_forge.utils.normalize_deg(coord)
Normalize a coordinate in degrees to the range [0, 360).
- Parameters:
coord (float or np.ndarray) – Coordinate(s) in degrees.
- Returns:
normalized_coord – Normalized coordinate(s) in the range [0, 360).
- Return type:
float or np.ndarray
mom6_forge.vgrid module
- class mom6_forge.vgrid.VGrid(dz: ndarray, name=None)
Bases:
objectVertical grid class.
- dz
Array of vertical grid spacings
- Type:
np.ndarray
- nk
Number of vertical levels
- Type:
int
- depth
Total depth of the vertical grid
- Type:
float
- z
Array of layer center depths
- Type:
np.ndarray
Create a vertical grid.
- Parameters:
dz (np.ndarray) – Array of vertical grid spacings (meters)
- property depth
Total depth of the water column in meters.
- classmethod from_file(filename: str, variable_name: str = 'dz', variable_type: Literal['layer_thickness', 'cell_center', 'cell_interface'] = 'layer_thickness', name: str = None)
Create a vertical grid from an existing vertical grid file.
- Parameters:
filename (str) – Name of the NetCDF file containing the vertical grid
coordinate_name (str, default: "dz") – Name of the variable to access within the given NetCDF file to get a vertical coordinate.
coordinate_type ({"layer_thickness", "cell_center", "cell_interface"}, default: "layer_thickness") –
Type of vertical coordinate information given by the file and variable.
layer_thickness: specifies the thickness of each layer in the vertical grid. Size of n for n layers.
cell_center: gives the depth at the center of each vertical cell. Size of n for n layers.
cell_interface: gives the depth at the interface between each vertical cell. Size of n+1 for n layers.
- classmethod hyperbolic(nk: int, depth: float, ratio: float, name: str = None)
Create a hyperbolic vertical grid instance. (Adapted from regional-mom6)
- Parameters:
nk (int) – Number of vertical levels
ratio (float) – Target ratio of top to bottom layer thicknesses
depth (float) – Total depth of the water column (meters)
name (str, optional) – Name of the vertical grid
- property nk
Number of vertical levels.
- classmethod uniform(nk: int, depth: float, name: str = None)
Create a uniform vertical grid instance.
- Parameters:
nk (int) – Number of vertical levels
depth (float) – Total depth of the water column (meters)
name (str, optional) – Name of the vertical grid
- write(filename: str, message: str = None, author: str = None)
Write the vertical grid (in thickness) to a NetCDF file.
- Parameters:
filename (str) – Name of the NetCDF file to write
- write_z_file(filename: str)
Write the vertical grid to a NetCDF file with interface and midpoints depths
- Parameters:
filename (str) – Name of the NetCDF file to write
- property zi
Array of vertical grid cell interface depths (meters) - size nk+1. Assumes there is a surface interface at 0 meters.
- property zl
Array of vertical grid cell center depths (meters).
mom6_forge.vgrid_creator module
- class mom6_forge.vgrid_creator.VGridCreator(*args: t.Any, **kwargs: t.Any)
Bases:
HBoxInteractive creator for vertical grids (VGrid). Allows creation, editing, saving, and loading of vertical grid profiles.
Public constructor
- construct_control_panel(ratio_value=1.0, grid_type='Uniform')
- construct_observances()
- static infer_ratio_and_type(dz, tol=0.01)
- load_vgrid(b=None)
- plot_vgrid()
- refresh_commit_dropdown()
- reset_vgrid(b=None)
- save_vgrid(_btn=None)
- update_commit_details(change=None)