Skip to content

Types API

API reference for base types and utilities.

Base Models

XBeachBaseModel

Bases: RompyBaseModel

Base model class for all XBeach parameter models.

Provides automatic serialization with: - Recursive flattening of nested components (model_type discriminators) - Boolean to integer conversion for XBeach compatibility - Standard params property and get() method

All XBeach parameter models should inherit from this class.

Attributes

model_config class-attribute instance-attribute

model_config = ConfigDict(populate_by_name=True)

params property

params: dict

Return the XBeach parameters as a flat dictionary.

Functions

_serialize_with_component_flattening

_serialize_with_component_flattening(serializer: Any) -> dict

Serialize model with recursive component flattening and bool to int conversion.

This serializer: 1. Recursively detects nested dictionaries (from parameter component serialization) 2. Flattens them by setting outer key = inner model_type value 3. Merges remaining inner key-values into the main dict 4. Converts booleans to integers for XBeach compatibility

Example

{'wavemodel': {'model_type': 'surfbeat', 'break': {'model_type': 'roelvink1', 'alpha': 1.0}}} becomes:

get

get(destdir: str | Path) -> dict

Return the params dict with file fetching for nested components.

This method handles two types of nested components: 1. Components with explicit parameter fields: Need special handling to extract the field value and merge remaining params 2. Discriminated union components: Already flattened by the serializer

The default implementation: - For components with explicit fields: includes that field in return dict - For discriminated unions or leaf components: returns standard params - For parent components: processes XBeachBaseModel children recursively

Override this method if you need custom file fetching logic (e.g., DataBlob).

Parameters

destdir: str | Path Directory path for file operations.

Returns

Flat dictionary of XBeach parameters.

XBeachDataBlob

Bases: DataBlob

Custom DataBlob for XBeach with special handling in get() method.

XBeachDataBlob fields are excluded from .params serialization to prevent internal fields (id, source, link) from leaking into params.txt. In .get() they are replaced with the fetched file path.

Usage

veggiefile: Optional[XBeachDataBlob] = Field(default=None, ...)

def get(self, destdir: Path) -> dict: params = super().get(destdir) if self.veggiefile and destdir: params["veggiefile"] = self.veggiefile.get(destdir).name return params

Functions

_serialize_skip_for_params

_serialize_skip_for_params(serializer: Any) -> dict

Skip serialization to prevent field leakage in params.

XBeachHotstartBlob

Bases: XBeachDataBlob

DataBlob for XBeach hotstart files with glob pattern support.

Hotstart files follow the naming convention: hotstart_{varname}{fileno:06d}.dat where varname is the variable name (zs, zb, uu, vv, etc.) and fileno is the hotstart file number (0-999).

The source should point to a directory containing hotstart files from a previous XBeach simulation.

Usage

hotstart_source: Optional[XBeachHotstartBlob] = Field(default=None, ...)

def get(self, destdir: Path, fileno: int = 0) -> list[Path]: # Returns list of copied hotstart files return self.hotstart_source.get(destdir, fileno)

Attributes

source class-attribute instance-attribute

source: AnyPath = Field(description='Directory containing hotstart files from a previous XBeach simulation. Can be a local path or remote URI (e.g., s3://bucket/path).')

Functions

validate_source_is_directory classmethod

validate_source_is_directory(v: AnyPath) -> AnyPath

Validate that source is a directory.

validate_link_not_allowed(v: bool) -> bool

Validate that link is not enabled for hotstart directories.

get

get(destdir: Union[str, Path], fileno: int = 0, *args, **kwargs) -> list[Path]

Copy hotstart files matching the pattern to destdir.

Parameters

destdir : str | Path The destination directory to copy hotstart files to. fileno : int, optional The hotstart file number to match (0-999). Default is 0.

Returns

list[Path] List of paths to the copied hotstart files.

Raises

FileNotFoundError If no hotstart files matching the pattern are found.


Grid

RegularGrid

Bases: BaseGrid

Xbeach regular grid class.

Attributes

model_type class-attribute instance-attribute

model_type: Literal['regular'] = Field(default='regular', description='Model type discriminator')

