InitialConditions

InitialConditions#

class roms_tools.InitialConditions(*, grid: Grid, ini_time: datetime, source: dict[str, str | Path | list[str | Path] | bool], bgc_source: dict[str, str | Path | list[str | Path] | bool] | 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', 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.

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.

  • source (RawDataSource) –

    Dictionary specifying the source of the physical initial condition data. Keys include:

    • ”name” (str): Name of the data source (e.g., “GLORYS”).

    • ”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, 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.

  • bgc_source (RawDataSource, optional) –

    Dictionary specifying the source of the biogeochemical (BGC) initial condition data. Keys include:

    • ”name” (str): Name of the data source (e.g., “CESM_REGRIDDED”).

    • ”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 containing multiple files.

    • ”climatology” (bool): Indicates if the data is climatology data. Defaults to False.

  • 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 when use_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 when bgc_source is provided, the physics source is a lat/lon dataset (not a ROMS restart), and the BGC source carries temperature/salinity (e.g. the unified dataset’s temp_WOA/ salt_WOA); otherwise interpolation falls back to depth space and notes in the log. Interpolation uses xgcm.Grid.transform with 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. Set prefill to fill the whole-domain source first (the regrid is then plain bilinear and extrap_method is 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 via prefill_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 via prefill_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_exponent for "inverse_dist"; num_levels for "creep_fill". Ignored by the other methods. Defaults to None.

  • 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 scipy interp. Byte-reproducible with pre-v4 outputs; when prefill is None a nearest-neighbor source pre-fill is applied automatically so scipy cannot propagate NaNs.

    Note that inverse_dist / nearest_s2d prefills still require xESMF for the fill step regardless of regrid_method. Applies only to lat/lon sources (ignored for a ROMS restart source). Defaults to None.

  • 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 when prefill is set. Defaults to None (treated as "inverse_dist").

  • extrap_kwargs (dict, optional) – Method-specific options for extrap_method: num_src_pnts / dist_exponent for "inverse_dist". Defaults to None.

Examples

>>> initial_conditions = InitialConditions(
...     grid=grid,
...     ini_time=datetime(2022, 1, 1),
...     source={"name": "GLORYS", "path": "physics_data.nc"},
...     bgc_source={
...         "name": "CESM_REGRIDDED",
...         "path": "bgc_data.nc",
...         "climatology": False,
...     },
... )
>>> initial_conditions = InitialConditions(
...     grid=grid,
...     ini_time=datetime(2022, 1, 1),
...     source={"name": "ROMS", "grid": parent_grid, "path": "restart.nc"},
...     bgc_source={
...         "name": "ROMS",
...         "grid": parent_grid,
...         "path": "restart.nc",
...     },
... )

Methods

InitialConditions.from_yaml(filepath[, use_dask])

Create an instance of the InitialConditions class from a YAML file.

InitialConditions.plot(var_name[, s, eta, ...])

Plot the initial conditions field for a given eta-, xi-, or s_rho- slice.

InitialConditions.save(filepath[, format])

Save the initial conditions information to one NetCDF file.

InitialConditions.to_yaml(filepath)

Export the parameters of the class to a YAML file, including the version of roms-tools.

Attributes

InitialConditions.allow_flex_time

Whether to handle ini_time flexibly.

InitialConditions.bgc_interpolation_method

"depth", "density", or "density_mld".

InitialConditions.bgc_source

Dictionary specifying the source of the biogeochemical (BGC) initial condition data.

InitialConditions.bypass_validation

Whether to skip validation checks in the processed data.

InitialConditions.chunks

Optional Dask chunk sizes for lat/lon and ROMS-restart initial-condition sources.

InitialConditions.extrap_kwargs

Method-specific options for extrap_method.

InitialConditions.extrap_method

xESMF destination extrapolation used on the default no-prefill path (None is treated as "inverse_dist") to fill target points whose source neighbors are all masked.

InitialConditions.initial_slice_bounds

Optional initial bounding slice when loading lat/lon forcing data with Dask.

InitialConditions.model_reference_date

The reference date for the model.

InitialConditions.prefill

Source-side fill applied before lateral regridding.

InitialConditions.prefill_kwargs

Method-specific options for prefill (e.g. num_src_pnts / dist_exponent).

InitialConditions.regrid_method

None/"auto" uses xESMF when installed (else scipy), "xesmf" forces xESMF, "scipy" forces scipy.

InitialConditions.use_dask

Whether to use dask for processing.

InitialConditions.grid

Object representing the grid information.

InitialConditions.ini_time

The date and time at which the initial conditions are set.

InitialConditions.source

Dictionary specifying the source of the physical initial condition data.

InitialConditions.ds

An xarray Dataset containing post-processed variables ready for input into ROMS.

InitialConditions.adjust_depth_for_sea_surface_height

Whether to account for sea surface height when computing depth coordinates.

InitialConditions.ds_depth_coords

An xarray Dataset containing the depth coordinates.