Skip to content

Wave Visualisation

Fluidmec provides reusable scientific visualisation functions for linear regular surface gravity waves.

Installation

The numerical data functions require only NumPy.

For plotting and animation support:

pip install "fluidmec[visualization]"

Regular-wave configuration

from fluidmec.visualization import RegularWave

wave = RegularWave(
    wave_height=2.0,
    period=8.0,
    depth=20.0,
    density=1025.0,
)

print(wave.wavelength)
print(wave.group_velocity)
print(wave.energy_flux)

The configuration is immutable. Dispersion and derived wave quantities are cached when first requested.

Numerical fields

from fluidmec.visualization import wave_field_data

data = wave_field_data(
    wave,
    time=2.0,
    nx=241,
    nz=81,
)

print(data["u"].shape)
print(data["dynamic_pressure"].max())

Field arrays have shape (nz, nx).

All dimensional numerical data use SI units.

Velocity and acceleration

The linear velocity components are

\[ u=\frac{gak}{\omega}C(z)\cos\theta, \]
\[ w=\frac{gak}{\omega}S(z)\sin\theta. \]

Local acceleration is

\[ a_x=gakC(z)\sin\theta, \]
\[ a_z=-gakS(z)\cos\theta. \]

Nonlinear convective acceleration is excluded.

Pressure decomposition

\[ p_d=\rho gaC(z)\cos\theta, \]
\[ p_h=-\rho gz, \]
\[ p_g=p_h+p_d. \]

Numerical pressure data are expressed in Pa. Pressure plots use kPa.

Reusable plots

from fluidmec.visualization import (
    plot_velocity_field,
    plot_pressure_field,
)

fig, ax = plot_velocity_field(wave)

fig.savefig(
    "velocity_field.png",
    dpi=300,
    bbox_inches="tight",
)

fig, ax = plot_pressure_field(
    wave,
    component="dynamic",
)

Plotting functions return figure and axes objects. They do not automatically display, save or close figures.

Existing Matplotlib axes

import matplotlib.pyplot as plt

from fluidmec.visualization import plot_velocity_field

fig, ax = plt.subplots()

plot_velocity_field(wave, ax=ax)

Particle trajectories

import numpy as np

from fluidmec.visualization import particle_orbit_data

time = np.linspace(0, wave.period, 200)

data = particle_orbit_data(
    wave,
    x0=10.0,
    z0=-5.0,
    time=time,
)

Particle coordinates represent first-order closed orbits. Stokes drift is not included.

Particle animation

from fluidmec.visualization import animate_particle_orbits

fig, animation = animate_particle_orbits(
    wave,
    frames=120,
    fps=20,
)

animation.save(
    "particle_motion.gif",
    writer="pillow",
    fps=20,
    dpi=120,
)

The caller must retain the animation object.

Directional wave surfaces

from fluidmec.visualization import plot_directional_surface

fig, ax = plot_directional_surface(
    wave,
    direction_deg=35.0,
)

Direction is measured counterclockwise from the positive x-axis.

Wave groups and energy transport

The regular-wave reference energy is

\[ E=\frac18\rho gH^2. \]

The energy flux per unit crest width is

\[ P=Ec_g. \]

The wave group visualisation uses two nearby frequencies and the finite-depth dispersion relation.

Applicability diagrams

The theory-selection map uses the preliminary screening rules implemented in Fluidmec's wave applicability module.

The boundaries are heuristic and do not guarantee the validity of a particular wave theory.

Scientific limitations

  • First-order linear regular surface gravity waves.
  • Incompressible, inviscid and irrotational flow.
  • Constant water depth and horizontal seabed.
  • No background currents.
  • No nonlinear convective acceleration.
  • No Stokes drift.
  • No breaking-wave or turbulence simulation.
  • Pressure and velocity fields use the mean water column.
  • Three-dimensional surfaces represent directional plane waves, not full three-dimensional CFD.
  • Energy values refer to the reference regular wave.

API reference

Numerical data for regular-wave visualisation.

All dimensional quantities use SI units.

The calculations represent first-order, incompressible, inviscid, irrotational surface gravity waves over a horizontal impermeable seabed.

Coordinates use z = 0 at the still-water level and z = -depth at the seabed.

The numerical functions do not require Matplotlib.

ENGINEERING_GRAVITY module-attribute

ENGINEERING_GRAVITY: Final[float] = 9.81

RegularWave dataclass

Configuration for a linear regular gravity wave.

Parameters:

Name Type Description Default
wave_height float

Non-negative crest-to-trough wave height [m].

required
period float

Positive wave period [s].

required
depth float

Positive still-water depth [m].

required
density float

Positive fluid density [kg/m^3]. Defaults to 1025 kg/m^3.

1025.0
gravity float

Positive gravitational acceleration [m/s^2].

ENGINEERING_GRAVITY
phase_offset float

Initial phase offset [rad].

0.0
Notes

Wave number is obtained from linear dispersion. The configuration does not enforce small-amplitude applicability or guarantee that waves are unbroken.

Use assess_wave_applicability for preliminary physical applicability screening.

Source code in src/fluidmec/visualization/wave_data.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
@dataclass(frozen=True)
class RegularWave:
    """Configuration for a linear regular gravity wave.

    Parameters
    ----------
    wave_height : float
        Non-negative crest-to-trough wave height [m].
    period : float
        Positive wave period [s].
    depth : float
        Positive still-water depth [m].
    density : float, optional
        Positive fluid density [kg/m^3].
        Defaults to 1025 kg/m^3.
    gravity : float, optional
        Positive gravitational acceleration [m/s^2].
    phase_offset : float, optional
        Initial phase offset [rad].

    Notes
    -----
    Wave number is obtained from linear dispersion.
    The configuration does not enforce small-amplitude
    applicability or guarantee that waves are unbroken.

    Use assess_wave_applicability for preliminary
    physical applicability screening.
    """

    wave_height: float
    period: float
    depth: float
    density: float = 1025.0
    gravity: float = ENGINEERING_GRAVITY
    phase_offset: float = 0.0

    def __post_init__(self):
        """Validate and normalise configuration inputs."""
        values = {
            "wave_height": _scalar(
                self.wave_height,
                "Wave height",
                non_negative=True,
            ),
            "period": _scalar(
                self.period, "Period", positive=True
            ),
            "depth": _scalar(
                self.depth, "Depth", positive=True
            ),
            "density": _scalar(
                self.density, "Density", positive=True
            ),
            "gravity": _scalar(
                self.gravity, "Gravity", positive=True
            ),
            "phase_offset": _scalar(
                self.phase_offset, "Phase offset"
            ),
        }

        for name, value in values.items():
            object.__setattr__(self, name, value)

    @property
    def amplitude(self):
        """Wave amplitude H/2 [m]."""
        return self.wave_height / 2.0

    @cached_property
    def omega(self):
        """Angular frequency 2*pi/T [rad/s]."""
        return _scalar(
            2.0 * np.pi / self.period,
            "Angular frequency",
            positive=True,
        )

    @cached_property
    def wave_number(self):
        """Linear dispersion wave number [rad/m]."""
        return solve_wave_number(
            self.period,
            self.depth,
            self.gravity,
        )

    @cached_property
    def wavelength(self):
        """Wavelength 2*pi/k [m]."""
        return _scalar(
            2.0 * np.pi / self.wave_number,
            "Wavelength",
            positive=True,
        )

    @cached_property
    def phase_velocity(self):
        """Linear phase velocity omega/k [m/s]."""
        return self.omega / self.wave_number

    @cached_property
    def group_velocity(self):
        """Linear group velocity [m/s]."""
        return self.phase_velocity * group_velocity_factor(
            self.wave_number * self.depth
        )

    @cached_property
    def energy_density(self):
        """Mean linear-wave energy per unit area [J/m^2]."""
        with np.errstate(over="ignore", invalid="ignore"):
            energy = (
                np.float64(self.density)
                * self.gravity
                * self.wave_height
                * self.wave_height
                / 8.0
            )

        return _scalar(
            energy, "Energy density", non_negative=True
        )

    @cached_property
    def energy_flux(self):
        """Mean energy flux per unit crest width [W/m]."""
        return _scalar(
            self.energy_density * self.group_velocity,
            "Energy flux",
            non_negative=True,
        )

amplitude property

amplitude

Wave amplitude H/2 [m].

omega cached property

omega

Angular frequency 2*pi/T [rad/s].

wave_number cached property

wave_number

Linear dispersion wave number [rad/m].

wavelength cached property

wavelength

Wavelength 2*pi/k [m].

phase_velocity cached property

phase_velocity

Linear phase velocity omega/k [m/s].

group_velocity cached property

group_velocity

Linear group velocity [m/s].

energy_density cached property

energy_density

Mean linear-wave energy per unit area [J/m^2].

energy_flux cached property

energy_flux

Mean energy flux per unit crest width [W/m].

as_float_array

as_float_array(value: ArrayLike, name: str) -> np.ndarray

Convert input to a finite floating-point array.

Source code in src/fluidmec/core/_validation.py
13
14
15
16
17
18
19
20
21
22
23
24
def as_float_array(
    value: ArrayLike,
    name: str,
) -> np.ndarray:
    """Convert input to a finite floating-point array."""

    array = np.asarray(value, dtype=float)

    if not np.all(np.isfinite(array)):
        raise ValueError(f"{name} must be finite.")

    return array

validate_non_negative

validate_non_negative(value: ArrayLike, name: str) -> np.ndarray

Validate non-negative numerical inputs.

Source code in src/fluidmec/core/_validation.py
41
42
43
44
45
46
47
48
49
50
51
52
def validate_non_negative(
    value: ArrayLike,
    name: str,
) -> np.ndarray:
    """Validate non-negative numerical inputs."""

    array = as_float_array(value, name)

    if np.any(array < 0):
        raise ValueError(f"{name} must be non-negative.")

    return array

validate_positive

validate_positive(value: ArrayLike, name: str) -> np.ndarray

Validate strictly positive numerical inputs.

Source code in src/fluidmec/core/_validation.py
27
28
29
30
31
32
33
34
35
36
37
38
def validate_positive(
    value: ArrayLike,
    name: str,
) -> np.ndarray:
    """Validate strictly positive numerical inputs."""

    array = as_float_array(value, name)

    if np.any(array <= 0):
        raise ValueError(f"{name} must be positive.")

    return array

cosh_depth_factor

cosh_depth_factor(wave_number: ArrayLike, z: ArrayLike, depth: ArrayLike) -> float | np.ndarray

Calculate the stable hyperbolic cosine depth factor.

Parameters:

Name Type Description Default
wave_number array_like

Positive wave number in rad/m.

required
z array_like

Vertical coordinate in metres, satisfying -h <= z <= 0.

required
depth array_like

Positive still-water depth in metres.

required

Returns:

Type Description
float or ndarray

Dimensionless cosine depth attenuation factor.

Notes

Governing expression:

C = cosh(k*(z+h))/cosh(k*h)

Stable exponential formulation:

C = exp(k*z)*(1 + exp(-2*k*(z+h)))
    / (1 + exp(-2*k*h))

All exponential arguments are non-positive within the mean water column.

At z = 0, C = 1.

Source code in src/fluidmec/waves/airy.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def cosh_depth_factor(
    wave_number: ArrayLike,
    z: ArrayLike,
    depth: ArrayLike,
) -> float | np.ndarray:
    """Calculate the stable hyperbolic cosine depth factor.

    Parameters
    ----------
    wave_number : array_like
        Positive wave number in rad/m.
    z : array_like
        Vertical coordinate in metres, satisfying -h <= z <= 0.
    depth : array_like
        Positive still-water depth in metres.

    Returns
    -------
    float or numpy.ndarray
        Dimensionless cosine depth attenuation factor.

    Notes
    -----
    Governing expression:

        C = cosh(k*(z+h))/cosh(k*h)

    Stable exponential formulation:

        C = exp(k*z)*(1 + exp(-2*k*(z+h)))
            / (1 + exp(-2*k*h))

    All exponential arguments are non-positive within
    the mean water column.

    At z = 0, C = 1.
    """
    k = validate_positive(wave_number, "Wave number")
    z, h = _validate_vertical_coordinates(z, depth)

    with np.errstate(over="ignore", under="ignore"):
        q = k * (z + h)
        b = k * h

        numerator = 1.0 + np.exp(-2.0 * q)
        denominator = 1.0 + np.exp(-2.0 * b)

        result = np.exp(k * z) * numerator / denominator

    return _finite_result(result, "Cosine depth factor")

group_velocity_factor

group_velocity_factor(dimensionless_depth: ArrayLike) -> float | np.ndarray

Calculate the dimensionless group velocity factor.

Parameters:

Name Type Description Default
dimensionless_depth array_like

Dimensionless water depth kh. Non-negative.

required

Returns:

Type Description
float or ndarray

Group velocity factor n = cg/cp. Values lie between 0.5 and 1.