ori class-attribute instance-attribute

ori: GeoPoint = Field(description='Origin of the grid in geographic space')

alfa class-attribute instance-attribute

alfa: float = Field(description='Angle of x-axis from east in degrees')

dx class-attribute instance-attribute

dx: float = Field(description='Grid spacing in the x-direction, for projected CRS, this value is defined in meters, for geographic CRS, it is defined in degrees')

dy class-attribute instance-attribute

dy: float = Field(description='Grid spacing in the y-direction, for projected CRS, this value is defined in meters, for geographic CRS, it is defined in degrees')

nx class-attribute instance-attribute

nx: int = Field(description="Number of grid points in the x-direction, the 'nx' paramter in the XBeach namelist will be one less than this value (nx - 1)")

ny class-attribute instance-attribute

ny: int = Field(description="Number of grid points in the y-direction, the 'ny' paramter in the XBeach namelist will be one less than this value (ny - 1)")

crs class-attribute instance-attribute

crs: Optional[CRS_TYPES] = Field(default=None, description='Coordinate reference system of the grid')

_validate_crs class-attribute instance-attribute

_validate_crs = field_validator('crs')(validate_crs)

model_config class-attribute instance-attribute

model_config = ConfigDict(arbitrary_types_allowed=True)

x0 cached property

x0: float

X coordinate of the grid origin in the grid crs.

y0 cached property

y0: float

Y coordinate of the grid origin in the grid crs.

x cached property

x: ndarray

X coordinates of the grid.

y cached property

y: ndarray

Y coordinates of the grid.

shape cached property

shape: tuple[int, int]

Shape of the grid.

gdf cached property

gdf

Geodataframe representation with multi-polygons for each grid cell.

left cached property

left: tuple[ndarray, ndarray]

Coordinates of the left (lateral) boundary of the grid.

right cached property

right: tuple[ndarray, ndarray]

Coordinates of the right (lateral) boundary of the grid.

back cached property

back: tuple[ndarray, ndarray]

Coordinates of the back (land) boundary of the grid.

front cached property

front: tuple[ndarray, ndarray]

Coordinates of the front (offshore) boundary of the grid.

offshore cached property

offshore: tuple[float, float]

Coordinates at the centre of the offshore boundary.

centre cached property

centre: tuple[float, float]

Coordinates at the centre of the grid.

proj4 cached property

proj4

PROJ4 string of the grid.

transform cached property

transform

Cartopy transformation for the grid.

projection cached property

projection

Cartopy stereographic projection for this grid.

params cached property

params

Return the XBeach parameters for the grid.

Functions

__repr__

__repr__() -> str

__str__

__str__() -> str

model_dump

model_dump(*args, **kwargs)

Dump the model representation of the object taking care of the CRS.

expand

expand(left=0, right=0, back=0, front=0) -> RegularGrid

Expand the grid boundaries.

_generate

_generate(left=0, right=0, back=0, front=0) -> tuple[ndarray, ndarray]

Generate the grid coordinates.

Parameters

left : int, optional Number of points to extend the left lateral boundary, by default 0. right : int, optional Number of points to extend the right lateral boundary, by default 0. back : int, optional Number of points to extend the back offshore boundary, by default 0. front : int, optional Number of points to extend the front inshore boundary, by default 0.

plot

plot(ax: GeoAxes = None, scale: str = None, projection: PlateCarree = None, buffer: float = 500, set_extent: bool = True, set_gridlines: bool = True, grid_kwargs: dict = dict(alpha=0.5, zorder=2), figsize: tuple = None, show_mesh: bool = False, mesh_step: int = 1, mesh_kwargs: dict = dict(color='k', linewidth=0.5), show_offshore: bool = True, show_origin: bool = True) -> GeoAxes

Plot the grid optionally overlaid with GSHHS coastlines.

Parameters

