Processes Module

Processes module for environmental model computation and I/O.

This module provides tools for: - Model execution (SWAN, read_copla, CSHORE, CoastalME) - Data processing and computation - Wave analysis and calculations - File I/O for various model formats

The processes module provides comprehensive tools for environmental model execution, data processing, and analysis of coastal, wave, and hydrological processes.

Data Loading Functions

Model Output Readers

create_mesh_dictionary(fname[, uf])

Load mesh parameters from Excel file into dictionary.

read_cshore(file_, path)

Load CSHORE model output files.

read_copla(fname[, grid])

Load COPLA model velocity field output.

read_swan(fname[, grid, vars_])

Load SWAN wave model output from MATLAB file.

delft_raw_files_point(point, mesh_filename, ...)

Extract time series at specific point from Delft3D model outputs.

delft_raw_files(folder, vars_, case_id_)

Load Delft3D raw output files for a single case.

Computation Functions

Data Processing

create_db(params, data[, mesh, time_, ...])

Create the project folder with the initialized files for SWAN and Copla models.

create_mesh(params[, mesh])

Create a computational mesh for the model domain.

create_xarray(x, y[, time_, vars_])

Create a 2D or 3D xarray Dataset with specified fields.

slopes(data[, variable])

Compute the bottom slopes in the direction of a specified variable.

save_db(time_, grid, data, params)

Create and save xarray Dataset with computed model results for a time step.

clean(params)

Remove temporary computation directory tree if deletion is enabled.

Sediment Transport

sediment_transport_Kobayashi(j, data, grid, ...)

Calculate suspended and bed-load transport following Kobayashi et al. (2008).

sediment_transport_CERC(data, params, theta_c)

Calculate longshore sediment transport using CERC formula.

Model Execution

nesting(k, l, params, data)

Execute nested SWAN and COPLA model runs for a specific time step.

run_swan(swan_executable_path, working_directory)

Execute SWAN (Simulating WAves Nearshore) model.

run_copla(copla_executable_path, ...)

Execute COPLA (Coastal Profile Algorithm) model.

run_cshore(cshore_executable_path, ...)

Execute CSHORE (Coastal Storm Hindcast of Reshaping and Erosion) model.

run_coastalme(coastalme_executable_path, ...)

Run CoastalME model in the specified directory.

Coastal Morphology

equilibrium_plan_shape(params, data)

Compute equilibrium planform shape using parabolic bay equation.

coastline_evolution(coastlines, points)

Track coastline position changes over time at specific points.

Hydrology

precipitation_to_flow(data, info)

Convert precipitation time series to streamflow using SCS Curve Number method.

wet_soil(window, cn)

Determine if soil is in wet condition based on rainfall history.

dry_soil(window, cn)

Determine if soil is in dry condition based on antecedent dry period.

unit_hydrograph_model(df, info)

Transform rainfall to discharge using SCS Unit Hydrograph method.

base_flow(window, df, info)

Compute base flow using exponential recession model.

distribute_precipitation(data, pattern, df, info)

Distribute precipitation data temporally according to SCS rainfall pattern.

cumulative_by_events(df[, eps])

Compute cumulative sum of precipitation resetting between storm events.

hydraulic_radius(channel_info[, type_])

Calculate hydraulic properties of open channel cross-sections.

water_elevation([type_])

Generate objective function for water depth calculation using Manning's equation.

settling_velocity(ds, info[, type_])

Calculate sediment particle settling velocity in water.

river_sediment_transport(df, info[, type_])

Calculate river bed-load sediment transport rate using various formulas.

storm_surge_from_waves(data, location[, ...])

Compute storm surge elevation from significant wave height.

flood_fill(c, r, mask)

Perform flood fill algorithm on a binary mask to identify connected regions.

Physical Properties

EOS_sea_water(T, S)

Compute density of seawater using equation of state (EOS).

bulk_fluid_density(T, S, C[, rhos])

Compute bulk fluid density from suspended sediment concentration.

Wave Analysis Functions

Wave Parameters

frequency_limits(Te)

Obtain cutoff frequencies for Baquerizo's wave separation method.

wave_number(t, h)

Calculate wave number from dispersion relation.

calculate_wave_reflection(T, mdat, t, xsn, h, dt)

Calculate wave reflection parameters from multi-sensor measurements.

closure_depth(data[, Hallermeier])

Compute closure depth using Hallermeier or Birkemeier empirical formula.

zero_cross(ts, dt)

Analyze time series using zero-upcrossing method.

Spectral Analysis

clsquare_s(eta, x, h, dt, eps, f1, f2)

Calculate complex amplitudes of incident and reflected wave trains.

Sediment Properties

fall_velocity(d, T, S)

Estimate sediment particle fall velocity using Soulsby's (1997) formula.

