tpt_sci_ocean/lib.rs
1//! # tpt-sci-ocean
2//!
3//! **Ocean circulation** modelling for the `tpt-science` pillar, built on
4//! [`tpt_sci_cfd_core`]. It provides:
5//!
6//! * A 2-D **shallow-water** model ([`ShallowWater`]) — the primitive prototype
7//! for large-scale circulation: free-surface height `h` plus depth-averaged
8//! velocities `u`, `v`, with gravity and Coriolis `f`. See the `examples/`
9//! tour (`cargo run --example shallow_water -p tpt-sci-ocean`).
10//! * A 3-D **z-level** ocean core ([`Ocean3D`]) — a stack of `nz` layers with
11//! hydrostatic pressure from a linear equation of state, prognostic
12//! temperature/salinity tracers, constant-coefficient vertical mixing, and an
13//! optional **non-hydrostatic pressure-correction** (3-D Poisson projection
14//! solved with conjugate gradients on a structured grid). See
15//! `cargo run --example ocean3d -p tpt-sci-ocean`.
16//! * A **data assimilation** module ([`nudge`], [`EnsembleKalmanFilter`],
17//! [`Var3D`]) — nudging plus a stochastic EnKF and a 3D-Var-lite analysis.
18//!
19//! This crate is reduced-order relative to a full 3-D primitive-equation ocean
20//! GCM, but closes out the hydrostatic, non-hydrostatic, and assimilation scope
21//! items.
22//!
23//! # Example
24//!
25//! ```
26//! use tpt_sci_ocean::ShallowWater;
27//!
28//! // 64×64 basin, gravity g = 9.81, Coriolis f = 1e-4.
29//! let mut sw = ShallowWater::new(64, 64, 1.0, 1.0, 9.81, 1e-4, 0.001);
30//! // Perturb the free surface; it should evolve without blowing up.
31//! sw.perturb_center(1.0);
32//! for _ in 0..10 {
33//! sw.step(0.001);
34//! }
35//! assert!(sw.max_speed().is_finite());
36//! ```
37#![forbid(unsafe_code)]
38
39mod data_assim;
40mod error;
41mod ocean3d;
42
43pub use data_assim::{EnkfResult, EnsembleKalmanFilter, Observation, Var3D, nudge};
44pub use error::OceanError;
45pub use ocean3d::Ocean3D;
46
47use tpt_sci_cfd_core::CollocatedGrid;
48
49/// A 2-D shallow-water ocean model on a uniform grid.
50#[derive(Debug, Clone)]
51pub struct ShallowWater {
52 grid: CollocatedGrid,
53 /// Free-surface height `h` (m), length `nx·ny`.
54 pub h: Vec<f64>,
55 /// Depth-averaged `x`-velocity `u`.
56 pub u: Vec<f64>,
57 /// Depth-averaged `y`-velocity `v`.
58 pub v: Vec<f64>,
59 /// Rest height `H0` (m).
60 pub h0: f64,
61 /// Gravity `g` (m/s²).
62 pub g: f64,
63 /// Coriolis parameter `f` (1/s).
64 pub f: f64,
65 /// Linear bottom friction `k` (1/s).
66 pub friction: f64,
67}
68
69impl ShallowWater {
70 /// Construct a model with rest height `h0` everywhere.
71 ///
72 /// # Panics
73 ///
74 /// Panics if the underlying grid construction fails (non-positive extents or
75 /// zero cell counts).
76 pub fn new(nx: usize, ny: usize, lx: f64, ly: f64, g: f64, f: f64, _dt: f64) -> Self {
77 let grid = CollocatedGrid::new(nx, ny, lx, ly).unwrap();
78 let n = grid.len();
79 Self {
80 h: vec![10.0; n],
81 u: vec![0.0; n],
82 v: vec![0.0; n],
83 h0: 10.0,
84 g,
85 f,
86 friction: 1e-4,
87 grid,
88 }
89 }
90
91 /// Add a Gaussian bump of amplitude `amp` at the domain center (a
92 /// gravity-wave seed).
93 pub fn perturb_center(&mut self, amp: f64) {
94 let (cx, cy) = (self.grid.nx as f64 / 2.0, self.grid.ny as f64 / 2.0);
95 for j in 0..self.grid.ny {
96 for i in 0..self.grid.nx {
97 let d2 = (i as f64 - cx).powi(2) + (j as f64 - cy).powi(2);
98 self.h[self.grid.idx(i, j)] += amp * (-d2 / 20.0).exp();
99 }
100 }
101 }
102
103 /// Advance by one explicit step of the shallow-water equations.
104 pub fn step(&mut self, dt: f64) {
105 let g = &self.grid;
106 let (dx, dy) = (g.dx, g.dy);
107 let idx = |i: usize, j: usize| g.idx(i, j);
108 let clamp = |i: isize, m: usize| -> usize { i.clamp(0, m as isize - 1) as usize };
109 let (h0, grav, f, k) = (self.h0, self.g, self.f, self.friction);
110
111 let h = self.h.clone();
112 let u = self.u.clone();
113 let v = self.v.clone();
114 let mut nh = h.clone();
115 let mut nu = u.clone();
116 let mut nv = v.clone();
117
118 for j in 0..g.ny {
119 for i in 0..g.nx {
120 let c = idx(i, j);
121 let im = idx(clamp(i as isize - 1, g.nx), j);
122 let ip = idx(clamp(i as isize + 1, g.nx), j);
123 let jm = idx(i, clamp(j as isize - 1, g.ny));
124 let jp = idx(i, clamp(j as isize + 1, g.ny));
125
126 // Continuity: dh/dt = -∇·(h u), Lax–Friedrichs form: the
127 // neighbour average replaces h[c] so the centred scheme is stable.
128 let div = (h[ip] * u[ip] - h[im] * u[im]) / (2.0 * dx)
129 + (h[jp] * v[jp] - h[jm] * v[jm]) / (2.0 * dy);
130 let h_avg = 0.25 * (h[ip] + h[im] + h[jp] + h[jm]);
131 nh[c] = (h_avg - dt * div).max(1e-3);
132
133 // Momentum (x): du/dt = -(u·∇)u - g·∂η/∂x + f·v - k·u.
134 let dudx = (u[ip] - u[im]) / (2.0 * dx);
135 let dudy = (u[jp] - u[jm]) / (2.0 * dy);
136 let deta = (nh[ip] - nh[im]) / (2.0 * dx);
137 let u_avg = 0.25 * (u[ip] + u[im] + u[jp] + u[jm]);
138 nu[c] =
139 u_avg + dt * (-(u[c] * dudx + v[c] * dudy) - grav * deta + f * v[c] - k * u[c]);
140
141 // Momentum (y): dv/dt = -(v·∇)v - g·∂η/∂y - f·u - k·v.
142 let dvdx = (v[ip] - v[im]) / (2.0 * dx);
143 let dvdy = (v[jp] - v[jm]) / (2.0 * dy);
144 let detay = (nh[jp] - nh[jm]) / (2.0 * dy);
145 let v_avg = 0.25 * (v[ip] + v[im] + v[jp] + v[jm]);
146 nv[c] = v_avg
147 + dt * (-(u[c] * dvdx + v[c] * dvdy) - grav * detay - f * u[c] - k * v[c]);
148 }
149 }
150 self.h = nh;
151 self.u = nu;
152 self.v = nv;
153 let _ = h0;
154 }
155
156 /// Maximum horizontal speed `max(|u|, |v|)` (a stability indicator).
157 #[must_use]
158 pub fn max_speed(&self) -> f64 {
159 self.u
160 .iter()
161 .zip(self.v.iter())
162 .map(|(&uu, &vv)| (uu.abs()).max(vv.abs()))
163 .fold(0.0, f64::max)
164 }
165
166 /// Borrow the grid.
167 #[must_use]
168 pub fn grid(&self) -> &CollocatedGrid {
169 &self.grid
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176 use approx::assert_abs_diff_eq;
177
178 #[test]
179 fn still_water_stays_still() {
180 let mut sw = ShallowWater::new(32, 32, 1.0, 1.0, 9.81, 0.0, 0.001);
181 for _ in 0..20 {
182 sw.step(0.001);
183 }
184 assert_abs_diff_eq!(sw.max_speed(), 0.0, epsilon = 1e-9);
185 }
186
187 #[test]
188 fn bump_propagates_finitely() {
189 // dt chosen inside the explicit-scheme CFL limit: c·dt/dx < 1 with
190 // c = sqrt(g·h0) = sqrt(9.81·10) ≈ 9.9 and dx = 1/48.
191 let mut sw = ShallowWater::new(48, 48, 1.0, 1.0, 9.81, 1e-4, 0.001);
192 sw.perturb_center(1.0);
193 for _ in 0..30 {
194 sw.step(0.001);
195 }
196 assert!(sw.max_speed().is_finite());
197 // Height stays positive and bounded.
198 assert!(sw.h.iter().all(|&x| x > 0.0 && x.is_finite()));
199 }
200
201 #[test]
202 fn coriolis_deflects_flow() {
203 let mut sw = ShallowWater::new(32, 32, 1.0, 1.0, 9.81, 1e-3, 0.002);
204 sw.u[sw.grid.idx(16, 16)] = 1.0; // initial zonal velocity
205 sw.step(0.002);
206 // Coriolis f·v term should have spawned a meridional (v) component.
207 assert!(sw.v[sw.grid.idx(16, 16)].abs() > 0.0);
208 }
209}