ax: matplotlib.axes.Axes, optional Axes object to plot on, by default create a new figure and axes. scale: str, optional Scale for the GSHHS coastline feature, one of 'c', 'l', 'i', 'h', 'f', by default None which implies no coastlines are plotted. projection: cartopy.crs.Projection, optional Map projection, by default use a stereographic projection. buffer: float, optional Buffer around the grid in meters, by default 500. set_extent: bool, optional Set the extent of the axes to the grid bbox and buffer, by default True. set_gridlines: bool, optional Add gridlines to the plot, by default True. grid_kwargs: dict, optional Keyword arguments for the grid plot, by default dict(alpha=0.5, zorder=2). figsize: tuple, optional Figure size in inches, by default None. show_mesh: bool, optional Show the model grid mesh, by default False. mesh_step: int, optional Step for the mesh plot, by default 1. mesh_kwargs: dict, optional Keyword arguments for the mesh, by default dict(color="k", linewidth=0.5). show_offshore: bool, optional Show the offshore boundary, by default True. show_origin: bool, optional Show the origin of the grid, by default True.

Returns

matplotlib.axes.Axes Axes object with the plot.

to_file

to_file(filename, **kwargs)

from_file classmethod

from_file(filename: str, **kwargs) -> RegularGrid

Read a grid from a file.

Parameters

filename : str Path to the file. kwargs : dict Additional keyword arguments for the geopandas read_file method.

Returns

RegularGrid RegularGrid object.


Bathymetry

XBeachBathy

Bases: XBeachDataGrid

XBeach bathymetry data class.

Attributes

model_type class-attribute instance-attribute

model_type: Literal['xbeach_bathy'] = Field(default='xbeach_bathy', description='Model type discriminator')

variables class-attribute instance-attribute

variables: Union[str, list] = Field(default='data', description='The variable name in the source dataset')

posdwn class-attribute instance-attribute

posdwn: bool = Field(default=True, description='Bathymerty is positive down if True, positive up if False')

left class-attribute instance-attribute

left: int = Field(default=0, description='Number of points to extend the left lateral boundary', ge=0)

right class-attribute instance-attribute

right: int = Field(default=0, description='Number of points to extend the right lateral boundary', ge=0)

extension class-attribute instance-attribute

extension: Union[SeawardExtensionBase, SeawardExtensionLinear] = Field(default_factory=SeawardExtensionBase, description='Method to extend the data seaward', discriminator='model_type')

interpolate_na class-attribute instance-attribute

interpolate_na: bool = Field(default=True, description='Interpolate NaN values in the source data')

interpolate_na_kwargs class-attribute instance-attribute

interpolate_na_kwargs: dict = Field(default_factory=dict, description='Keyword arguments for the interpolate_na method')

params property

params

Return the XBeach parameters for the bathy data.

Functions

single_variable

single_variable() -> XBeachBathy

Ensure a single variable is provided.

expand_lateral

expand_lateral(data: Np2DArray, grid: RegularGrid) -> tuple[Np2DArray, RegularGrid]

Extend the data laterally.

Parameters

data: Np2DArray The data grid to extend. grid: rompy_xbeach.grid.RegularGrid The grid associated with the data.

Returns

data_ext: Np2DArray The extended data grid. grid_ext: rompy_xbeach.grid.RegularGrid The grid associated with the extended data.

get

get(destdir: str | Path, grid: RegularGrid, time: Optional[TimeRange] = None) -> tuple[Path, Path, Path, RegularGrid]

Write the data source to a new location.

Parameters

destdir : str | Path The destination directory to write data file to. grid: rompy_xbeach.grid.RegularGrid The grid to interpolate the data to. time: TimeRange, optional The times to filter the data to, only used if self.filter_time is True.

Returns

xfile: Path The path to the generated x-coordinate data file. yfile: Path The path to the generated y-coordinate data file. depfile: Path The path to the generated bathymetry data file. grid: rompy_xbeach.grid.RegularGrid The grid associated with the bathymetry data.

SeawardExtensionLinear

Bases: SeawardExtensionBase

Linear extension of the data grid.

This class extends the data grid in the seaward direction by linearly interpolating between the existing offshore boundary and the extended boundary. The length of the extension is calculated based on the shallowest offshore depth, the depth at the extended boundary, and the maximum slope.

Attributes

model_type class-attribute instance-attribute

model_type: Literal['linear'] = Field(default='linear', description='Model type discriminator')

