InitialConditionsSource#
- class roms_tools.InitialConditionsSource(*, grid: Grid, ini_time: datetime, type: str = 'physics', source: dict[str, str | Path | list[str | Path] | bool] | None = None, physics_forcing: InitialConditionsSource | None = None, model_reference_date: datetime = datetime.datetime(2000, 1, 1, 0, 0), allow_flex_time: bool = False, use_dask: bool = False, chunks: dict[str, int] | None = None, initial_slice_bounds: dict[str, tuple[int | float, int | float]] | None = None, bypass_validation: bool = False, bgc_interpolation_method: str = 'depth', use_vars: list[str] | None = None, prefill: str | None = None, prefill_kwargs: dict | None = None, regrid_method: str | None = None, extrap_method: str | None = None, extrap_kwargs: dict | None = None)#
Represents initial conditions for ROMS, including physical and biogeochemical data. This class will not typically be called by a user. Instead, multiple InitialConditionsSource objects are created when interacting with the user-facing InitialConditions class, from which a final ROMS input file can be saved.
- Parameters:
grid (Grid) – Object representing the grid information used for the model.
ini_time (datetime) – The date and time at which the initial conditions are set. If no exact match is found, the closest time entry to ini_time within the time range [ini_time, ini_time + 24 hours] is selected.
type ({"physics", "bgc"}, optional) – Whether this object processes the physical initial-condition dataset (
"physics", the default) or a biogeochemical dataset ("bgc"). MirrorsBoundaryForcingSource’stypeexactly.type="bgc"requiresphysics_forcing– unlike boundary forcing, there is no standalone bgc-only mode here (this object’s own bgc processing always aligns its output onto the physics time coordinate, so it needs a physics companion regardless of whether the chosenbgc_interpolation_methoditself needs T/S).source (RawDataSource, optional) –
Dictionary specifying the source: the physical initial-condition dataset when
type="physics", or the BGC dataset whentype="bgc". Keys include:”name” (str): Name of the data source (e.g., “GLORYS” for physics; “CESM_REGRIDDED”, “UNIFIED”, “GLODAP”, “constants”, or “ESPER” for bgc).
”path” (Union[str, Path, List[Union[str, Path]]]): The path to the raw data file(s). This can be:
A single string (with or without wildcards).
A single Path object.
A list of strings or Path objects.
If omitted (physics/GLORYS only), the data will be streamed via the Copernicus Marine Toolkit. Note: streaming is currently not recommended due to performance limitations.
”climatology” (bool): Indicates if the data is climatology data. Defaults to False.
physics_forcing (InitialConditionsSource, optional) –
Required when
type="bgc": an already-built,type="physics"InitialConditionsSourceobject supplying temperature/salinity for this object’s BGC processing.This object’s own physics regridding (u, v, zeta, w, barotropic velocities, temp, salt, …) is skipped entirely, so multiple BGC sources for one initial-condition snapshot no longer each pay for a redundant full-physics regrid.
ESPERderivation and"density"/"density_mld"vertical interpolation readphysics_forcing.ds["temp"]/["salt"]andphysics_forcing.ds_depth_coordsdirectly, lazily (no.load()/.compute()), instead of this object’s own (nonexistent) physics pass.The resulting
dscarries only this object’s own BGC tracers – combine it withphysics_forcing.ds(e.g. viaxr.merge/merge()) to get a complete initial-conditions dataset.
Mirrors
BoundaryForcingSource’sphysics_forcingpattern.model_reference_date (datetime, optional) – The reference date for the model. Defaults to January 1, 2000.
use_dask (bool, optional) – Indicates whether to use dask for processing. If True, data is processed with dask; if False, data is processed eagerly. Defaults to False.
chunks (dict[str, int], optional) – Dictionary specifying chunk sizes for dask dimensions, e.g.,
{"latitude": 100, "longitude": 100}. If provided, these chunks override the default chunking scheme whenuse_dask=True. Dimensions must match the underlying dataset, e.g. for ROMS restart files, the dimensions must be “eta_rho”, etc. Defaults to None (default chunking is used).initial_slice_bounds (dict, optional) –
- Optional horizontal subset to apply when loading with dask. Only Geographic bounds are supported:
{"latitude": (min_lat, max_lat), "longitude": (min_lon, max_lon)}in degrees. The bounds are applied to the dataset before reading the underlying datasets to reduce memory usage. Not used for ROMS restart or other datasets sources.
allow_flex_time (bool, optional) –
Controls how strictly ini_time is handled:
If False (default): requires an exact match to ini_time. Raises a ValueError if no match exists.
If True: allows a +24h search window after ini_time and selects the closest available time entry within that window. Raises a ValueError if none are found.
bypass_validation (bool, optional) – Indicates whether to skip validation checks in the processed data. When set to True, the validation process that ensures no NaN values exist at wet points in the processed dataset is bypassed. Defaults to False.
bgc_interpolation_method (str, optional) –
Vertical interpolation method for BGC tracers. One of:
"depth"(default): linear interpolation in depth."density": linear interpolation in potential-density (isopycnal) space, preserving water-mass properties. Density is computed from temperature and salinity via TEOS-10 sigma-0 — the BGC source’s own T/S for the source coordinate and the physics T/S for the target."density_mld": the mixed layer depth (MLD) is found in the source and target density fields; the source mixed layer is scaled so its MLD matches the target’s, and below the MLD the tracer is interpolated 1:1 in depth. This keeps the mixed layers aligned while preserving the absolute depth of sub-mixed-layer features, and avoids the surface degeneracy of pure density space.
"density"and"density_mld"only apply whentype="bgc", the physics source is a lat/lon dataset (not a ROMS restart), and the BGC source carries temperature/salinity (e.g. the unified dataset’stemp_WOA/salt_WOA); otherwise interpolation falls back to depth space and notes in the log. Interpolation usesxgcm.Grid.transformwith the linear method inside the source range and edge-value extrapolation outside (mask_edges=False).prefill (str or None, optional) –
How to fill NaN (land/void) cells in the source before regridding. The default (
None) applies no source prefill: with xESMF installed, masked bilinear interpolation plus destination extrapolation (extrap_method) produces NaN-free initial-condition fields directly; without xESMF, the source is automatically pre-filled with a cheap nearest-neighbor fill before scipy interpolation. Setprefillto fill the whole-domain source first (the regrid is then plain bilinear andextrap_methodis ignored). Options:"2d_lateral_fill"– legacy AMG Poisson fill (smoothest, slow; no xESMF required). This reproduces the pre-v4 fill behavior."inverse_dist"– xESMF inverse-distance-weighted source fill (tunable viaprefill_kwargs; requires xESMF)."nearest_s2d"– xESMF nearest-source fill (requires xESMF)."nearest_neighbor"– cheap distance-transform fill (no xESMF; also the automatic fallback when xESMF is unavailable). Use for cross-platform reproducibility or when xESMF is unavailable and the AMG fill is too slow; not recommended when xESMF is available."creep_fill"– xESMF truncated Laplace-style diffusion source fill (tunable viaprefill_kwargs; requires xESMF). Not available in current released xESMF – requires a newer/unreleased xESMF + ESMF; provided for use once a supporting xESMF is installed.
Applies only to lat/lon physics/BGC sources; for a ROMS restart source it is ignored (the legacy fill path is used) and a note is logged. Defaults to
None.prefill_kwargs (dict, optional) – Method-specific options for
prefill:num_src_pnts/dist_exponentfor"inverse_dist";num_levelsfor"creep_fill". Ignored by the other methods. Defaults toNone.regrid_method (str or None, optional) –
Horizontal regrid engine, chosen independently of
prefill:None/"auto"(default) – use xESMF if it is installed (lazy, weight-reused, faster on large grids), otherwise scipy."xesmf"– force the xESMF regridder (raises if xESMF is absent)."scipy"– force scipyinterp. Byte-reproducible with pre-v4 outputs; whenprefillisNonea nearest-neighbor source pre-fill is applied automatically so scipy cannot propagate NaNs.
Note that
inverse_dist/nearest_s2dprefills still require xESMF for the fill step regardless ofregrid_method. Applies only to lat/lon sources (ignored for a ROMS restart source). Defaults toNone.extrap_method (str or None, optional) – xESMF destination extrapolation used on the default path (
prefill is None) to fill target points whose source neighbors are all land/out of range, guaranteeing NaN-free output."inverse_dist"(the effective default) gives an inverse-distance-weighted average of the nearest source points (smoothly varying);"nearest_s2d"uses the single nearest source point. Ignored whenprefillis set. Defaults toNone(treated as"inverse_dist").extrap_kwargs (dict, optional) – Method-specific options for
extrap_method:num_src_pnts/dist_exponentfor"inverse_dist". Defaults toNone.
Examples
>>> physics = InitialConditionsSource( ... grid=grid, ... ini_time=datetime(2022, 1, 1), ... source={"name": "GLORYS", "path": "physics_data.nc"}, ... ) >>> bgc = InitialConditionsSource( ... grid=grid, ... ini_time=datetime(2022, 1, 1), ... type="bgc", ... physics_forcing=physics, ... source={ ... "name": "CESM_REGRIDDED", ... "path": "bgc_data.nc", ... "climatology": False, ... }, ... )
>>> initial_conditions = InitialConditionsSource( ... grid=grid, ... ini_time=datetime(2022, 1, 1), ... source={"name": "ROMS", "grid": parent_grid, "path": "restart.nc"}, ... )
Methods
InitialConditionsSource.from_yaml(filepath)Create an instance of the InitialConditionsSource class from a YAML file.
InitialConditionsSource.merge(physics, bgc)Merge a physics object with one or more bgc-only objects into a single ROMS-ready initial-conditions dataset.
InitialConditionsSource.plot(var_name[, s, ...])Plot the initial conditions field for a given eta-, xi-, or s_rho- slice.
InitialConditionsSource.save(filepath[, ...])Save the initial conditions information to one NetCDF file.
InitialConditionsSource.to_yaml(filepath)Export the parameters of the class to a YAML file, including the version of roms-tools.
Attributes
InitialConditionsSource.allow_flex_timeWhether to handle ini_time flexibly.
InitialConditionsSource.bgc_interpolation_method"depth","density", or"density_mld".InitialConditionsSource.bypass_validationWhether to skip validation checks in the processed data.
InitialConditionsSource.chunksOptional Dask chunk sizes for lat/lon and ROMS-restart initial-condition sources.
InitialConditionsSource.extrap_kwargsMethod-specific options for
extrap_method.InitialConditionsSource.extrap_methodxESMF destination extrapolation used on the default no-prefill path (
Noneis treated as"inverse_dist") to fill target points whose source neighbors are all masked.InitialConditionsSource.initial_slice_boundsOptional initial bounding slice when loading lat/lon forcing data with Dask.
InitialConditionsSource.model_reference_dateThe reference date for the model.
InitialConditionsSource.physics_forcinga
type="physics"InitialConditionsSource object supplying temperature/salinity, so this object's own physics regridding is skipped entirely.InitialConditionsSource.prefillSource-side fill applied before lateral regridding.
InitialConditionsSource.prefill_kwargsMethod-specific options for
prefill(e.g.num_src_pnts/dist_exponent).InitialConditionsSource.regrid_methodNone/"auto"uses xESMF when installed (else scipy),"xesmf"forces xESMF,"scipy"forces scipy.InitialConditionsSource.sourcethe physical dataset when
type="physics", the BGC dataset whentype="bgc".InitialConditionsSource.typeWhether this object processes the physics source (
"physics") or a BGC source ("bgc").InitialConditionsSource.use_daskWhether to use dask for processing.
InitialConditionsSource.use_varsOptional down-selection of the BGC variables written from
source(only applies whentype="bgc").InitialConditionsSource.gridObject representing the grid information.
InitialConditionsSource.ini_timeThe date and time at which the initial conditions are set.
InitialConditionsSource.dsAn xarray Dataset containing post-processed variables ready for input into ROMS.
InitialConditionsSource.adjust_depth_for_sea_surface_heightWhether to account for sea surface height when computing depth coordinates.
InitialConditionsSource.ds_depth_coordsAn xarray Dataset containing the depth coordinates.