Skip to content

Config

SwanConfig is the SWAN model configuration. It gathers the components, one per SWAN command or group of commands, and renders the SWAN command file (INPUT). It subclasses rompy's BaseConfig.

SWAN Configuration Module

This module provides configuration classes for the SWAN model within the ROMPY framework.

HERE module-attribute

HERE = Path(__file__).parent

DEFAULT_TEMPLATE module-attribute

DEFAULT_TEMPLATE = str(
    Path(__file__).parent / "templates" / "swan"
)

STARTUP_TYPE module-attribute

STARTUP_TYPE = Annotated[
    STARTUP, Field(description="Startup components")
]

INITIAL_TYPE module-attribute

INITIAL_TYPE = Annotated[
    boundary.INITIAL, Field(description="Initial component")
]

PHYSICS_TYPE module-attribute

PHYSICS_TYPE = Annotated[
    PHYSICS, Field(description="Physics components")
]

PROP_TYPE module-attribute

PROP_TYPE = Annotated[
    numerics.PROP,
    Field(description="Propagation components"),
]

NUMERIC_TYPE module-attribute

NUMERIC_TYPE = Annotated[
    numerics.NUMERIC,
    Field(description="Numerics components"),
]

OUTPUT_TYPE module-attribute

OUTPUT_TYPE = Annotated[
    OUTPUT, Field(description="Output components")
]

LOCKUP_TYPE module-attribute

LOCKUP_TYPE = Annotated[
    LOCKUP, Field(description="Output components")
]

CGRID_TYPES module-attribute

CGRID_TYPES = Annotated[
    Union[
        cgrid.REGULAR, cgrid.CURVILINEAR, cgrid.UNSTRUCTURED
    ],
    Field(
        description="Cgrid component",
        discriminator="model_type",
    ),
]

INPGRID_TYPES module-attribute

INPGRID_TYPES = Annotated[
    SerializeAsAny[Union[INPGRIDS, DataInterface]],
    Field(
        description="Input grid components",
        discriminator="model_type",
    ),
]

BOUNDARY_TYPES module-attribute

BOUNDARY_TYPES = Annotated[
    Union[
        boundary.BOUNDSPEC,
        boundary.BOUNDNEST1,
        boundary.BOUNDNEST2,
        boundary.BOUNDNEST3,
        BoundaryInterface,
    ],
    Field(
        description="Boundary component",
        discriminator="model_type",
    ),
]

logger module-attribute

logger = logging.getLogger(__name__)

SwanConfig pydantic-model

SwanConfig(**data: Any)

Bases: BaseConfig

SWAN config class.

TODO: Combine boundary and inpgrid into a single input type.

Note

The cgrid is the only required field since it is used to define the swan grid object which is passed to other components.

Time Control

When calling the config with a runtime TimeRange object (e.g., from ModelRun.period), the temporal parameters are set as follows:

COMPUTE Components (LOCKUP): - Time values (tbeg, tend, delt) are always from the runtime TimeRange - Time and interval formatting (tfmt, dfmt) can be specified in the component's times field - The runtime interval defines the computational timestep (deltc) - COMPUTE, the single computation of stationary mode, has no times; output components are then also written without times

OUTPUT Components (BLOCK, TABLE, SPECOUT, NESTOUT): - Start time (tbeg) is the runtime start unless the component's times field sets it, e.g. to leave out a spin-up period - Time interval (delt) can be specified in the component's times field to override runtime interval - Time and interval formatting (tfmt, dfmt) can be specified in the component's times field - If no times field is specified, the component uses runtime interval for delt

This allows fine-grained control over: - COMPUTE: Time and interval formatting - OUTPUT: Time interval and formatting

All components start at the same time from ModelRun.period.start.

Examples:

In nonstationary mode, the BLOCK output sets its own interval while the TABLE output and the computation use the run interval:

import tempfile
from datetime import timedelta
from pathlib import Path

from rompy.core.time import TimeRange
from rompy.logging import config as logging_config
from rompy.model import ModelRun
from rompy_swan.config import SwanConfig
from rompy_swan.grid import SwanGrid

logging_config.update(level="WARNING")

grid = SwanGrid(x0=110.0, y0=-36.0, dx=0.5, dy=0.5, nx=13, ny=15)
config = SwanConfig(
    startup=dict(mode=dict(kind="nonstationary")),
    cgrid=dict(
        model_type="regular",
        grid=grid.component,
        spectrum=dict(mdc=36, flow=0.04, fhigh=1.0),
    ),
    output=dict(
        # Custom 30-minute output interval
        block=dict(
            model_type="block",
            sname="COMPGRID",
            fname="output.nc",
            output=["hsign"],
            times=dict(delt=timedelta(minutes=30), dfmt="min"),
        ),
        # Uses the run interval (1 hour)
        points=dict(model_type="points", sname="sites", xp=[115.5], yp=[-32.0]),
        table=dict(sname="sites", fname="table.txt", output=["hsign", "dir"]),
    ),
    lockup=dict(compute=dict(model_type="nonstat")),
)
period = TimeRange(start="2024-01-01T00", end="2024-01-02T00", interval="1h")
run = ModelRun(run_id="times", period=period, output_dir=tempfile.mkdtemp(), config=config)
input_file = (Path(run()) / "INPUT").read_text()
lines = input_file.splitlines()
print("\n".join(line for line in lines if line.startswith(("BLOCK", "TABLE", "COMPUTE", " "))))
    xp=115.5 yp=-32.0