Notes

Equation:

n = 0.5*(1 + 2*kh/sinh(2*kh))

The shallow-water limit at kh = 0 is defined as n = 1.

An exponential reformulation avoids overflow in sinh. NumPy expm1 reduces cancellation for small arguments.

For kh >= 20, the correction to 0.5 is below ordinary double-precision floating-point resolution.

Examples:

>>> group_velocity_factor(0.0)
1.0
>>> group_velocity_factor(100.0)
0.5
Source code in src/fluidmec/waves/velocity.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def group_velocity_factor(
    dimensionless_depth: ArrayLike,
) -> float | np.ndarray:
    """Calculate the dimensionless group velocity factor.

    Parameters
    ----------
    dimensionless_depth : array_like
        Dimensionless water depth kh. Non-negative.

    Returns
    -------
    float or numpy.ndarray
        Group velocity factor n = cg/cp.
        Values lie between 0.5 and 1.

    Notes
    -----
    Equation:

        n = 0.5*(1 + 2*kh/sinh(2*kh))

    The shallow-water limit at kh = 0 is defined as n = 1.

    An exponential reformulation avoids overflow in sinh.
    NumPy expm1 reduces cancellation for small arguments.

    For kh >= 20, the correction to 0.5 is below ordinary
    double-precision floating-point resolution.

    Examples
    --------
    >>> group_velocity_factor(0.0)
    1.0
    >>> group_velocity_factor(100.0)
    0.5
    """
    kh = validate_non_negative(
        dimensionless_depth,
        "Dimensionless water depth",
    )

    # Restrict exponential evaluation to a safe range.
    # Larger arguments are already at the deep-water limit.
    y = 2.0 * np.minimum(kh, 20.0)

    numerator = 2.0 * y * np.exp(-y)
    denominator = -np.expm1(-2.0 * y)

    # The analytical limit of y/sinh(y) at y=0 is one.
    ratio = np.divide(
        numerator,
        denominator,
        out=np.ones_like(y),
        where=y > 0.0,
    )

    ratio = np.where(kh >= 20.0, 0.0, ratio)

    result = 0.5 * (1.0 + ratio)

    # Protect physical bounds against floating-point roundoff.
    result = np.clip(result, 0.5, 1.0)

    return format_output(result)

sinh_depth_factor

sinh_depth_factor(wave_number: ArrayLike, z: ArrayLike, depth: ArrayLike) -> float | np.ndarray

Calculate the stable hyperbolic sine depth factor.

Parameters:

Name Type Description Default
wave_number array_like

Positive wave number in rad/m.

required
z array_like

Vertical coordinate in metres, satisfying -h <= z <= 0.

required
depth array_like

Positive still-water depth in metres.

required

Returns:

Type Description
float or ndarray

Dimensionless sine depth attenuation factor.

Notes

Governing expression:

S = sinh(k*(z+h))/cosh(k*h)

Stable exponential formulation:

S = exp(k*z)*(1 - exp(-2*k*(z+h)))
    / (1 + exp(-2*k*h))

NumPy expm1 is used to reduce cancellation close to the seabed.

At z = -h, S = 0. At z = 0, S = tanh(k*h).

Source code in src/fluidmec/waves/airy.py
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def sinh_depth_factor(
    wave_number: ArrayLike,
    z: ArrayLike,
    depth: ArrayLike,
) -> float | np.ndarray:
    """Calculate the stable hyperbolic sine depth factor.

    Parameters
    ----------
    wave_number : array_like
        Positive wave number in rad/m.
    z : array_like
        Vertical coordinate in metres, satisfying -h <= z <= 0.
    depth : array_like
        Positive still-water depth in metres.

    Returns
    -------
    float or numpy.ndarray
        Dimensionless sine depth attenuation factor.

    Notes
    -----
    Governing expression:

        S = sinh(k*(z+h))/cosh(k*h)

    Stable exponential formulation:

        S = exp(k*z)*(1 - exp(-2*k*(z+h)))
            / (1 + exp(-2*k*h))

    NumPy expm1 is used to reduce cancellation
    close to the seabed.

    At z = -h, S = 0.
    At z = 0, S = tanh(k*h).
    """
    k = validate_positive(wave_number, "Wave number")
    z, h = _validate_vertical_coordinates(z, depth)

    with np.errstate(over="ignore", under="ignore"):
        q = k * (z + h)
        b = k * h

        numerator = -np.expm1(-2.0 * q)
        denominator = 1.0 + np.exp(-2.0 * b)

        result = np.exp(k * z) * numerator / denominator

    return _finite_result(result, "Sine depth factor")

solve_wave_number

solve_wave_number(period: ArrayLike, depth: ArrayLike, gravity: ArrayLike = ENGINEERING_GRAVITY, *, method: str = 'newton', tolerance: float = 1e-10, max_iterations: int = 100) -> float | np.ndarray

Solve the linear wave dispersion relation for k.

Parameters:

Name Type Description Default
period array_like

Wave period T, in seconds. Positive.

required
depth array_like

Still-water depth h, in metres. Positive.

required
gravity array_like

Gravitational acceleration g, in m/s^2.

ENGINEERING_GRAVITY
method (newton, bisection)

Safeguarded Newton-Raphson or bisection.

"newton"
tolerance float

Relative dimensionless residual tolerance. Must be between zero and one, exclusive.

1e-10
max_iterations int

Maximum number of solver evaluations.

100

Returns:

Type Description
float or ndarray

Positive wave-number magnitude k, in rad/m.

Raises:

Type Description
ValueError

If physical inputs or solver options are invalid.

RuntimeError

If the solver does not converge.

Notes

Solves:

x*tanh(x) = mu

where x = kh and mu = omega**2h/g.

Convergence criterion:

abs(x*tanh(x) - mu) / mu <= tolerance

Newton steps outside the root bracket are replaced by bisection steps.

Supports NumPy broadcasting. Every array element must converge before the function returns.

The result is based on linear gravity wave theory, without current or surface tension.

Source code in src/fluidmec/waves/dispersion.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def solve_wave_number(
    period: ArrayLike,
    depth: ArrayLike,
    gravity: ArrayLike = ENGINEERING_GRAVITY,
    *,
    method: str = "newton",
    tolerance: float = 1e-10,
    max_iterations: int = 100,
) -> float | np.ndarray:
    """Solve the linear wave dispersion relation for k.

    Parameters
    ----------
    period : array_like
        Wave period T, in seconds. Positive.
    depth : array_like
        Still-water depth h, in metres. Positive.
    gravity : array_like, optional
        Gravitational acceleration g, in m/s^2.
    method : {"newton", "bisection"}, optional
        Safeguarded Newton-Raphson or bisection.
    tolerance : float, optional
        Relative dimensionless residual tolerance.
        Must be between zero and one, exclusive.
    max_iterations : int, optional
        Maximum number of solver evaluations.

    Returns
    -------
    float or numpy.ndarray
        Positive wave-number magnitude k, in rad/m.

    Raises
    ------
    ValueError
        If physical inputs or solver options are invalid.
    RuntimeError
        If the solver does not converge.

    Notes
    -----
    Solves:

        x*tanh(x) = mu

    where x = k*h and mu = omega**2*h/g.

    Convergence criterion:

        abs(x*tanh(x) - mu) / mu <= tolerance

    Newton steps outside the root bracket are replaced
    by bisection steps.

    Supports NumPy broadcasting. Every array element must
    converge before the function returns.

    The result is based on linear gravity wave theory,
    without current or surface tension.
    """
    tolerance = _validate_solver_options(
        method,
        tolerance,
        max_iterations,
    )

    period = validate_positive(period, "Wave period")
    depth = validate_positive(depth, "Water depth")
    gravity = validate_positive(gravity, "Gravity")

    period, depth, gravity = np.broadcast_arrays(
        period,
        depth,
        gravity,
    )

    omega = 2.0 * np.pi / period

    with np.errstate(
        over="ignore",
        under="ignore",
        invalid="ignore",
    ):
        mu = omega**2 * depth / gravity

    if np.any(~np.isfinite(mu)) or np.any(mu <= 0):
        raise ValueError("Inputs exceed the supported numerical range.")

    # The limiting solutions are:
    # Deep water: x = mu
    # Shallow water: x = sqrt(mu)
    #
    # Twice the larger limiting value provides an
    # upper bracket for ordinary positive inputs.
    estimate = np.maximum(mu, np.sqrt(mu))

    lower = np.zeros_like(mu)
    upper = 2.0 * estimate

    if np.any(~np.isfinite(upper)):
        raise ValueError("Unable to construct a finite root bracket.")

    if np.any(_dimensionless_residual(upper, mu) < 0):
        raise RuntimeError("Unable to bracket the dispersion root.")

    x = estimate.copy()

    for _ in range(max_iterations):
        residual = _dimensionless_residual(x, mu)

        converged = np.abs(residual) / mu <= tolerance

        if np.all(converged):
            result = x / depth

            if np.any(~np.isfinite(result)) or np.any(result <= 0):
                raise ValueError("Wave number exceeds numerical range.")

            return format_output(result)

        active = ~converged

        lower = np.where(
            active & (residual < 0),
            x,
            lower,
        )

        upper = np.where(
            active & (residual > 0),
            x,
            upper,
        )

        midpoint = lower + 0.5 * (upper - lower)

        if method == "newton":
            derivative = _dimensionless_derivative(x)

            with np.errstate(
                divide="ignore",
                invalid="ignore",
                over="ignore",
            ):
                candidate = x - residual / derivative

            valid_step = (
                np.isfinite(candidate) & (candidate > lower) & (candidate < upper)
            )

            next_x = np.where(
                valid_step,
                candidate,
                midpoint,
            )

        else:
            next_x = midpoint

        # Preserve array elements that have converged.
        x = np.where(active, next_x, x)

    raise RuntimeError(
        f"Wave dispersion solver did not converge within {max_iterations} iterations."
    )

_scalar

_scalar(value, name, *, positive=False, non_negative=False)

Validate a finite scalar configuration value.

Source code in src/fluidmec/visualization/wave_data.py
35
36
37
38
39
40
41
42
43
44
45
46
47
def _scalar(value, name, *, positive=False, non_negative=False):
    """Validate a finite scalar configuration value."""
    if positive:
        result = validate_positive(value, name)
    elif non_negative:
        result = validate_non_negative(value, name)
    else:
        result = as_float_array(value, name)

    if result.ndim != 0:
        raise ValueError(f"{name} must be scalar.")

    return float(result)

_count

_count(value, name, minimum=2)

Validate an integer grid or sample count.

Source code in src/fluidmec/visualization/wave_data.py
50
51
52
53
54
55
56
57
58
59
60
61
def _count(value, name, minimum=2):
    """Validate an integer grid or sample count."""
    if (
        isinstance(value, (bool, np.bool_))
        or not isinstance(value, (int, np.integer))
        or value < minimum
    ):
        raise ValueError(
            f"{name} must be an integer >= {minimum}."
        )

    return int(value)

_finite_fields

_finite_fields(data)

Reject nonfinite numerical outputs.

Source code in src/fluidmec/visualization/wave_data.py
64
65
66
67
68
69
70
71
72
def _finite_fields(data):
    """Reject nonfinite numerical outputs."""
    for name, value in data.items():
        if not np.all(np.isfinite(value)):
            raise ValueError(
                f"{name} exceeds the supported numerical range."
            )

    return data

wave_field_data

wave_field_data(wave: RegularWave, time: float = 0.0, *, wavelengths: float = 2.0, nx: int = 241, nz: int = 81) -> dict

Evaluate linear wave fields on a rectangular grid.

Parameters:

Name Type Description Default
wave RegularWave

Validated regular-wave configuration.

required
time float

Evaluation time [s].

0.0
wavelengths float

Positive horizontal domain length in wavelengths.

2.0
nx int

Horizontal and vertical grid sample counts.

241
nz int

Horizontal and vertical grid sample counts.

241

Returns:

Type Description
dict

x, z : one-dimensional coordinates [m]. X, Z : two-dimensional mesh coordinates [m]. eta : surface elevation along x [m]. u, w : velocity components [m/s]. speed : velocity magnitude [m/s]. ax, az : local acceleration components [m/s^2]. acceleration : acceleration magnitude [m/s^2]. dynamic_pressure : pressure perturbation [Pa]. hydrostatic_pressure : hydrostatic gauge pressure [Pa]. gauge_pressure : total linearised gauge pressure [Pa].

Notes

Field arrays have shape (nz, nx). The domain is the mean water column, not the instantaneous moving free-surface domain.

Acceleration is first-order local acceleration; nonlinear convective acceleration is excluded.