environmentaltools.processes.density(T, S)[source]

Estimate water density from temperature and salinity.

Uses empirical approximation for seawater density as function of temperature and salinity.

Parameters:
  • T (float) – Water temperature (°C)

  • S (float) – Salinity (‰ or ppt)

Returns:

rho – Water density (kg/m³)

Return type:

float

Notes

Approximation from Van Rijn (1993):

ρ = 1000 + 1.455 * CL - 6.5×10⁻³ * (T - 4 + 0.4*CL)²

where CL = (S - 0.03) / 1.805 is chlorinity.

Valid for typical oceanographic conditions (S = 0-40‰, T = 0-30°C).

References

Van Rijn, L. C. (1993). Principles of sediment transport in rivers, estuaries and coastal seas. Aqua Publications.

environmentaltools.processes.kinematic_viscosity(T)[source]

Estimate kinematic viscosity of water from temperature.

Calculates temperature-dependent kinematic viscosity using empirical formula.

Parameters:

T (float) – Water temperature (°C)

Returns:

kvis – Kinematic viscosity (m²/s)

Return type:

float

Notes

Approximation from Van Rijn (1989). Kinematic viscosity decreases with increasing temperature.

Typical values: - At 0°C: ν ≈ 1.79 × 10⁻⁶ m²/s - At 10°C: ν ≈ 1.31 × 10⁻⁶ m²/s - At 20°C: ν ≈ 1.00 × 10⁻⁶ m²/s

References

Van Rijn, L. C. (1989). Handbook of Sediment Transport by Currents and Waves.

File Writing Functions

Model Input Writers

environmentaltools.processes.write_cshore(properties: dict, folder: str)[source]

Write CSHORE model input file (infile).

Creates the main input file for CSHORE (Coastal Storm Modeling System) with all necessary parameters for beach profile evolution, sediment transport, wave transformation, and coastal structure simulation.

Parameters:
  • properties (dict) –

    Dictionary containing CSHORE model parameters:

    • headerstr

      Project description header

    • ilineint

      Line number option (1: single line, 2: multiple lines)

    • iproflint

      Profile option (0: initial, 1: recorded)

    • isedavint

      Sediment availability (0: unlimited, 1: limited)

    • ipermint

      Permeable layer option (0: no, 1: yes)

    • ioverint

      Overtopping and overflow option

    • iwtranint

      Wave transmission option

    • ipondint

      Ponding option for runup zone

    • infiltint

      Infiltration option

    • iwcintint

      Wave-current interaction option

    • irollint

      Roller model option

    • iwindint

      Wind effects option (0: no wind, 1: with wind)

    • itideint

      Tidal variation option

    • ivegint

      Vegetation option

    • dxfloat

      Node spacing (m)

    • gammafloat

      Breaking parameter

    • d50float

      Median sediment grain size (m)

    • wffloat

      Sediment fall velocity (m/s)

    • sgfloat

      Sediment specific gravity

    • effbfloat

      Suspended load efficiency factor

    • effffloat

      Bed load efficiency factor

    • slpfloat

      Suspended load parameter

    • slpotfloat

      Suspended load parameter (offshore transport)

    • tanphifloat

      Tangent of internal friction angle

    • blpfloat

      Bed load parameter

    • rwhfloat

      Roller parameter

    • ilabint

      Laboratory or field scale

    • nwaveint

      Number of wave conditions

    • nsurgint

      Number of surge conditions

    • timebc_wavefloat

      Time for boundary condition (s)

    • Tpfloat

      Peak wave period (s)

    • Hrmsfloat

      Root-mean-square wave height (m)

    • Wsetupfloat

      Wave setup (m)

    • swlbcfloat

      Still water level boundary condition (m)

    • anglefloat

      Wave angle (degrees)

    • xnp.ndarray

      Cross-shore coordinates (m)

    • zbnp.ndarray

      Beach elevation (m)

    • fwnp.ndarray

      Bottom friction factor

    • VelVfloat, optional

      Wind velocity (m/s), required if iwind=1

    • DirVfloat, optional

      Wind direction (degrees), required if iwind=1

    • slgradientfloat, optional

      Sea level gradient, required if itide=1

  • folder (str) – Directory path where the input file will be created

Returns:

Creates ‘infile’ in the specified folder

Return type:

None

Notes

The function creates a formatted text file following CSHORE input specifications:

  • Model control parameters (lines, profile, sediment options)

  • Physical parameters (grid spacing, breaking, sediment properties)

  • Boundary conditions (waves, wind, tide)

  • Bathymetric profile data

Wind and tide data are conditionally written based on iwind and itide flags.

Examples