BLOCK sname='COMPGRID' fname='output.nc' HSIGN &
    OUTPUT tbegblk=20240101.000000 deltblk=30.0 MIN
TABLE sname='sites' fname='table.txt' &
    HSIGN &
    DIR &
    OUTPUT tbegtbl=20240101.000000 delttbl=3600.0 SEC
COMPUTE NONSTATIONARY tbegc=20240101.000000 deltc=3600.0 SEC tendc=20240102.000000

Fields:

Validators:

model_type pydantic-field

model_type: Literal['swan', 'SWAN'] = 'swan'

Model type discriminator

template pydantic-field

template: str = DEFAULT_TEMPLATE

The template for SWAN.

cgrid pydantic-field

cgrid: CGRID_TYPES

startup pydantic-field

startup: Optional[STARTUP_TYPE] = None

inpgrid pydantic-field

inpgrid: Optional[INPGRID_TYPES] = None

forcing pydantic-field

forcing: Optional[FORCING] = None

boundary pydantic-field

boundary: Optional[BOUNDARY_TYPES] = None

initial pydantic-field

initial: Optional[INITIAL_TYPE] = None

physics pydantic-field

physics: Optional[PHYSICS_TYPE] = None

prop pydantic-field

prop: Optional[PROP_TYPE] = None

numeric pydantic-field

numeric: Optional[NUMERIC_TYPE] = None

output pydantic-field

output: Optional[OUTPUT_TYPE] = None

lockup pydantic-field

lockup: Optional[LOCKUP_TYPE] = None

stationary_mode property

stationary_mode: bool

True if SWAN runs in stationary mode (MODE STATIONARY, the default).

grid property

grid

Define a SwanGrid from the cgrid field.

checkout pydantic-field

checkout: Optional[str] = 'main'

The git branch to use if the template is a git repo

compute_consistent_with_mode pydantic-validator

compute_consistent_with_mode() -> SwanConfig

Ensure the computation and inputs are possible in the SWAN mode.