Source code in src/fluidmec/visualization/wave_data.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def wave_field_data(
    wave: RegularWave,
    time: float = 0.0,
    *,
    wavelengths: float = 2.0,
    nx: int = 241,
    nz: int = 81,
) -> dict:
    """Evaluate linear wave fields on a rectangular grid.

    Parameters
    ----------
    wave : RegularWave
        Validated regular-wave configuration.
    time : float, optional
        Evaluation time [s].
    wavelengths : float, optional
        Positive horizontal domain length in wavelengths.
    nx, nz : int, optional
        Horizontal and vertical grid sample counts.

    Returns
    -------
    dict
        x, z : one-dimensional coordinates [m].
        X, Z : two-dimensional mesh coordinates [m].
        eta : surface elevation along x [m].
        u, w : velocity components [m/s].
        speed : velocity magnitude [m/s].
        ax, az : local acceleration components [m/s^2].
        acceleration : acceleration magnitude [m/s^2].
        dynamic_pressure : pressure perturbation [Pa].
        hydrostatic_pressure : hydrostatic gauge pressure [Pa].
        gauge_pressure : total linearised gauge pressure [Pa].

    Notes
    -----
    Field arrays have shape (nz, nx).
    The domain is the mean water column, not the
    instantaneous moving free-surface domain.

    Acceleration is first-order local acceleration;
    nonlinear convective acceleration is excluded.
    """
    time = _scalar(time, "Time")
    wavelengths = _scalar(
        wavelengths, "Domain wavelengths", positive=True
    )
    nx = _count(nx, "nx")
    nz = _count(nz, "nz")

    k = wave.wave_number
    omega = wave.omega
    a = wave.amplitude
    g = wave.gravity

    x = np.linspace(
        0.0, wavelengths * wave.wavelength, nx
    )
    z = np.linspace(-wave.depth, 0.0, nz)

    X, Z = np.meshgrid(x, z)

    theta = k * X - omega * time + wave.phase_offset

    C = cosh_depth_factor(k, Z, wave.depth)
    S = sinh_depth_factor(k, Z, wave.depth)

    velocity_scale = g * a * k / omega
    acceleration_scale = g * a * k

    u = velocity_scale * C * np.cos(theta)
    w = velocity_scale * S * np.sin(theta)

    ax = acceleration_scale * C * np.sin(theta)
    az = -acceleration_scale * S * np.cos(theta)

    pd = wave.density * g * a * C * np.cos(theta)
    ph = -wave.density * g * Z

    eta = a * np.cos(
        k * x - omega * time + wave.phase_offset
    )

    return _finite_fields({
        "x": x,
        "z": z,
        "X": X,
        "Z": Z,
        "eta": eta,
        "u": u,
        "w": w,
        "speed": np.hypot(u, w),
        "ax": ax,
        "az": az,
        "acceleration": np.hypot(ax, az),
        "dynamic_pressure": pd,
        "hydrostatic_pressure": ph,
        "gauge_pressure": ph + pd,
    })

particle_orbit_data

particle_orbit_data(wave: RegularWave, x0, z0, time) -> dict

Calculate first-order particle orbital coordinates.

Parameters:

Name Type Description Default
wave RegularWave

Regular-wave configuration.

required
x0 array_like

Mean horizontal particle positions [m].

required
z0 array_like

Mean vertical positions [m], within [-depth, 0].

required
time array_like

Evaluation times [s].

required

Returns:

Type Description
dict

X, Z : instantaneous particle positions [m]. xi, zeta : first-order displacements [m]. horizontal_radius, vertical_radius : orbital semi-axis lengths [m].

Notes

Inputs follow standard NumPy broadcasting rules. These trajectories are first-order closed orbits. Stokes drift and nonlinear particle advection are not represented.

Source code in src/fluidmec/visualization/wave_data.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def particle_orbit_data(
    wave: RegularWave,
    x0,
    z0,
    time,
) -> dict:
    """Calculate first-order particle orbital coordinates.

    Parameters
    ----------
    wave : RegularWave
        Regular-wave configuration.
    x0 : array_like
        Mean horizontal particle positions [m].
    z0 : array_like
        Mean vertical positions [m], within [-depth, 0].
    time : array_like
        Evaluation times [s].

    Returns
    -------
    dict
        X, Z : instantaneous particle positions [m].
        xi, zeta : first-order displacements [m].
        horizontal_radius, vertical_radius : orbital
            semi-axis lengths [m].

    Notes
    -----
    Inputs follow standard NumPy broadcasting rules.
    These trajectories are first-order closed orbits.
    Stokes drift and nonlinear particle advection
    are not represented.
    """
    x0 = as_float_array(x0, "Mean x")
    z0 = as_float_array(z0, "Mean z")
    time = as_float_array(time, "Time")

    x0, z0, time = np.broadcast_arrays(
        x0, z0, time
    )

    k = wave.wave_number
    omega = wave.omega

    C = cosh_depth_factor(k, z0, wave.depth)
    S = sinh_depth_factor(k, z0, wave.depth)

    scale = (
        wave.gravity * wave.amplitude * k / omega**2
    )

    A = scale * C
    B = scale * S

    theta = k * x0 - omega * time + wave.phase_offset

    xi = -A * np.sin(theta)
    zeta = B * np.cos(theta)

    return _finite_fields({
        "X": x0 + xi,
        "Z": z0 + zeta,
        "xi": xi,
        "zeta": zeta,
        "horizontal_radius": A,
        "vertical_radius": B,
    })

directional_surface_data

directional_surface_data(wave: RegularWave, time: float = 0.0, *, direction_deg: float = 0.0, wavelengths: float = 2.0, nx: int = 121, ny: int = 121) -> dict

Calculate a directional linear plane-wave surface.

Parameters:

Name Type Description Default
wave RegularWave

Regular-wave configuration.

required
time float

Evaluation time [s].

0.0
direction_deg float

Propagation direction measured counterclockwise from the positive x-axis [degrees].

0.0
wavelengths float

Side length of the square domain in wavelengths.

2.0
nx int

Grid sample counts.

121
ny int

Grid sample counts.

121

Returns:

Type Description
dict

X, Y : horizontal mesh coordinates [m]. eta : surface elevation [m]. kx, ky : directional wave-number components [rad/m].

Notes

This is a directional plane wave, not a nonlinear three-dimensional free-surface flow solution.

Source code in src/fluidmec/visualization/wave_data.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
def directional_surface_data(
    wave: RegularWave,
    time: float = 0.0,
    *,
    direction_deg: float = 0.0,
    wavelengths: float = 2.0,
    nx: int = 121,
    ny: int = 121,
) -> dict:
    """Calculate a directional linear plane-wave surface.

    Parameters
    ----------
    wave : RegularWave
        Regular-wave configuration.
    time : float, optional
        Evaluation time [s].
    direction_deg : float, optional
        Propagation direction measured counterclockwise
        from the positive x-axis [degrees].
    wavelengths : float, optional
        Side length of the square domain in wavelengths.
    nx, ny : int, optional
        Grid sample counts.

    Returns
    -------
    dict
        X, Y : horizontal mesh coordinates [m].
        eta : surface elevation [m].
        kx, ky : directional wave-number components [rad/m].

    Notes
    -----
    This is a directional plane wave, not a nonlinear
    three-dimensional free-surface flow solution.
    """
    time = _scalar(time, "Time")
    direction_deg = _scalar(
        direction_deg, "Direction"
    )
    wavelengths = _scalar(
        wavelengths, "Domain wavelengths", positive=True
    )
    nx = _count(nx, "nx")
    ny = _count(ny, "ny")

    beta = np.deg2rad(direction_deg % 360.0)

    kx = wave.wave_number * np.cos(beta)
    ky = wave.wave_number * np.sin(beta)

    length = wavelengths * wave.wavelength

    x = np.linspace(0.0, length, nx)
    y = np.linspace(0.0, length, ny)

    X, Y = np.meshgrid(x, y)

    theta = (
        kx * X
        + ky * Y
        - wave.omega * time
        + wave.phase_offset
    )

    return _finite_fields({
        "X": X,
        "Y": Y,
        "eta": wave.amplitude * np.cos(theta),
        "kx": kx,
        "ky": ky,
    })

wave_packet_data

wave_packet_data(wave: RegularWave, time: float = 0.0, *, frequency_fraction: float = 0.05, wavelengths: float = 20.0, nx: int = 2001) -> dict

Calculate a two-frequency dispersive wave group.

Parameters:

Name Type Description Default
wave RegularWave

Reference wave configuration.

required
time float

Evaluation time [s].

0.0
frequency_fraction float

Fractional angular-frequency half-separation. Must lie strictly between zero and one.

0.05
wavelengths float

Domain length in reference wavelengths.

20.0
nx int

Horizontal sample count.

2001

Returns:

Type Description
dict

x : horizontal coordinate [m]. eta : superposed wave elevation [m]. envelope : absolute modulation envelope [m]. envelope_velocity : finite-difference group speed [m/s]. phase_velocity : carrier phase speed [m/s]. group_velocity : reference analytical group speed [m/s]. energy_density : reference wave energy [J/m^2]. energy_flux : reference wave energy flux [W/m].

Notes

Each component has half the reference amplitude. The maximum combined envelope equals the reference amplitude.

The reference energy and flux are for the original regular wave, not the mean energy of the two-wave superposition.

Source code in src/fluidmec/visualization/wave_data.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
def wave_packet_data(
    wave: RegularWave,
    time: float = 0.0,
    *,
    frequency_fraction: float = 0.05,
    wavelengths: float = 20.0,
    nx: int = 2001,
) -> dict:
    """Calculate a two-frequency dispersive wave group.

    Parameters
    ----------
    wave : RegularWave
        Reference wave configuration.
    time : float, optional
        Evaluation time [s].
    frequency_fraction : float, optional
        Fractional angular-frequency half-separation.
        Must lie strictly between zero and one.
    wavelengths : float, optional
        Domain length in reference wavelengths.
    nx : int, optional
        Horizontal sample count.

    Returns
    -------
    dict
        x : horizontal coordinate [m].
        eta : superposed wave elevation [m].
        envelope : absolute modulation envelope [m].
        envelope_velocity : finite-difference group speed [m/s].
        phase_velocity : carrier phase speed [m/s].
        group_velocity : reference analytical group speed [m/s].
        energy_density : reference wave energy [J/m^2].
        energy_flux : reference wave energy flux [W/m].

    Notes
    -----
    Each component has half the reference amplitude.
    The maximum combined envelope equals the reference
    amplitude.

    The reference energy and flux are for the original
    regular wave, not the mean energy of the two-wave
    superposition.
    """
    time = _scalar(time, "Time")
    fraction = _scalar(
        frequency_fraction,
        "Frequency fraction",
        positive=True,
    )

    if fraction >= 1.0:
        raise ValueError(
            "Frequency fraction must be less than one."
        )

    wavelengths = _scalar(
        wavelengths, "Domain wavelengths", positive=True
    )
    nx = _count(nx, "nx")

    omega1 = wave.omega * (1.0 - fraction)
    omega2 = wave.omega * (1.0 + fraction)

    k1 = solve_wave_number(
        2.0 * np.pi / omega1,
        wave.depth,
        wave.gravity,
    )
    k2 = solve_wave_number(
        2.0 * np.pi / omega2,
        wave.depth,
        wave.gravity,
    )

    delta_k = k2 - k1
    delta_omega = omega2 - omega1

    if delta_k <= 0.0 or delta_omega <= 0.0:
        raise ValueError(
            "Frequency separation is numerically unresolved."
        )

    x = np.linspace(
        0.0, wavelengths * wave.wavelength, nx
    )

    phase1 = k1 * x - omega1 * time + wave.phase_offset
    phase2 = k2 * x - omega2 * time + wave.phase_offset

    eta = (
        wave.amplitude / 2.0
        * (np.cos(phase1) + np.cos(phase2))
    )

    envelope = wave.amplitude * np.abs(
        np.cos(
            (delta_k * x - delta_omega * time) / 2.0
        )
    )

    return _finite_fields({
        "x": x,
        "eta": eta,
        "envelope": envelope,
        "envelope_velocity": delta_omega / delta_k,
        "phase_velocity": (omega1 + omega2) / (k1 + k2),
        "group_velocity": wave.group_velocity,
        "energy_density": wave.energy_density,
        "energy_flux": wave.energy_flux,
    })

Reusable scientific plots for linear regular waves.

Plotting functions return Matplotlib figure and axes objects. They do not call show(), savefig() or close().

The user owns the returned figure and its lifecycle.

BLUE module-attribute

BLUE = '#176B9B'

NAVY module-attribute

NAVY = '#15324A'

ORANGE module-attribute

ORANGE = '#D97732'

GREEN module-attribute

GREEN = '#20866C'

RegularWave dataclass

Configuration for a linear regular gravity wave.

Parameters:

Name Type Description Default
wave_height float

Non-negative crest-to-trough wave height [m].

required
period float

Positive wave period [s].

required
depth float

Positive still-water depth [m].

required
density float

Positive fluid density [kg/m^3]. Defaults to 1025 kg/m^3.