>>> props = {
...     'header': 'Beach Profile Simulation',
...     'iline': 1, 'iprofl': 0, 'isedav': 1,
...     'dx': 1.0, 'gamma': 0.4, 'd50': 0.0003,
...     'Hrms': 2.5, 'Tp': 8.0, 'angle': 0.0,
...     'x': np.arange(0, 500, 1.0),
...     'zb': np.linspace(-5, 3, 500),
...     # ... more parameters
... }
>>> write_cshore(props, './cshore_run')
environmentaltools.processes.write_swan(i, index_, case_id, data, params, mesh='global', local=False, nested=False)[source]

Write SWAN model input files (swaninit and input file).

Creates initialization and input files for SWAN (Simulating WAves Nearshore) spectral wave model, including grid definition, boundary conditions, physical processes, and output specifications.

Parameters:
  • i (int) – Time step counter (0-indexed)

  • index (pd.Timestamp or datetime-like) – Timestamp for current simulation time

  • case_id (str) – Case identifier (e.g., ‘0001’, ‘0002’)

  • data (pd.DataFrame) –

    Time series with boundary condition data containing columns:

    • etafloat

      Water level (m)

    • Hsfloat

      Significant wave height (m)

    • Tpfloat

      Peak wave period (s)

    • DirMfloat

      Mean wave direction (degrees, nautical convention)

    • Vvfloat

      Wind velocity (m/s)

    • DirVfloat

      Wind direction (degrees)

  • params (dict) –

    Model configuration parameters:

    • directorystr

      Working directory path

    • project_namestr

      Project identifier

    • {mesh}_coords_xfloat

      Grid origin x-coordinate (m)

    • {mesh}_coords_yfloat

      Grid origin y-coordinate (m)

    • {mesh}_anglefloat

      Grid rotation angle (degrees)

    • {mesh}_length_xfloat

      Grid extent in x-direction (m)

    • {mesh}_length_yfloat

      Grid extent in y-direction (m)

    • {mesh}_nodes_xint

      Number of grid nodes in x-direction

    • {mesh}_nodes_yint

      Number of grid nodes in y-direction

    • {mesh}_inc_xfloat

      Grid spacing in x-direction (m)

    • {mesh}_inc_yfloat

      Grid spacing in y-direction (m)

  • mesh (str, optional) – Mesh identifier (‘global’ or ‘local’). Default: ‘global’

  • local (bool, optional) – Flag for local mesh (deprecated, not used). Default: False

  • nested (bool, optional) – If True, creates nested grid output for downscaling. Default: False

Returns:

Creates two files in params[‘directory’]/case_id/:

  • swaninit: Initialization file

  • input_{mesh}_{case_id}.swn: SWAN command file

Return type:

None

Notes

The function generates SWAN input files with:

Grid Configuration:

  • Regular Cartesian grid with specified origin, extent, and resolution

  • Directional discretization: 36 bins (10° resolution)

  • Frequency range: 0.05-0.50 Hz

Boundary Conditions:

  • Global mesh: JONSWAP spectrum with constant parameters

  • Local mesh: Nested boundary from parent grid

  • Two-sided boundaries (North/South and East/West)

Physical Processes:

  • Wave generation (GEN3 with exponential growth)

  • Triad and quadruplet wave-wave interactions

  • Depth-induced breaking and whitecapping

  • Wave setup and diffraction

Output:

  • Nested mode: Boundary conditions for nested grid

  • Standard mode: Wave parameters on computational grid (Hs, Tp, Dir, etc.)

Direction convention: SWAN uses nautical convention (waves coming from), automatically converted from PdE convention (270 - angle).

Examples

>>> import pandas as pd
>>> data = pd.DataFrame({
...     'eta': [0.5], 'Hs': [2.0], 'Tp': [8.0],
...     'DirM': [45.0], 'Vv': [10.0], 'DirV': [90.0]
... })
>>> params = {
...     'directory': './swan_run',
...     'project_name': 'Beach_Wave_Modeling',
...     'global_coords_x': 0, 'global_coords_y': 0,
...     'global_angle': 0, 'global_length_x': 1000,
...     'global_length_y': 500, 'global_nodes_x': 101,
...     'global_nodes_y': 51, # ... more parameters
... }
>>> write_swan(0, data.index[0], '0001', data, params, mesh='global')
environmentaltools.processes.write_copla(i, index_, case_id, data, params, mesh='local')[source]

Write COPLA model input files for nearshore profile evolution.

Creates input files for COPLA (Coupled Profile and Area) model, which simulates beach profile evolution and morphodynamics. Reads SWAN wave output and formats it for COPLA computation.