In stationary mode (SWAN's default) SWAN makes a single computation without times, COMPUTE, and accepts no time information in the inputs and output. Computations at given times, COMPUTE_STAT and COMPUTE_NONSTAT, and the time-stamped files written by the data and boundary interfaces need MODE NONSTATIONARY.

no_nor_if_spherical pydantic-validator

no_nor_if_spherical() -> SwanConfig

Ensure SET nor is not prescribed when using spherical coordinates.

no_repeating_if_setup pydantic-validator

no_repeating_if_setup() -> SwanConfig

Ensure COORD repeating not set when using set-up.

alp_is_zero_if_spherical pydantic-validator

alp_is_zero_if_spherical() -> SwanConfig

Ensure alp is zero when using spherical coordinates.

cgrid_contain_inpgrids pydantic-validator

cgrid_contain_inpgrids() -> SwanConfig

Ensure all inpgrids are inside the cgrid area.

layer_defined_if_no_mud_inpgrid pydantic-validator

layer_defined_if_no_mud_inpgrid() -> SwanConfig

Ensure layer is set in MUD command if not defined with INPGRID MUD.

transm_msc_mdc

transm_msc_mdc() -> SwanConfig

Ensure the number of transmission coefficients match msc and mdc.

locations_2d pydantic-validator

locations_2d() -> SwanConfig

Ensure Location components not used in 1D mode.

group_within_cgrid pydantic-validator

group_within_cgrid() -> SwanConfig

Ensure group indices are contained in computational grid.

not_curvilinear_if_ray pydantic-validator

not_curvilinear_if_ray() -> SwanConfig

Ensure bottom and water level grids are not curvilinear for RAY.

resolve_segment_ij_sentinels pydantic-validator

resolve_segment_ij_sentinels() -> SwanConfig

Replace -1 sentinel values in BOUNDSPEC SEGMENT IJ with grid max indices.

SWAN terminates the SEGMENT IJ reading loop when it encounters a negative i value, so -1 cannot be used literally. This validator allows users to specify -1 as a shorthand for the last grid index (mx for i, my for j) and replaces it with the actual value derived from the cgrid definition.

check_for_typos classmethod

check_for_typos(data: Any) -> Any

Suggest the closest field name for an unknown input key.

A field can be given by its name or, like in pydantic, by its alias.

dump_inputs_dict

dump_inputs_dict() -> dict

Return the original inputs as a dictionary.

dump_inputs_json

dump_inputs_json() -> str

Return the original inputs as a JSON string.

render

render(context: dict, output_dir: Path | str) -> None

Render the configuration template to the output directory.

This method orchestrates the template rendering process. The default implementation uses cookiecutter rendering with the template and checkout defined on this config. Subclasses can override this method to implement alternative rendering strategies (e.g., direct file writing, Jinja2, custom logic).

Parameters:

Name Type Description Default
context dict

Full context dictionary. Expected to contain at least 'runtime' and 'config' keys.

required
output_dir Path | str

Target directory for rendered output.

required

SwanConfigComponents pydantic-model

SwanConfigComponents(**kwargs)

Bases: SwanConfig

Deprecated: Use SwanConfig instead.

This class is deprecated and will be removed in a future version. Please use SwanConfig instead of SwanConfigComponents.

Fields:

Validators:

model_type pydantic-field

model_type: Literal["swanconfig", "SWANCONFIG"] = (
    "swanconfig"
)

Model type discriminator

template pydantic-field

template: str = DEFAULT_TEMPLATE

The template for SWAN.

checkout pydantic-field

checkout: Optional[str] = 'main'

The git branch to use if the template is a git repo

cgrid pydantic-field

cgrid: CGRID_TYPES

startup pydantic-field

startup: Optional[STARTUP_TYPE] = None

inpgrid pydantic-field

inpgrid: Optional[INPGRID_TYPES] = None

forcing pydantic-field

forcing: Optional[FORCING] = None

boundary pydantic-field

boundary: Optional[BOUNDARY_TYPES] = None

initial pydantic-field

initial: Optional[INITIAL_TYPE] = None

physics pydantic-field

physics: Optional[PHYSICS_TYPE] = None

prop pydantic-field

prop: Optional[PROP_TYPE] = None

numeric pydantic-field

numeric: Optional[NUMERIC_TYPE] = None

output pydantic-field

output: Optional[OUTPUT_TYPE] = None

lockup pydantic-field

lockup: Optional[LOCKUP_TYPE] = None

stationary_mode property

stationary_mode: bool

True if SWAN runs in stationary mode (MODE STATIONARY, the default).

grid property

grid

Define a SwanGrid from the cgrid field.

check_for_typos classmethod

check_for_typos(data: Any) -> Any

Suggest the closest field name for an unknown input key.

A field can be given by its name or, like in pydantic, by its alias.

dump_inputs_dict

dump_inputs_dict() -> dict

Return the original inputs as a dictionary.

dump_inputs_json

dump_inputs_json() -> str

Return the original inputs as a JSON string.

render

render(context: dict, output_dir: Path | str) -> None

Render the configuration template to the output directory.

This method orchestrates the template rendering process. The default implementation uses cookiecutter rendering with the template and checkout defined on this config. Subclasses can override this method to implement alternative rendering strategies (e.g., direct file writing, Jinja2, custom logic).

Parameters:

Name Type Description Default
context dict

Full context dictionary. Expected to contain at least 'runtime' and 'config' keys.

required
output_dir Path | str

Target directory for rendered output.

required

compute_consistent_with_mode pydantic-validator

compute_consistent_with_mode() -> SwanConfig

Ensure the computation and inputs are possible in the SWAN mode.

In stationary mode (SWAN's default) SWAN makes a single computation without times, COMPUTE, and accepts no time information in the inputs and output. Computations at given times, COMPUTE_STAT and COMPUTE_NONSTAT, and the time-stamped files written by the data and boundary interfaces need MODE NONSTATIONARY.

no_nor_if_spherical pydantic-validator

no_nor_if_spherical() -> SwanConfig

Ensure SET nor is not prescribed when using spherical coordinates.

no_repeating_if_setup pydantic-validator

no_repeating_if_setup() -> SwanConfig

Ensure COORD repeating not set when using set-up.

alp_is_zero_if_spherical pydantic-validator

alp_is_zero_if_spherical() -> SwanConfig

Ensure alp is zero when using spherical coordinates.

cgrid_contain_inpgrids pydantic-validator

cgrid_contain_inpgrids() -> SwanConfig

Ensure all inpgrids are inside the cgrid area.

layer_defined_if_no_mud_inpgrid pydantic-validator

layer_defined_if_no_mud_inpgrid() -> SwanConfig

Ensure layer is set in MUD command if not defined with INPGRID MUD.

transm_msc_mdc

transm_msc_mdc() -> SwanConfig

Ensure the number of transmission coefficients match msc and mdc.

locations_2d pydantic-validator

locations_2d() -> SwanConfig

Ensure Location components not used in 1D mode.

group_within_cgrid pydantic-validator

group_within_cgrid() -> SwanConfig

Ensure group indices are contained in computational grid.

not_curvilinear_if_ray pydantic-validator

not_curvilinear_if_ray() -> SwanConfig

Ensure bottom and water level grids are not curvilinear for RAY.

resolve_segment_ij_sentinels pydantic-validator

resolve_segment_ij_sentinels() -> SwanConfig

Replace -1 sentinel values in BOUNDSPEC SEGMENT IJ with grid max indices.

SWAN terminates the SEGMENT IJ reading loop when it encounters a negative i value, so -1 cannot be used literally. This validator allows users to specify -1 as a shorthand for the last grid index (mx for i, my for j) and replaces it with the actual value derived from the cgrid definition.