1025.0
gravity float

Positive gravitational acceleration [m/s^2].

ENGINEERING_GRAVITY
phase_offset float

Initial phase offset [rad].

0.0
Notes

Wave number is obtained from linear dispersion. The configuration does not enforce small-amplitude applicability or guarantee that waves are unbroken.

Use assess_wave_applicability for preliminary physical applicability screening.

Source code in src/fluidmec/visualization/wave_data.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
@dataclass(frozen=True)
class RegularWave:
    """Configuration for a linear regular gravity wave.

    Parameters
    ----------
    wave_height : float
        Non-negative crest-to-trough wave height [m].
    period : float
        Positive wave period [s].
    depth : float
        Positive still-water depth [m].
    density : float, optional
        Positive fluid density [kg/m^3].
        Defaults to 1025 kg/m^3.
    gravity : float, optional
        Positive gravitational acceleration [m/s^2].
    phase_offset : float, optional
        Initial phase offset [rad].

    Notes
    -----
    Wave number is obtained from linear dispersion.
    The configuration does not enforce small-amplitude
    applicability or guarantee that waves are unbroken.

    Use assess_wave_applicability for preliminary
    physical applicability screening.
    """

    wave_height: float
    period: float
    depth: float
    density: float = 1025.0
    gravity: float = ENGINEERING_GRAVITY
    phase_offset: float = 0.0

    def __post_init__(self):
        """Validate and normalise configuration inputs."""
        values = {
            "wave_height": _scalar(
                self.wave_height,
                "Wave height",
                non_negative=True,
            ),
            "period": _scalar(
                self.period, "Period", positive=True
            ),
            "depth": _scalar(
                self.depth, "Depth", positive=True
            ),
            "density": _scalar(
                self.density, "Density", positive=True
            ),
            "gravity": _scalar(
                self.gravity, "Gravity", positive=True
            ),
            "phase_offset": _scalar(
                self.phase_offset, "Phase offset"
            ),
        }

        for name, value in values.items():
            object.__setattr__(self, name, value)

    @property
    def amplitude(self):
        """Wave amplitude H/2 [m]."""
        return self.wave_height / 2.0

    @cached_property
    def omega(self):
        """Angular frequency 2*pi/T [rad/s]."""
        return _scalar(
            2.0 * np.pi / self.period,
            "Angular frequency",
            positive=True,
        )

    @cached_property
    def wave_number(self):
        """Linear dispersion wave number [rad/m]."""
        return solve_wave_number(
            self.period,
            self.depth,
            self.gravity,
        )

    @cached_property
    def wavelength(self):
        """Wavelength 2*pi/k [m]."""
        return _scalar(
            2.0 * np.pi / self.wave_number,
            "Wavelength",
            positive=True,
        )

    @cached_property
    def phase_velocity(self):
        """Linear phase velocity omega/k [m/s]."""
        return self.omega / self.wave_number

    @cached_property
    def group_velocity(self):
        """Linear group velocity [m/s]."""
        return self.phase_velocity * group_velocity_factor(
            self.wave_number * self.depth
        )

    @cached_property
    def energy_density(self):
        """Mean linear-wave energy per unit area [J/m^2]."""
        with np.errstate(over="ignore", invalid="ignore"):
            energy = (
                np.float64(self.density)
                * self.gravity
                * self.wave_height
                * self.wave_height
                / 8.0
            )

        return _scalar(
            energy, "Energy density", non_negative=True
        )

    @cached_property
    def energy_flux(self):
        """Mean energy flux per unit crest width [W/m]."""
        return _scalar(
            self.energy_density * self.group_velocity,
            "Energy flux",
            non_negative=True,
        )

amplitude property

amplitude

Wave amplitude H/2 [m].

omega cached property

omega

Angular frequency 2*pi/T [rad/s].

wave_number cached property

wave_number

Linear dispersion wave number [rad/m].

wavelength cached property

wavelength

Wavelength 2*pi/k [m].

phase_velocity cached property

phase_velocity

Linear phase velocity omega/k [m/s].

group_velocity cached property

group_velocity

Linear group velocity [m/s].

energy_density cached property

energy_density

Mean linear-wave energy per unit area [J/m^2].

energy_flux cached property

energy_flux

Mean energy flux per unit crest width [W/m].

breaking_utilisation

breaking_utilisation(wave_height: ArrayLike, wavelength: ArrayLike, depth: ArrayLike, *, coefficient: float = MICHE_COEFFICIENT, breaker_index: float = DEFAULT_BREAKER_INDEX) -> ScalarOrArray

Calculate utilisation of the combined breaking limit.

Parameters:

Name Type Description Default
wave_height array_like

Non-negative regular wave height H [m].

required
wavelength array_like

Positive wavelength L [m].

required
depth array_like

Positive still-water depth h [m].

required
coefficient float

Positive Miche coefficient [-].

MICHE_COEFFICIENT
breaker_index float

Positive empirical breaker index [-].

DEFAULT_BREAKER_INDEX

Returns:

Type Description
float or ndarray

Ratio H/min(H_Miche, H_depth), dimensionless.

Notes

This is equivalent to the maximum utilisation of the two individual adopted criteria.

Source code in src/fluidmec/waves/applicability.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
def breaking_utilisation(
    wave_height: ArrayLike,
    wavelength: ArrayLike,
    depth: ArrayLike,
    *,
    coefficient: float = MICHE_COEFFICIENT,
    breaker_index: float = DEFAULT_BREAKER_INDEX,
) -> ScalarOrArray:
    """Calculate utilisation of the combined breaking limit.

    Parameters
    ----------
    wave_height : array_like
        Non-negative regular wave height H [m].
    wavelength : array_like
        Positive wavelength L [m].
    depth : array_like
        Positive still-water depth h [m].
    coefficient : float, optional
        Positive Miche coefficient [-].
    breaker_index : float, optional
        Positive empirical breaker index [-].

    Returns
    -------
    float or ndarray
        Ratio H/min(H_Miche, H_depth), dimensionless.

    Notes
    -----
    This is equivalent to the maximum utilisation
    of the two individual adopted criteria.
    """
    height = validate_non_negative(wave_height, "Wave height")

    limit = combined_breaking_height(
        wavelength,
        depth,
        coefficient=coefficient,
        breaker_index=breaker_index,
    )

    return _safe_ratio(height, limit, "Breaking utilisation")

miche_breaking_steepness

miche_breaking_steepness(wavelength: ArrayLike, depth: ArrayLike, coefficient: float = MICHE_COEFFICIENT) -> ScalarOrArray

Calculate Miche's approximate limiting steepness.

Parameters:

Name Type Description Default
wavelength array_like

Positive wavelength L [m].

required
depth array_like

Positive still-water depth h [m].

required
coefficient float

Positive Miche coefficient, default 0.142.

MICHE_COEFFICIENT

Returns:

Type Description
float or ndarray

Limiting dimensionless wave steepness Hb/L.

Notes

Hb/L = coefficienttanh(2pi*h/L).

The criterion approximates a limiting regular-wave steepness and is not a dynamic breaking model.

Source code in src/fluidmec/waves/applicability.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def miche_breaking_steepness(
    wavelength: ArrayLike,
    depth: ArrayLike,
    coefficient: float = MICHE_COEFFICIENT,
) -> ScalarOrArray:
    """Calculate Miche's approximate limiting steepness.

    Parameters
    ----------
    wavelength : array_like
        Positive wavelength L [m].
    depth : array_like
        Positive still-water depth h [m].
    coefficient : float, optional
        Positive Miche coefficient, default 0.142.

    Returns
    -------
    float or ndarray
        Limiting dimensionless wave steepness Hb/L.

    Notes
    -----
    Hb/L = coefficient*tanh(2*pi*h/L).

    The criterion approximates a limiting regular-wave
    steepness and is not a dynamic breaking model.
    """
    length = validate_positive(wavelength, "Wavelength")
    water_depth = validate_positive(depth, "Water depth")
    c = _positive_scalar(coefficient, "Miche coefficient")

    with np.errstate(
        over="ignore",
        under="ignore",
    ):
        kh = (water_depth / length) * (2.0 * np.pi)
        result = c * np.tanh(kh)

    return _finite_output(result, "Miche breaking steepness")

recommend_wave_theory

recommend_wave_theory(wave_height: ArrayLike, wavelength: ArrayLike, depth: ArrayLike, *, coefficient: float = MICHE_COEFFICIENT, breaker_index: float = DEFAULT_BREAKER_INDEX, warning_ratio: float = DEFAULT_WARNING_RATIO, linear_ka_limit: float = 0.05, linear_height_ratio_limit: float = 0.1, linear_ursell_limit: float = 1.0, cnoidal_ursell_limit: float = 26.0, cnoidal_depth_limit: float = 0.1, steep_ka_limit: float = 0.3) -> TextOrArray

Recommend candidate wave theories for screening.

Parameters:

Name Type Description Default
wave_height array_like

Non-negative regular wave height H [m].

required
wavelength array_like

Positive wavelength L [m].

required
depth array_like

Positive still-water depth h [m].

required
coefficient float

Positive Miche coefficient [-].

MICHE_COEFFICIENT
breaker_index float

Positive empirical breaker index [-].

DEFAULT_BREAKER_INDEX
warning_ratio float

Breaking utilisation warning threshold (0, 1).

DEFAULT_WARNING_RATIO
linear_ka_limit float

Maximum dimensionless amplitude for the adopted linear-wave screening rule.

0.05
linear_height_ratio_limit float

Maximum H/h for the linear screening rule.

0.1
linear_ursell_limit float

Maximum Ursell number for the linear rule outside the deep-water regime.

1.0
cnoidal_ursell_limit float

Minimum Ursell number for the cnoidal candidate rule.

26.0
cnoidal_depth_limit float

Maximum relative depth h/L for the cnoidal candidate rule.

0.1
steep_ka_limit float

Dimensionless amplitude above which a higher-order numerical theory is suggested.

0.3

Returns:

Type Description
str or ndarray

Candidate theory label.

Notes

The decision rules are configurable heuristics. They are not universal theory-validity boundaries.

The Ursell number is primarily relevant to long waves. Its linear screening condition is therefore not imposed in the deep-water regime.

A recommendation does not verify a particular solver, accuracy tolerance or engineering design.

Source code in src/fluidmec/waves/applicability.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
def recommend_wave_theory(
    wave_height: ArrayLike,
    wavelength: ArrayLike,
    depth: ArrayLike,
    *,
    coefficient: float = MICHE_COEFFICIENT,
    breaker_index: float = DEFAULT_BREAKER_INDEX,
    warning_ratio: float = DEFAULT_WARNING_RATIO,
    linear_ka_limit: float = 0.05,
    linear_height_ratio_limit: float = 0.1,
    linear_ursell_limit: float = 1.0,
    cnoidal_ursell_limit: float = 26.0,
    cnoidal_depth_limit: float = 0.1,
    steep_ka_limit: float = 0.3,
) -> TextOrArray:
    """Recommend candidate wave theories for screening.

    Parameters
    ----------
    wave_height : array_like
        Non-negative regular wave height H [m].
    wavelength : array_like
        Positive wavelength L [m].
    depth : array_like
        Positive still-water depth h [m].
    coefficient : float, optional
        Positive Miche coefficient [-].
    breaker_index : float, optional
        Positive empirical breaker index [-].
    warning_ratio : float, optional
        Breaking utilisation warning threshold (0, 1).
    linear_ka_limit : float, optional
        Maximum dimensionless amplitude for the
        adopted linear-wave screening rule.
    linear_height_ratio_limit : float, optional
        Maximum H/h for the linear screening rule.
    linear_ursell_limit : float, optional
        Maximum Ursell number for the linear rule
        outside the deep-water regime.
    cnoidal_ursell_limit : float, optional
        Minimum Ursell number for the cnoidal
        candidate rule.
    cnoidal_depth_limit : float, optional
        Maximum relative depth h/L for the cnoidal
        candidate rule.
    steep_ka_limit : float, optional
        Dimensionless amplitude above which a
        higher-order numerical theory is suggested.

    Returns
    -------
    str or ndarray
        Candidate theory label.

    Notes
    -----
    The decision rules are configurable heuristics.
    They are not universal theory-validity boundaries.

    The Ursell number is primarily relevant to long
    waves. Its linear screening condition is therefore
    not imposed in the deep-water regime.

    A recommendation does not verify a particular
    solver, accuracy tolerance or engineering design.
    """
    height, length, water_depth = _wave_inputs(wave_height, wavelength, depth)

    warning = _warning_threshold(warning_ratio)

    linear_ka = _positive_scalar(linear_ka_limit, "Linear ka limit")
    linear_ratio = _positive_scalar(
        linear_height_ratio_limit,
        "Linear height ratio limit",
    )
    linear_ur = _positive_scalar(linear_ursell_limit, "Linear Ursell limit")
    cnoidal_ur = _positive_scalar(cnoidal_ursell_limit, "Cnoidal Ursell limit")
    cnoidal_depth = _positive_scalar(cnoidal_depth_limit, "Cnoidal depth limit")
    steep_ka = _positive_scalar(steep_ka_limit, "Steep ka limit")

    if linear_ka >= steep_ka:
        raise ValueError("Linear ka limit must be below steep ka limit.")

    if linear_ur >= cnoidal_ur:
        raise ValueError("Linear Ursell limit must be below cnoidal Ursell limit.")

    if cnoidal_depth >= 0.5:
        raise ValueError("Cnoidal depth limit must be below 0.5.")

    steepness = _safe_ratio(height, length, "Wave steepness")

    ka = _finite_output(
        np.pi * np.asarray(steepness),
        "Dimensionless amplitude",
    )

    relative_depth = _safe_ratio(water_depth, length, "Relative depth")

    height_ratio = relative_wave_height(height, water_depth)

    ur = ursell_number(height, length, water_depth)

    utilisation = breaking_utilisation(
        height,
        length,
        water_depth,
        coefficient=coefficient,
        breaker_index=breaker_index,
    )

    linear = (
        (ka <= linear_ka)
        & (height_ratio <= linear_ratio)
        & ((relative_depth >= 0.5) | (ur <= linear_ur))
    )

    cnoidal = (relative_depth <= cnoidal_depth) & (ur >= cnoidal_ur)

    higher_order = (utilisation >= warning) | (ka >= steep_ka)

    result = np.select(
        [
            utilisation >= 1.0,
            linear,
            cnoidal,
            higher_order,
            relative_depth <= 0.05,
        ],
        [
            "breaking_wave_assessment",
            "linear_airy_candidate",
            "cnoidal_long_wave_candidate",
            "higher_order_numerical_candidate",
            "nonlinear_shallow_water_candidate",
        ],
        default="stokes_candidate",
    )

    return _text_output(result)