Parameters:
  • i (int) – Time step counter (0-indexed)

  • index (pd.Timestamp or datetime-like) – Timestamp for current simulation time

  • case_id (str) – Case identifier (e.g., ‘0001’, ‘0002’)

  • data (pd.DataFrame) –

    Time series with boundary condition data containing:

    • Hsfloat

      Significant wave height (m)

    • Tpfloat

      Peak wave period (s)

    • DirMfloat

      Mean wave direction (degrees)

    • etafloat

      Water level / tidal elevation (m)

  • params (dict) –

    Model configuration parameters:

    • directorystr

      Working directory path

    • {mesh}_nodes_xint

      Number of cross-shore nodes

    • {mesh}_nodes_yint

      Number of longshore nodes

    • {mesh}_inc_xfloat

      Grid spacing in x-direction (m)

    • {mesh}_inc_yfloat

      Grid spacing in y-direction (m)

  • mesh (str, optional) – Mesh identifier, typically ‘local’. Default: ‘local’

Returns:

Creates three files in params[‘directory’]/case_id/:

  • {case_id}out.dat: Output configuration with wave field from SWAN

  • CLAVE.DAT: Key file with case identifier

  • {case_id}in.dat: Input parameters file

  • {case_id}dat: Calibration and solver parameters

Return type:

None

Notes

The function performs coordinate system transformation:

  • SWAN uses standard coordinates (X: east, Y: north)

  • COPLA uses rotated coordinates: Xc = -Ys, Yc = Xs

  • Wave direction adjusted: Dir_copla = Dir_swan - 90°

File Structure:

{case_id}out.dat contains:

  • Grid dimensions and coordinates

  • Bathymetry from SWAN depth output

  • Wave height field (Hs/2 for amplitude)

  • Wave direction field

{case_id}in.dat specifies:

  • Computational grid parameters

  • Boundary condition type

  • Wave period and tidal level

  • Incident wave amplitude and direction

{case_id}dat contains solver settings:

  • Time step and roughness (Manning coefficient)

  • Eddy viscosity and Coriolis parameter

  • Nonlinear terms and flooding options

NaN values are replaced with 1e-6 for numerical stability.

Examples

>>> import pandas as pd
>>> data = pd.DataFrame({
...     'Hs': [2.0], 'Tp': [8.0],
...     'DirM': [45.0], 'eta': [0.5]
... })
>>> params = {
...     'directory': './copla_run',
...     'local_nodes_x': 50, 'local_nodes_y': 100,
...     'local_inc_x': 5.0, 'local_inc_y': 10.0
... }
>>> write_copla(0, data.index[0], '0001', data, params)
environmentaltools.processes.directory(params, data, global_db, local_db)[source]

Create project directory structure with initialized SWAN model files.

Sets up the complete directory tree for a SWAN modeling project, creating folders for each simulation case and initializing bathymetry and input files for nested grid computations.

Parameters:
  • params (dict) –

    Model configuration parameters containing:

    • directorystr

      Root directory path for the project

  • data (pd.DataFrame) – Time series with boundary conditions, indexed by timestamps. Each row represents one simulation case.

  • global_db (xr.Dataset) –

    Global (coarse) grid dataset containing:

    • depthxr.DataArray

      Bathymetry on global grid (m)

  • local_db (xr.Dataset) –

    Local (fine) grid dataset containing:

    • depthxr.DataArray

      Bathymetry on local nested grid (m)

Returns:

Creates directory structure:

  • params[‘directory’]/: Root project folder

  • params[‘directory’]/####/: Case folders (0001, 0002, …)

Each case folder contains:

  • ####_global.dat: Global grid bathymetry

  • ####_local.dat: Local grid bathymetry

  • swaninit: SWAN initialization file

  • input_global_####.swn: SWAN input file

Return type:

None

Notes

The function performs the following operations:

  1. Creates root project directory (if it doesn’t exist)

  2. Loops through all time steps in data

  3. For each case:

    • Creates numbered subdirectory (####)

    • Writes global and local bathymetry files

    • Generates SWAN input files for nested run

Case numbering is 1-indexed with zero-padding to 4 digits (0001-9999).

The nested flag in write_swan ensures boundary condition files are generated for downscaling from global to local grid.

Examples

>>> import pandas as pd
>>> import xarray as xr
>>> import numpy as np
>>>
>>> # Create sample datasets
>>> data = pd.DataFrame({
...     'Hs': [2.0, 2.5, 3.0],
...     'Tp': [8.0, 9.0, 10.0],
...     'DirM': [45, 60, 75]
... }, index=pd.date_range('2024-01-01', periods=3, freq='6h'))
>>>
>>> global_db = xr.Dataset({
...     'depth': (['y', 'x'], np.random.rand(50, 100) * 10)
... })
>>> local_db = xr.Dataset({
...     'depth': (['y', 'x'], np.random.rand(100, 200) * 10)
... })
>>>
>>> params = {'directory': './swan_project'}
>>> directory(params, data, global_db, local_db)
>>> # Creates: ./swan_project/0001/, ./swan_project/0002/, ./swan_project/0003/