depth class-attribute instance-attribute

depth: float = Field(default=25, description='Depth at the offshore boundary of the extended grid', gt=0)

slope class-attribute instance-attribute

slope: float = Field(default=0.3, description='Slope of the linear extension', gt=0)

Functions

xlen

xlen(h_profile: float) -> float

Calculate the 1D extension length.

Parameters

h_profile: float Depth at the offshore boundary of the existing cross shore profile.

Returns

xlen : float The extension length in the cross shore direction (m).

get

get(data: Np2DArray, grid: RegularGrid, posdwn: bool) -> tuple[Np2DArray, RegularGrid]

Extend the data in the seaward direction.

Parameters

data: np.ndarray The data grid to extend. grid: rompy_xbeach.grid.RegularGrid The grid associated with the data. posdwn: bool Bathymetry is positive down if True, positive up if False.

Returns

data_ext: np.ndarray The extended data grid. grid_ext: rompy_xbeach.grid.RegularGrid The grid associated with the extended data.


Sources

SourceGeotiff

Bases: SourceBase

Geotiff source class.

Attributes

model_type class-attribute instance-attribute

model_type: Literal['geotiff'] = Field(default='geotiff', description='Model type discriminator')

filename class-attribute instance-attribute

filename: str | Path = Field(description='Path to the geotiff dataset')

band class-attribute instance-attribute

band: int = Field(default=1, description='Band to read from the dataset after opening it with rasterio', ge=1)

kwargs class-attribute instance-attribute

kwargs: dict = Field(default={}, description='Keyword arguments to pass to rioxarray.open_rasterio')

Functions

validate_rasterio_kwargs classmethod

validate_rasterio_kwargs(v) -> dict

Validate the rasterio keyword arguments.

_open

_open() -> Dataset

This method needs to return an xarray Dataset object.

SourceXYZ

Bases: SourceBase

XYZ source class.

Attributes

model_type class-attribute instance-attribute

model_type: Literal['xyz'] = Field(default='xyz', description='Model type discriminator')

filename class-attribute instance-attribute

filename: str | Path = Field(description='Path to the xyz dataset')

crs class-attribute instance-attribute

crs: Union[int, str] = Field(description='Coordinate reference system of the source data')

res class-attribute instance-attribute

res: float = Field(description='Resolution of the regular grid to interpolate onto')

xcol class-attribute instance-attribute

xcol: str = Field(default='x', description='Name of the column containing the x data')

ycol class-attribute instance-attribute

ycol: str = Field(default='y', description='Name of the column containing the y data')

zcol class-attribute instance-attribute

zcol: str = Field(default='z', description='Name of the column containing the z data')

read_csv_kwargs class-attribute instance-attribute

read_csv_kwargs: dict = Field(default={}, description='Keyword arguments to pass to pandas.read_csv')

griddata_kwargs class-attribute instance-attribute

griddata_kwargs: dict = Field(default={'method': 'linear'}, description='Keyword arguments to pass to scipy.interpolate.griddata')

Functions

_open_dataframe

_open_dataframe() -> DataFrame

Read the xyz data from the file.

_open

_open() -> Dataset

Interpolate the xyz data onto a regular grid.

SourceCRSFile

Bases: SourceMixin, SourceFile

Source dataset with CRS support from file to open with xarray.open_dataset.

SourceCRSIntake

Bases: SourceMixin, SourceIntake

Source dataset with CRS support from intake catalog.

SourceCRSDataset

Bases: SourceMixin, SourceDataset

Source dataset with CRS support from an existing xarray Dataset object.

SourceCRSWavespectra

Bases: SourceMixin, SourceWavespectra

Source dataset with CRS support from wavespectra reader.

Note

Default values are provided for crs, x_dim and y_dim fields as they are common to most wavespectra datasets.

Functions

set_defaults classmethod

set_defaults(values)

Set default values for wavespectra-specific fields.

SourceCRSOceantide

Bases: SourceMixin, SourceOceantide

Source dataset with CRS support from intake catalog.

Functions

set_defaults classmethod

set_defaults(values)

Set default values for oceantide-specific fields.