get_pyplot

get_pyplot()

Load Matplotlib only when a plotting function is called.

Returns:

Type Description
module

Matplotlib pyplot module.

Raises:

Type Description
ImportError

If Matplotlib is unavailable.

Notes

Fluidmec does not change the user's Matplotlib backend. Headless applications should select Agg before plotting.

Source code in src/fluidmec/visualization/_backend.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def get_pyplot():
    """Load Matplotlib only when a plotting function is called.

    Returns
    -------
    module
        Matplotlib pyplot module.

    Raises
    ------
    ImportError
        If Matplotlib is unavailable.

    Notes
    -----
    Fluidmec does not change the user's Matplotlib backend.
    Headless applications should select Agg before plotting.
    """
    try:
        import matplotlib.pyplot as plt
    except ImportError as exc:
        raise ImportError(
            "Visualisation requires Matplotlib. Install it with "
            'pip install "fluidmec[visualization]".'
        ) from exc

    return plt

directional_surface_data

directional_surface_data(wave: RegularWave, time: float = 0.0, *, direction_deg: float = 0.0, wavelengths: float = 2.0, nx: int = 121, ny: int = 121) -> dict

Calculate a directional linear plane-wave surface.

Parameters:

Name Type Description Default
wave RegularWave

Regular-wave configuration.

required
time float

Evaluation time [s].

0.0
direction_deg float

Propagation direction measured counterclockwise from the positive x-axis [degrees].

0.0
wavelengths float

Side length of the square domain in wavelengths.

2.0
nx int

Grid sample counts.

121
ny int

Grid sample counts.

121

Returns:

Type Description
dict

X, Y : horizontal mesh coordinates [m]. eta : surface elevation [m]. kx, ky : directional wave-number components [rad/m].

Notes

This is a directional plane wave, not a nonlinear three-dimensional free-surface flow solution.

Source code in src/fluidmec/visualization/wave_data.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
def directional_surface_data(
    wave: RegularWave,
    time: float = 0.0,
    *,
    direction_deg: float = 0.0,
    wavelengths: float = 2.0,
    nx: int = 121,
    ny: int = 121,
) -> dict:
    """Calculate a directional linear plane-wave surface.

    Parameters
    ----------
    wave : RegularWave
        Regular-wave configuration.
    time : float, optional
        Evaluation time [s].
    direction_deg : float, optional
        Propagation direction measured counterclockwise
        from the positive x-axis [degrees].
    wavelengths : float, optional
        Side length of the square domain in wavelengths.
    nx, ny : int, optional
        Grid sample counts.

    Returns
    -------
    dict
        X, Y : horizontal mesh coordinates [m].
        eta : surface elevation [m].
        kx, ky : directional wave-number components [rad/m].

    Notes
    -----
    This is a directional plane wave, not a nonlinear
    three-dimensional free-surface flow solution.
    """
    time = _scalar(time, "Time")
    direction_deg = _scalar(
        direction_deg, "Direction"
    )
    wavelengths = _scalar(
        wavelengths, "Domain wavelengths", positive=True
    )
    nx = _count(nx, "nx")
    ny = _count(ny, "ny")

    beta = np.deg2rad(direction_deg % 360.0)

    kx = wave.wave_number * np.cos(beta)
    ky = wave.wave_number * np.sin(beta)

    length = wavelengths * wave.wavelength

    x = np.linspace(0.0, length, nx)
    y = np.linspace(0.0, length, ny)

    X, Y = np.meshgrid(x, y)

    theta = (
        kx * X
        + ky * Y
        - wave.omega * time
        + wave.phase_offset
    )

    return _finite_fields({
        "X": X,
        "Y": Y,
        "eta": wave.amplitude * np.cos(theta),
        "kx": kx,
        "ky": ky,
    })

particle_orbit_data

particle_orbit_data(wave: RegularWave, x0, z0, time) -> dict

Calculate first-order particle orbital coordinates.

Parameters:

Name Type Description Default
wave RegularWave

Regular-wave configuration.

required
x0 array_like

Mean horizontal particle positions [m].

required
z0 array_like

Mean vertical positions [m], within [-depth, 0].

required
time array_like

Evaluation times [s].

required

Returns:

Type Description
dict

X, Z : instantaneous particle positions [m]. xi, zeta : first-order displacements [m]. horizontal_radius, vertical_radius : orbital semi-axis lengths [m].

Notes

Inputs follow standard NumPy broadcasting rules. These trajectories are first-order closed orbits. Stokes drift and nonlinear particle advection are not represented.

Source code in src/fluidmec/visualization/wave_data.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def particle_orbit_data(
    wave: RegularWave,
    x0,
    z0,
    time,
) -> dict:
    """Calculate first-order particle orbital coordinates.

    Parameters
    ----------
    wave : RegularWave
        Regular-wave configuration.
    x0 : array_like
        Mean horizontal particle positions [m].
    z0 : array_like
        Mean vertical positions [m], within [-depth, 0].
    time : array_like
        Evaluation times [s].

    Returns
    -------
    dict
        X, Z : instantaneous particle positions [m].
        xi, zeta : first-order displacements [m].
        horizontal_radius, vertical_radius : orbital
            semi-axis lengths [m].

    Notes
    -----
    Inputs follow standard NumPy broadcasting rules.
    These trajectories are first-order closed orbits.
    Stokes drift and nonlinear particle advection
    are not represented.
    """
    x0 = as_float_array(x0, "Mean x")
    z0 = as_float_array(z0, "Mean z")
    time = as_float_array(time, "Time")

    x0, z0, time = np.broadcast_arrays(
        x0, z0, time
    )

    k = wave.wave_number
    omega = wave.omega

    C = cosh_depth_factor(k, z0, wave.depth)
    S = sinh_depth_factor(k, z0, wave.depth)

    scale = (
        wave.gravity * wave.amplitude * k / omega**2
    )

    A = scale * C
    B = scale * S

    theta = k * x0 - omega * time + wave.phase_offset

    xi = -A * np.sin(theta)
    zeta = B * np.cos(theta)

    return _finite_fields({
        "X": x0 + xi,
        "Z": z0 + zeta,
        "xi": xi,
        "zeta": zeta,
        "horizontal_radius": A,
        "vertical_radius": B,
    })

wave_field_data

wave_field_data(wave: RegularWave, time: float = 0.0, *, wavelengths: float = 2.0, nx: int = 241, nz: int = 81) -> dict

Evaluate linear wave fields on a rectangular grid.

Parameters:

Name Type Description Default
wave RegularWave

Validated regular-wave configuration.

required
time float

Evaluation time [s].

0.0
wavelengths float

Positive horizontal domain length in wavelengths.

2.0
nx int

Horizontal and vertical grid sample counts.

241
nz int

Horizontal and vertical grid sample counts.

241

Returns:

Type Description
dict

x, z : one-dimensional coordinates [m]. X, Z : two-dimensional mesh coordinates [m]. eta : surface elevation along x [m]. u, w : velocity components [m/s]. speed : velocity magnitude [m/s]. ax, az : local acceleration components [m/s^2]. acceleration : acceleration magnitude [m/s^2]. dynamic_pressure : pressure perturbation [Pa]. hydrostatic_pressure : hydrostatic gauge pressure [Pa]. gauge_pressure : total linearised gauge pressure [Pa].

Notes

Field arrays have shape (nz, nx). The domain is the mean water column, not the instantaneous moving free-surface domain.

Acceleration is first-order local acceleration; nonlinear convective acceleration is excluded.

Source code in src/fluidmec/visualization/wave_data.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def wave_field_data(
    wave: RegularWave,
    time: float = 0.0,
    *,
    wavelengths: float = 2.0,
    nx: int = 241,
    nz: int = 81,
) -> dict:
    """Evaluate linear wave fields on a rectangular grid.

    Parameters
    ----------
    wave : RegularWave
        Validated regular-wave configuration.
    time : float, optional
        Evaluation time [s].
    wavelengths : float, optional
        Positive horizontal domain length in wavelengths.
    nx, nz : int, optional
        Horizontal and vertical grid sample counts.

    Returns
    -------
    dict
        x, z : one-dimensional coordinates [m].
        X, Z : two-dimensional mesh coordinates [m].
        eta : surface elevation along x [m].
        u, w : velocity components [m/s].
        speed : velocity magnitude [m/s].
        ax, az : local acceleration components [m/s^2].
        acceleration : acceleration magnitude [m/s^2].
        dynamic_pressure : pressure perturbation [Pa].
        hydrostatic_pressure : hydrostatic gauge pressure [Pa].
        gauge_pressure : total linearised gauge pressure [Pa].

    Notes
    -----
    Field arrays have shape (nz, nx).
    The domain is the mean water column, not the
    instantaneous moving free-surface domain.

    Acceleration is first-order local acceleration;
    nonlinear convective acceleration is excluded.
    """
    time = _scalar(time, "Time")
    wavelengths = _scalar(
        wavelengths, "Domain wavelengths", positive=True
    )
    nx = _count(nx, "nx")
    nz = _count(nz, "nz")

    k = wave.wave_number
    omega = wave.omega
    a = wave.amplitude
    g = wave.gravity

    x = np.linspace(
        0.0, wavelengths * wave.wavelength, nx
    )
    z = np.linspace(-wave.depth, 0.0, nz)

    X, Z = np.meshgrid(x, z)

    theta = k * X - omega * time + wave.phase_offset

    C = cosh_depth_factor(k, Z, wave.depth)
    S = sinh_depth_factor(k, Z, wave.depth)

    velocity_scale = g * a * k / omega
    acceleration_scale = g * a * k

    u = velocity_scale * C * np.cos(theta)
    w = velocity_scale * S * np.sin(theta)

    ax = acceleration_scale * C * np.sin(theta)
    az = -acceleration_scale * S * np.cos(theta)

    pd = wave.density * g * a * C * np.cos(theta)
    ph = -wave.density * g * Z

    eta = a * np.cos(
        k * x - omega * time + wave.phase_offset
    )

    return _finite_fields({
        "x": x,
        "z": z,
        "X": X,
        "Z": Z,
        "eta": eta,
        "u": u,
        "w": w,
        "speed": np.hypot(u, w),
        "ax": ax,
        "az": az,
        "acceleration": np.hypot(ax, az),
        "dynamic_pressure": pd,
        "hydrostatic_pressure": ph,
        "gauge_pressure": ph + pd,
    })

wave_packet_data

wave_packet_data(wave: RegularWave, time: float = 0.0, *, frequency_fraction: float = 0.05, wavelengths: float = 20.0, nx: int = 2001) -> dict

Calculate a two-frequency dispersive wave group.

Parameters:

Name Type Description Default
wave RegularWave

Reference wave configuration.

required
time float

Evaluation time [s].

0.0
frequency_fraction float

Fractional angular-frequency half-separation. Must lie strictly between zero and one.

0.05
wavelengths float

Domain length in reference wavelengths.

20.0
nx int

Horizontal sample count.

2001

Returns:

Type Description
dict

x : horizontal coordinate [m]. eta : superposed wave elevation [m]. envelope : absolute modulation envelope [m]. envelope_velocity : finite-difference group speed [m/s]. phase_velocity : carrier phase speed [m/s]. group_velocity : reference analytical group speed [m/s]. energy_density : reference wave energy [J/m^2]. energy_flux : reference wave energy flux [W/m].

Notes

Each component has half the reference amplitude. The maximum combined envelope equals the reference amplitude.

The reference energy and flux are for the original regular wave, not the mean energy of the two-wave superposition.

Source code in src/fluidmec/visualization/wave_data.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
def wave_packet_data(
    wave: RegularWave,
    time: float = 0.0,
    *,
    frequency_fraction: float = 0.05,
    wavelengths: float = 20.0,
    nx: int = 2001,
) -> dict:
    """Calculate a two-frequency dispersive wave group.

    Parameters
    ----------
    wave : RegularWave
        Reference wave configuration.
    time : float, optional
        Evaluation time [s].
    frequency_fraction : float, optional
        Fractional angular-frequency half-separation.
        Must lie strictly between zero and one.
    wavelengths : float, optional
        Domain length in reference wavelengths.
    nx : int, optional
        Horizontal sample count.

    Returns
    -------
    dict
        x : horizontal coordinate [m].
        eta : superposed wave elevation [m].
        envelope : absolute modulation envelope [m].
        envelope_velocity : finite-difference group speed [m/s].
        phase_velocity : carrier phase speed [m/s].
        group_velocity : reference analytical group speed [m/s].
        energy_density : reference wave energy [J/m^2].
        energy_flux : reference wave energy flux [W/m].

    Notes
    -----
    Each component has half the reference amplitude.
    The maximum combined envelope equals the reference
    amplitude.

    The reference energy and flux are for the original
    regular wave, not the mean energy of the two-wave
    superposition.
    """
    time = _scalar(time, "Time")
    fraction = _scalar(
        frequency_fraction,
        "Frequency fraction",
        positive=True,
    )

    if fraction >= 1.0:
        raise ValueError(
            "Frequency fraction must be less than one."
        )

    wavelengths = _scalar(
        wavelengths, "Domain wavelengths", positive=True
    )
    nx = _count(nx, "nx")

    omega1 = wave.omega * (1.0 - fraction)
    omega2 = wave.omega * (1.0 + fraction)

    k1 = solve_wave_number(
        2.0 * np.pi / omega1,
        wave.depth,
        wave.gravity,
    )
    k2 = solve_wave_number(
        2.0 * np.pi / omega2,
        wave.depth,
        wave.gravity,
    )

    delta_k = k2 - k1
    delta_omega = omega2 - omega1

    if delta_k <= 0.0 or delta_omega <= 0.0:
        raise ValueError(
            "Frequency separation is numerically unresolved."
        )

    x = np.linspace(
        0.0, wavelengths * wave.wavelength, nx
    )

    phase1 = k1 * x - omega1 * time + wave.phase_offset
    phase2 = k2 * x - omega2 * time + wave.phase_offset

    eta = (
        wave.amplitude / 2.0
        * (np.cos(phase1) + np.cos(phase2))
    )

    envelope = wave.amplitude * np.abs(
        np.cos(
            (delta_k * x - delta_omega * time) / 2.0
        )
    )

    return _finite_fields({
        "x": x,
        "eta": eta,
        "envelope": envelope,
        "envelope_velocity": delta_omega / delta_k,
        "phase_velocity": (omega1 + omega2) / (k1 + k2),
        "group_velocity": wave.group_velocity,
        "energy_density": wave.energy_density,
        "energy_flux": wave.energy_flux,
    })

_axes

_axes(ax=None, figsize=(12, 6))

Create axes or reuse user-supplied axes.

Source code in src/fluidmec/visualization/wave_plots.py
33
34
35
36
37
38
39
40
41
42
43
def _axes(ax=None, figsize=(12, 6)):
    """Create axes or reuse user-supplied axes."""
    if ax is not None:
        return ax.figure, ax

    plt = get_pyplot()

    return plt.subplots(
        figsize=figsize,
        layout="constrained",
    )

_style

_style(ax, title, xlabel, ylabel)

Apply consistent scientific axis labels.

Source code in src/fluidmec/visualization/wave_plots.py
46
47
48
49
50
51
52
53
54
55
def _style(ax, title, xlabel, ylabel):
    """Apply consistent scientific axis labels."""
    ax.set(
        title=title,
        xlabel=xlabel,
        ylabel=ylabel,
    )

    ax.title.set_fontweight("bold")
    ax.grid(alpha=0.15)

_wave_boundaries

_wave_boundaries(ax, wave, data)

Draw reference surface, SWL and seabed.

Source code in src/fluidmec/visualization/wave_plots.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def _wave_boundaries(ax, wave, data):
    """Draw reference surface, SWL and seabed."""
    ax.plot(
        data["x"],
        data["eta"],
        color=NAVY,
        linewidth=1.8,
        label="Linear free surface",
    )

    ax.axhline(
        0.0,
        color="grey",
        linestyle="--",
        linewidth=0.8,
    )

    ax.axhline(
        -wave.depth,
        color="#947454",
        linewidth=2.0,
    )

    margin = max(
        wave.amplitude * 1.3,
        wave.depth * 0.03,
    )

    ax.set_ylim(
        -wave.depth * 1.02,
        margin,
    )

_levels

_levels(values, *, signed=False)

Generate nondegenerate contour levels.

Source code in src/fluidmec/visualization/wave_plots.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def _levels(values, *, signed=False):
    """Generate nondegenerate contour levels."""
    maximum = float(np.max(np.abs(values)))

    if maximum == 0.0:
        maximum = 1.0

    if signed:
        return np.linspace(-maximum, maximum, 41)

    return np.linspace(0.0, maximum, 41)

plot_surface_elevation

plot_surface_elevation(wave: RegularWave, time: float = 0.0, *, ax=None, wavelengths: float = 2.0)

Plot linear free-surface elevation.

Parameters:

Name Type Description Default
wave RegularWave

Regular-wave configuration.

required
time float

Evaluation time [s].

0.0
ax Axes

Existing axes.

None
wavelengths float

Horizontal domain length in wavelengths.

2.0

Returns:

Type Description
(figure, axes)

Matplotlib figure and axes.

Source code in src/fluidmec/visualization/wave_plots.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def plot_surface_elevation(
    wave: RegularWave,
    time: float = 0.0,
    *,
    ax=None,
    wavelengths: float = 2.0,
):
    """Plot linear free-surface elevation.

    Parameters
    ----------
    wave : RegularWave
        Regular-wave configuration.
    time : float
        Evaluation time [s].
    ax : matplotlib.axes.Axes, optional
        Existing axes.
    wavelengths : float
        Horizontal domain length in wavelengths.

    Returns
    -------
    figure, axes
        Matplotlib figure and axes.
    """
    data = wave_field_data(
        wave,
        time,
        wavelengths=wavelengths,
        nx=601,
        nz=2,
    )

    fig, ax = _axes(ax)

    ax.plot(
        data["x"],
        data["eta"],
        color=BLUE,
        linewidth=2.5,
    )

    ax.fill_between(
        data["x"],
        data["eta"],
        -wave.depth,
        color=BLUE,
        alpha=0.15,
    )

    ax.axhline(0.0, color="grey", linestyle="--")
    ax.axhline(-wave.depth, color="#947454")

    _style(
        ax,
        f"Linear wave surface | t = {time:.2f} s",
        "Horizontal position [m]",
        "Elevation [m]",
    )

    return fig, ax

_vector_field

_vector_field(wave, time, ax, wavelengths, *, acceleration=False)

Render a velocity or local acceleration field.

Source code in src/fluidmec/visualization/wave_plots.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def _vector_field(
    wave,
    time,
    ax,
    wavelengths,
    *,
    acceleration=False,
):
    """Render a velocity or local acceleration field."""
    data = wave_field_data(
        wave,
        time,
        wavelengths=wavelengths,
    )

    fig, ax = _axes(ax)

    if acceleration:
        horizontal = data["ax"]
        vertical = data["az"]
        magnitude = data["acceleration"]
        units = "m/s²"
        title = "Local acceleration field"
    else:
        horizontal = data["u"]
        vertical = data["w"]
        magnitude = data["speed"]
        units = "m/s"
        title = "Velocity field"

    image = ax.contourf(
        data["X"],
        data["Z"],
        magnitude,
        levels=_levels(magnitude),
        cmap="viridis",
    )

    # Subsample the numerical grid for readable arrows.
    selection = (slice(None, None, 8), slice(None, None, 12))

    ax.quiver(
        data["X"][selection],
        data["Z"][selection],
        horizontal[selection],
        vertical[selection],
        color="white",
        angles="xy",
        scale_units="xy",
        scale=(
            max(float(np.max(magnitude)), 1e-12)
            / (0.025 * wave.wavelength)
        ),
        width=0.002,
    )

    fig.colorbar(
        image,
        ax=ax,
        label=f"Magnitude [{units}]",
    )

    _wave_boundaries(ax, wave, data)

    _style(
        ax,
        f"{title} | t = {time:.2f} s",
        "Horizontal position [m]",
        "Vertical position [m]",
    )

    return fig, ax

plot_velocity_field

plot_velocity_field(wave: RegularWave, time: float = 0.0, *, ax=None, wavelengths: float = 2.0)

Plot first-order velocity contours and vectors.

Velocity magnitude is expressed in m/s. Arrow directions represent local velocity vectors. Arrow lengths are scaled for visual readability.

Returns a Matplotlib figure and axes.

Source code in src/fluidmec/visualization/wave_plots.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
def plot_velocity_field(
    wave: RegularWave,
    time: float = 0.0,
    *,
    ax=None,
    wavelengths: float = 2.0,
):
    """Plot first-order velocity contours and vectors.

    Velocity magnitude is expressed in m/s.
    Arrow directions represent local velocity vectors.
    Arrow lengths are scaled for visual readability.

    Returns a Matplotlib figure and axes.
    """
    return _vector_field(
        wave, time, ax, wavelengths
    )

plot_acceleration_field

plot_acceleration_field(wave: RegularWave, time: float = 0.0, *, ax=None, wavelengths: float = 2.0)

Plot first-order local acceleration vectors.

Magnitude is expressed in m/s^2. Nonlinear convective acceleration is excluded.

Returns a Matplotlib figure and axes.

Source code in src/fluidmec/visualization/wave_plots.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def plot_acceleration_field(
    wave: RegularWave,
    time: float = 0.0,
    *,
    ax=None,
    wavelengths: float = 2.0,
):
    """Plot first-order local acceleration vectors.

    Magnitude is expressed in m/s^2.
    Nonlinear convective acceleration is excluded.

    Returns a Matplotlib figure and axes.
    """
    return _vector_field(
        wave,
        time,
        ax,
        wavelengths,
        acceleration=True,
    )

plot_pressure_field

plot_pressure_field(wave: RegularWave, time: float = 0.0, *, component: str = 'dynamic', ax=None, wavelengths: float = 2.0)

Plot wave pressure contours in kPa.

Parameters:

Name Type Description Default
wave RegularWave

Regular-wave configuration.

required
time float

Evaluation time [s].

0.0
component (dynamic, hydrostatic, gauge)

Pressure component to display.

"dynamic"
ax Axes

Existing axes.

None
wavelengths float

Horizontal domain length in wavelengths.

2.0

Returns:

Type Description
(figure, axes)

Matplotlib figure and axes.

Notes

Gauge pressure excludes atmospheric pressure. Dynamic pressure is a signed perturbation. Calculations use the mean water column.

Source code in src/fluidmec/visualization/wave_plots.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
def plot_pressure_field(
    wave: RegularWave,
    time: float = 0.0,
    *,
    component: str = "dynamic",
    ax=None,
    wavelengths: float = 2.0,
):
    """Plot wave pressure contours in kPa.

    Parameters
    ----------
    wave : RegularWave
        Regular-wave configuration.
    time : float
        Evaluation time [s].
    component : {"dynamic", "hydrostatic", "gauge"}
        Pressure component to display.
    ax : matplotlib.axes.Axes, optional
        Existing axes.
    wavelengths : float
        Horizontal domain length in wavelengths.

    Returns
    -------
    figure, axes
        Matplotlib figure and axes.

    Notes
    -----
    Gauge pressure excludes atmospheric pressure.
    Dynamic pressure is a signed perturbation.
    Calculations use the mean water column.
    """
    keys = {
        "dynamic": "dynamic_pressure",
        "hydrostatic": "hydrostatic_pressure",
        "gauge": "gauge_pressure",
    }

    if component not in keys:
        raise ValueError(
            "Component must be dynamic, hydrostatic or gauge."
        )

    data = wave_field_data(
        wave,
        time,
        wavelengths=wavelengths,
    )

    values = data[keys[component]] / 1000.0

    signed = component == "dynamic" or np.min(values) < 0

    fig, ax = _axes(ax)

    image = ax.contourf(
        data["X"],
        data["Z"],
        values,
        levels=_levels(values, signed=signed),
        cmap="RdBu_r" if signed else "viridis",
    )

    fig.colorbar(
        image,
        ax=ax,
        label="Pressure [kPa]",
    )

    _wave_boundaries(ax, wave, data)

    _style(
        ax,
        f"{component.capitalize()} pressure | t = {time:.2f} s",
        "Horizontal position [m]",
        "Vertical position [m]",
    )

    return fig, ax

plot_particle_orbits

plot_particle_orbits(wave: RegularWave, *, ax=None, samples: int = 241)

Plot first-order particle orbital trajectories.

Trajectories are evaluated over one wave period. Mean particle locations span the water column.

Returns a Matplotlib figure and axes.

Notes

Equal axis scaling preserves orbital geometry. No second-order Stokes drift is included.

Source code in src/fluidmec/visualization/wave_plots.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
def plot_particle_orbits(
    wave: RegularWave,
    *,
    ax=None,
    samples: int = 241,
):
    """Plot first-order particle orbital trajectories.

    Trajectories are evaluated over one wave period.
    Mean particle locations span the water column.

    Returns a Matplotlib figure and axes.

    Notes
    -----
    Equal axis scaling preserves orbital geometry.
    No second-order Stokes drift is included.
    """
    from .wave_data import _count

    samples = _count(samples, "Samples", minimum=3)

    fig, ax = _axes(ax)

    times = np.linspace(
        0.0, wave.period, samples
    )

    x_centres = np.linspace(
        0.15 * wave.wavelength,
        0.85 * wave.wavelength,
        5,
    )

    z_centres = np.linspace(
        -0.1 * wave.depth,
        -wave.depth,
        6,
    )

    for x0 in x_centres:
        for z0 in z_centres:
            data = particle_orbit_data(
                wave, x0, z0, times
            )

            ax.plot(
                data["X"],
                data["Z"],
                color=BLUE,
                linewidth=1.3,
            )

            ax.scatter(
                x0, z0,
                s=8,
                color=NAVY,
            )

            ax.scatter(
                data["X"][0],
                data["Z"][0],
                s=18,
                color=ORANGE,
            )

    ax.axhline(0.0, color="grey", linestyle="--")
    ax.axhline(-wave.depth, color="#947454")

    ax.set_aspect("equal", adjustable="box")

    _style(
        ax,
        "First-order particle orbital trajectories",
        "Horizontal position [m]",
        "Vertical position [m]",
    )

    return fig, ax

plot_directional_surface

plot_directional_surface(wave: RegularWave, time: float = 0.0, *, direction_deg: float = 30.0, wavelengths: float = 2.0, ax=None)

Plot a three-dimensional directional wave surface.

Direction is measured counterclockwise from +x in degrees. Surface elevation is expressed in metres.

Returns a Matplotlib figure and 3D axes.

Notes

Vertical visual exaggeration may result from the figure aspect ratio. Coordinate labels retain SI units.

Source code in src/fluidmec/visualization/wave_plots.py
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
def plot_directional_surface(
    wave: RegularWave,
    time: float = 0.0,
    *,
    direction_deg: float = 30.0,
    wavelengths: float = 2.0,
    ax=None,
):
    """Plot a three-dimensional directional wave surface.

    Direction is measured counterclockwise from +x
    in degrees. Surface elevation is expressed in metres.

    Returns a Matplotlib figure and 3D axes.

    Notes
    -----
    Vertical visual exaggeration may result from the
    figure aspect ratio. Coordinate labels retain SI units.
    """
    data = directional_surface_data(
        wave,
        time,
        direction_deg=direction_deg,
        wavelengths=wavelengths,
    )

    if ax is None:
        plt = get_pyplot()
        fig = plt.figure(
            figsize=(12, 8),
            layout="constrained",
        )
        ax = fig.add_subplot(111, projection="3d")
    else:
        fig = ax.figure

        if not hasattr(ax, "plot_surface"):
            raise ValueError("A 3D axes object is required.")

    surface = ax.plot_surface(
        data["X"],
        data["Y"],
        data["eta"],
        cmap="coolwarm",
        linewidth=0,
        antialiased=True,
        vmin=-max(wave.amplitude, 1e-12),
        vmax=max(wave.amplitude, 1e-12),
    )

    fig.colorbar(
        surface,
        ax=ax,
        shrink=0.65,
        label="Elevation [m]",
    )

    ax.set(
        title=f"Directional wave | β = {direction_deg:g}°",
        xlabel="x [m]",
        ylabel="y [m]",
        zlabel="Elevation [m]",
    )

    ax.view_init(elev=30, azim=-60)

    return fig, ax

plot_energy_transport

plot_energy_transport(wave: RegularWave, time: float = 0.0, *, frequency_fraction: float = 0.05, ax=None)

Plot a two-frequency wave group and its envelope.

Displays carrier phase velocity and finite-difference envelope velocity, together with reference regular-wave energy density and flux.

Returns a Matplotlib figure and axes.

Source code in src/fluidmec/visualization/wave_plots.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def plot_energy_transport(
    wave: RegularWave,
    time: float = 0.0,
    *,
    frequency_fraction: float = 0.05,
    ax=None,
):
    """Plot a two-frequency wave group and its envelope.

    Displays carrier phase velocity and finite-difference
    envelope velocity, together with reference regular-wave
    energy density and flux.

    Returns a Matplotlib figure and axes.
    """
    data = wave_packet_data(
        wave,
        time,
        frequency_fraction=frequency_fraction,
    )

    fig, ax = _axes(ax)

    ax.plot(
        data["x"],
        data["eta"],
        color=BLUE,
        linewidth=1.5,
        label="Superposed waves",
    )

    ax.plot(
        data["x"],
        data["envelope"],
        color=ORANGE,
        linestyle="--",
        label="Modulation envelope",
    )

    ax.plot(
        data["x"],
        -data["envelope"],
        color=ORANGE,
        linestyle="--",
    )

    ax.text(
        0.02,
        0.97,
        (
            f"Carrier speed = {data['phase_velocity']:.3f} m/s\n"
            f"Envelope speed = {data['envelope_velocity']:.3f} m/s\n"
            f"Reference E = {wave.energy_density:.1f} J/m²\n"
            f"Reference P = {wave.energy_flux / 1000:.2f} kW/m"
        ),
        transform=ax.transAxes,
        va="top",
        fontsize=10,
        bbox={
            "facecolor": "white",
            "alpha": 0.9,
            "edgecolor": "none",
        },
    )

    ax.legend(loc="lower right")

    _style(
        ax,
        f"Dispersive wave group | t = {time:.2f} s",
        "Horizontal position [m]",
        "Elevation [m]",
    )

    return fig, ax

plot_wave_applicability

plot_wave_applicability(wave: RegularWave | None = None, *, ax=None, resolution: int = 300)

Plot heuristic wave theory applicability regions.

Parameters:

Name Type Description Default
wave RegularWave or None

Optional wave configuration to mark on the diagram.

None
ax Axes

Existing axes.

None
resolution int

Sample count along each dimension.

300

Returns:

Type Description
(figure, axes)

Matplotlib figure and axes.

Notes

Regions follow Fluidmec's configurable screening conventions, not experimentally validated universal theory boundaries.

Source code in src/fluidmec/visualization/wave_plots.py
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
def plot_wave_applicability(
    wave: RegularWave | None = None,
    *,
    ax=None,
    resolution: int = 300,
):
    """Plot heuristic wave theory applicability regions.

    Parameters
    ----------
    wave : RegularWave or None
        Optional wave configuration to mark on the diagram.
    ax : matplotlib.axes.Axes, optional
        Existing axes.
    resolution : int
        Sample count along each dimension.

    Returns
    -------
    figure, axes
        Matplotlib figure and axes.

    Notes
    -----
    Regions follow Fluidmec's configurable screening
    conventions, not experimentally validated universal
    theory boundaries.
    """
    from matplotlib.colors import BoundaryNorm, ListedColormap

    from .wave_data import _count

    resolution = _count(
        resolution, "Resolution", minimum=10
    )

    fig, ax = _axes(ax)

    depths = np.geomspace(0.005, 2.0, resolution)
    steepness = np.geomspace(1e-5, 0.2, resolution)

    D, S = np.meshgrid(depths, steepness)

    labels = [
        "linear_airy_candidate",
        "stokes_candidate",
        "nonlinear_shallow_water_candidate",
        "cnoidal_long_wave_candidate",
        "higher_order_numerical_candidate",
        "breaking_wave_assessment",
    ]

    names = [
        "Airy",
        "Stokes",
        "Nonlinear shallow water",
        "Cnoidal / long wave",
        "Higher-order numerical",
        "Breaking assessment",
    ]

    theory = recommend_wave_theory(S, 1.0, D)

    codes = np.full(theory.shape, -1, dtype=int)

    for index, label in enumerate(labels):
        codes[theory == label] = index

    if np.any(codes < 0):
        raise ValueError(
            "Unknown theory label in applicability data."
        )

    cmap = ListedColormap([
        GREEN,
        "#438CBA",
        "#9BC7E4",
        "#D5B35B",
        ORANGE,
        "#B94343",
    ])

    norm = BoundaryNorm(
        np.arange(-0.5, 6.5),
        cmap.N,
    )

    image = ax.pcolormesh(
        D, S, codes,
        cmap=cmap,
        norm=norm,
        shading="auto",
    )

    bar = fig.colorbar(
        image,
        ax=ax,
        ticks=np.arange(6),
    )

    bar.ax.set_yticklabels(names)

    utilisation = breaking_utilisation(
        S, 1.0, D
    )

    contours = ax.contour(
        D,
        S,
        utilisation,
        levels=[0.8, 1.0],
        colors=["white", "black"],
        linewidths=1.5,
    )

    ax.clabel(
        contours,
        fmt={0.8: "80%", 1.0: "100%"},
        fontsize=8,
    )

    ax.plot(
        depths,
        miche_breaking_steepness(1.0, depths),
        color="black",
        linestyle=":",
        label="Miche limit",
    )

    if wave is not None and wave.wave_height > 0:
        ax.scatter(
            wave.depth / wave.wavelength,
            wave.wave_height / wave.wavelength,
            color="white",
            edgecolor="black",
            marker="*",
            s=180,
            zorder=5,
            label="Selected wave",
        )

    ax.set(
        xscale="log",
        yscale="log",
    )

    ax.legend(loc="lower right")

    _style(
        ax,
        "Wave theory screening — heuristic boundaries",
        "Relative depth h/L [-]",
        "Wave steepness H/L [-]",
    )

    return fig, ax

Animations of first-order regular-wave particle motion.

RegularWave dataclass

Configuration for a linear regular gravity wave.

Parameters:

Name Type Description Default
wave_height float

Non-negative crest-to-trough wave height [m].

required
period float

Positive wave period [s].

required
depth float

Positive still-water depth [m].

required
density float

Positive fluid density [kg/m^3]. Defaults to 1025 kg/m^3.

1025.0
gravity float

Positive gravitational acceleration [m/s^2].

ENGINEERING_GRAVITY
phase_offset float

Initial phase offset [rad].

0.0
Notes

Wave number is obtained from linear dispersion. The configuration does not enforce small-amplitude applicability or guarantee that waves are unbroken.

Use assess_wave_applicability for preliminary physical applicability screening.

Source code in src/fluidmec/visualization/wave_data.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
@dataclass(frozen=True)
class RegularWave:
    """Configuration for a linear regular gravity wave.

    Parameters
    ----------
    wave_height : float
        Non-negative crest-to-trough wave height [m].
    period : float
        Positive wave period [s].
    depth : float
        Positive still-water depth [m].
    density : float, optional
        Positive fluid density [kg/m^3].
        Defaults to 1025 kg/m^3.
    gravity : float, optional
        Positive gravitational acceleration [m/s^2].
    phase_offset : float, optional
        Initial phase offset [rad].

    Notes
    -----
    Wave number is obtained from linear dispersion.
    The configuration does not enforce small-amplitude
    applicability or guarantee that waves are unbroken.

    Use assess_wave_applicability for preliminary
    physical applicability screening.
    """

    wave_height: float
    period: float
    depth: float
    density: float = 1025.0
    gravity: float = ENGINEERING_GRAVITY
    phase_offset: float = 0.0

    def __post_init__(self):
        """Validate and normalise configuration inputs."""
        values = {
            "wave_height": _scalar(
                self.wave_height,
                "Wave height",
                non_negative=True,
            ),
            "period": _scalar(
                self.period, "Period", positive=True
            ),
            "depth": _scalar(
                self.depth, "Depth", positive=True
            ),
            "density": _scalar(
                self.density, "Density", positive=True
            ),
            "gravity": _scalar(
                self.gravity, "Gravity", positive=True
            ),
            "phase_offset": _scalar(
                self.phase_offset, "Phase offset"
            ),
        }

        for name, value in values.items():
            object.__setattr__(self, name, value)

    @property
    def amplitude(self):
        """Wave amplitude H/2 [m]."""
        return self.wave_height / 2.0

    @cached_property
    def omega(self):
        """Angular frequency 2*pi/T [rad/s]."""
        return _scalar(
            2.0 * np.pi / self.period,
            "Angular frequency",
            positive=True,
        )

    @cached_property
    def wave_number(self):
        """Linear dispersion wave number [rad/m]."""
        return solve_wave_number(
            self.period,
            self.depth,
            self.gravity,
        )

    @cached_property
    def wavelength(self):
        """Wavelength 2*pi/k [m]."""
        return _scalar(
            2.0 * np.pi / self.wave_number,
            "Wavelength",
            positive=True,
        )

    @cached_property
    def phase_velocity(self):
        """Linear phase velocity omega/k [m/s]."""
        return self.omega / self.wave_number

    @cached_property
    def group_velocity(self):
        """Linear group velocity [m/s]."""
        return self.phase_velocity * group_velocity_factor(
            self.wave_number * self.depth
        )

    @cached_property
    def energy_density(self):
        """Mean linear-wave energy per unit area [J/m^2]."""
        with np.errstate(over="ignore", invalid="ignore"):
            energy = (
                np.float64(self.density)
                * self.gravity
                * self.wave_height
                * self.wave_height
                / 8.0
            )

        return _scalar(
            energy, "Energy density", non_negative=True
        )

    @cached_property
    def energy_flux(self):
        """Mean energy flux per unit crest width [W/m]."""
        return _scalar(
            self.energy_density * self.group_velocity,
            "Energy flux",
            non_negative=True,
        )

amplitude property

amplitude

Wave amplitude H/2 [m].

omega cached property

omega

Angular frequency 2*pi/T [rad/s].

wave_number cached property

wave_number

Linear dispersion wave number [rad/m].

wavelength cached property

wavelength

Wavelength 2*pi/k [m].

phase_velocity cached property

phase_velocity

Linear phase velocity omega/k [m/s].

group_velocity cached property

group_velocity

Linear group velocity [m/s].

energy_density cached property

energy_density

Mean linear-wave energy per unit area [J/m^2].

energy_flux cached property

energy_flux

Mean energy flux per unit crest width [W/m].

get_animation

get_animation()

Load the optional Matplotlib animation module.

Source code in src/fluidmec/visualization/_backend.py
34
35
36
37
38
39
40
41
42
43
44
def get_animation():
    """Load the optional Matplotlib animation module."""
    try:
        from matplotlib import animation
    except ImportError as exc:
        raise ImportError(
            "Animation requires Matplotlib. Install "
            'fluidmec[visualization].'
        ) from exc

    return animation

get_pyplot

get_pyplot()

Load Matplotlib only when a plotting function is called.

Returns:

Type Description
module

Matplotlib pyplot module.

Raises:

Type Description
ImportError

If Matplotlib is unavailable.

Notes

Fluidmec does not change the user's Matplotlib backend. Headless applications should select Agg before plotting.

Source code in src/fluidmec/visualization/_backend.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def get_pyplot():
    """Load Matplotlib only when a plotting function is called.

    Returns
    -------
    module
        Matplotlib pyplot module.

    Raises
    ------
    ImportError
        If Matplotlib is unavailable.

    Notes
    -----
    Fluidmec does not change the user's Matplotlib backend.
    Headless applications should select Agg before plotting.
    """
    try:
        import matplotlib.pyplot as plt
    except ImportError as exc:
        raise ImportError(
            "Visualisation requires Matplotlib. Install it with "
            'pip install "fluidmec[visualization]".'
        ) from exc

    return plt

_count

_count(value, name, minimum=2)

Validate an integer grid or sample count.

Source code in src/fluidmec/visualization/wave_data.py
50
51
52
53
54
55
56
57
58
59
60
61
def _count(value, name, minimum=2):
    """Validate an integer grid or sample count."""
    if (
        isinstance(value, (bool, np.bool_))
        or not isinstance(value, (int, np.integer))
        or value < minimum
    ):
        raise ValueError(
            f"{name} must be an integer >= {minimum}."
        )

    return int(value)

particle_orbit_data

particle_orbit_data(wave: RegularWave, x0, z0, time) -> dict

Calculate first-order particle orbital coordinates.

Parameters:

Name Type Description Default
wave RegularWave

Regular-wave configuration.

required
x0 array_like

Mean horizontal particle positions [m].

required
z0 array_like

Mean vertical positions [m], within [-depth, 0].

required
time array_like

Evaluation times [s].

required

Returns:

Type Description
dict

X, Z : instantaneous particle positions [m]. xi, zeta : first-order displacements [m]. horizontal_radius, vertical_radius : orbital semi-axis lengths [m].

Notes

Inputs follow standard NumPy broadcasting rules. These trajectories are first-order closed orbits. Stokes drift and nonlinear particle advection are not represented.

Source code in src/fluidmec/visualization/wave_data.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def particle_orbit_data(
    wave: RegularWave,
    x0,
    z0,
    time,
) -> dict:
    """Calculate first-order particle orbital coordinates.

    Parameters
    ----------
    wave : RegularWave
        Regular-wave configuration.
    x0 : array_like
        Mean horizontal particle positions [m].
    z0 : array_like
        Mean vertical positions [m], within [-depth, 0].
    time : array_like
        Evaluation times [s].

    Returns
    -------
    dict
        X, Z : instantaneous particle positions [m].
        xi, zeta : first-order displacements [m].
        horizontal_radius, vertical_radius : orbital
            semi-axis lengths [m].

    Notes
    -----
    Inputs follow standard NumPy broadcasting rules.
    These trajectories are first-order closed orbits.
    Stokes drift and nonlinear particle advection
    are not represented.
    """
    x0 = as_float_array(x0, "Mean x")
    z0 = as_float_array(z0, "Mean z")
    time = as_float_array(time, "Time")

    x0, z0, time = np.broadcast_arrays(
        x0, z0, time
    )

    k = wave.wave_number
    omega = wave.omega

    C = cosh_depth_factor(k, z0, wave.depth)
    S = sinh_depth_factor(k, z0, wave.depth)

    scale = (
        wave.gravity * wave.amplitude * k / omega**2
    )

    A = scale * C
    B = scale * S

    theta = k * x0 - omega * time + wave.phase_offset

    xi = -A * np.sin(theta)
    zeta = B * np.cos(theta)

    return _finite_fields({
        "X": x0 + xi,
        "Z": z0 + zeta,
        "xi": xi,
        "zeta": zeta,
        "horizontal_radius": A,
        "vertical_radius": B,
    })

animate_particle_orbits

animate_particle_orbits(wave: RegularWave, *, frames: int = 120, fps: int = 20, periods: int = 1)

Animate first-order water-particle trajectories.

Parameters:

Name Type Description Default
wave RegularWave

Regular-wave configuration.

required
frames int

Number of animation frames, at least two.

120
fps int

Positive playback frame rate.

20
periods int

Number of physical wave periods represented.

1

Returns:

Name Type Description
figure Figure

Animation figure.

animation FuncAnimation

Animation object retained by the caller.

Notes

Playback duration is frames/fps seconds, which may differ from the represented physical time.

Particle paths use first-order closed trajectories. Stokes drift, breaking, turbulence and nonlinear free-surface motion are not represented.

The function does not save or display the animation.

Source code in src/fluidmec/visualization/wave_animation.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def animate_particle_orbits(
    wave: RegularWave,
    *,
    frames: int = 120,
    fps: int = 20,
    periods: int = 1,
):
    """Animate first-order water-particle trajectories.

    Parameters
    ----------
    wave : RegularWave
        Regular-wave configuration.
    frames : int, optional
        Number of animation frames, at least two.
    fps : int, optional
        Positive playback frame rate.
    periods : int, optional
        Number of physical wave periods represented.

    Returns
    -------
    figure : matplotlib.figure.Figure
        Animation figure.
    animation : matplotlib.animation.FuncAnimation
        Animation object retained by the caller.

    Notes
    -----
    Playback duration is frames/fps seconds, which may
    differ from the represented physical time.

    Particle paths use first-order closed trajectories.
    Stokes drift, breaking, turbulence and nonlinear
    free-surface motion are not represented.

    The function does not save or display the animation.
    """
    frames = _count(frames, "Frames")
    fps = _count(fps, "FPS", minimum=1)
    periods = _count(periods, "Periods", minimum=1)

    plt = get_pyplot()
    animation_module = get_animation()

    fig, ax = plt.subplots(
        figsize=(14, 7),
        layout="constrained",
    )

    times = np.linspace(
        0.0,
        periods * wave.period,
        frames,
        endpoint=False,
    )

    orbit_times = np.linspace(
        0.0, wave.period, 241
    )

    x_centres = np.linspace(
        0.1 * wave.wavelength,
        1.9 * wave.wavelength,
        11,
    )

    z_centres = np.linspace(
        -0.12 * wave.depth,
        -wave.depth,
        6,
    )

    X0, Z0 = np.meshgrid(
        x_centres, z_centres
    )

    x0 = X0.ravel()
    z0 = Z0.ravel()

    trajectories = particle_orbit_data(
        wave,
        x0[:, None],
        z0[:, None],
        orbit_times[None, :],
    )

    for X, Z in zip(
        trajectories["X"],
        trajectories["Z"],
    ):
        ax.plot(
            X,
            Z,
            color="#176B9B",
            linewidth=0.8,
            alpha=0.55,
        )

    ax.scatter(
        x0,
        z0,
        color="#15324A",
        s=5,
        alpha=0.5,
    )

    positions = particle_orbit_data(
        wave,
        x0[:, None],
        z0[:, None],
        times[None, :],
    )

    x = np.linspace(
        0.0, 2.0 * wave.wavelength, 801
    )

    eta = wave.amplitude * np.cos(
        wave.wave_number * x + wave.phase_offset
    )

    surface, = ax.plot(
        x,
        eta,
        color="#176B9B",
        linewidth=2.5,
        label="Linear free surface",
    )

    particles = ax.scatter(
        positions["X"][:, 0],
        positions["Z"][:, 0],
        color="#D97732",
        s=24,
        zorder=5,
        label="Water particles",
    )

    ax.axhline(
        0.0,
        color="grey",
        linestyle="--",
        label="Still-water level",
    )

    ax.axhline(
        -wave.depth,
        color="#947454",
        linewidth=3,
        label="Seabed",
    )

    margin = max(
        wave.amplitude * 2.0,
        wave.depth * 0.08,
    )

    horizontal_margin = max(
        float(np.max(trajectories["horizontal_radius"])),
        0.02 * wave.wavelength,
    )

    ax.set(
        xlim=(
            -horizontal_margin,
            2.0 * wave.wavelength + horizontal_margin,
        ),
        ylim=(
            -wave.depth * 1.04,
            margin,
        ),
        xlabel="Horizontal position [m]",
        ylabel="Vertical position [m]",
    )

    ax.set_aspect("equal", adjustable="box")
    ax.grid(alpha=0.15)
    ax.legend(loc="lower right")

    title = ax.set_title(
        "Fluidmec | First-order particle motion"
    )

    def update(frame):
        """Update particle coordinates and surface elevation."""
        time = times[frame]

        eta = wave.amplitude * np.cos(
            wave.wave_number * x
            - wave.omega * time
            + wave.phase_offset
        )

        surface.set_ydata(eta)

        particles.set_offsets(
            np.column_stack((
                positions["X"][:, frame],
                positions["Z"][:, frame],
            ))
        )

        title.set_text(
            f"Fluidmec | Particle motion | t = {time:.2f} s"
        )

        return surface, particles, title

    animation = animation_module.FuncAnimation(
        fig,
        update,
        frames=frames,
        interval=1000.0 / fps,
        blit=False,
        repeat=True,
        cache_frame_data=False,
    )

    return fig, animation

Headless rendering

Fluidmec supports non-interactive scientific rendering using Matplotlib's Agg backend.

Linux, Docker and cloud servers

export MPLBACKEND=Agg

Windows PowerShell

$env:MPLBACKEND = "Agg"

Python configuration

import matplotlib

matplotlib.use("Agg")

from fluidmec.visualization import (
    RegularWave,
    plot_velocity_field,
)

wave = RegularWave(2.0, 8.0, 20.0)

fig, ax = plot_velocity_field(wave)

fig.savefig("velocity_field.png", dpi=300)

The backend should be selected before importing pyplot.

Headless rendering supports PNG, PDF, SVG and GIF generation without a graphical display server.

Fluidmec does not automatically override the user's Matplotlib backend.