Skip to main content

tpt_sci_climate/
lib.rs

1//! # tpt-sci-climate
2//!
3//! Simple **climate modelling** for the `tpt-science` pillar, built on
4//! [`tpt_sci_ode`]. It provides reduced-order models suitable for coupling and
5//! teaching:
6//!
7//! * A **0-D energy-balance model** [`EnergyBalanceModel`] — global-mean
8//!   surface temperature under incoming shortwave, grey-body longwave outgoing,
9//!   and a CO₂ radiative-forcing term (`ΔF = 5.35·ln(C/C0)` W/m²).
10//! * **Multi-band longwave radiative transfer** (`radiative_transfer`) — a
11//!   simplified multi-band grey-slab scheme [`MultiBandRadiativeTransfer`] and a
12//!   `k`-distribution [`CorrelatedKRt`], replacing the single grey band of
13//!   [`grey_radiative_transfer`].
14//! * A tiny **atmospheric chemistry** box [`ChemistryBox`] for a linear
15//!   production–loss tracer (e.g. OH-driven CH₄ decay), extended to a 3-D
16//!   advection–diffusion–reaction tracer field [`Tracer3D`].
17//! * A genuine **primitive-equation atmospheric GCM dynamical core**
18//!   [`AtmosphereGcm`] — a 3-D hydrostatic (optionally non-hydrostatic) primitive
19//!   equation solver, coupled to the [`EnergyBalanceModel`].
20//!
21//! These close out the v1 "out of scope" climate items: the single grey band is
22//! replaced by a multi-band/correlated-k scheme, chemistry is extended to 3-D
23//! transport, and the EBM is backed by a working GCM dynamical core.
24//!
25//! # Example
26//!
27//! ```
28//! use tpt_sci_climate::EnergyBalanceModel;
29//!
30//! let mut ebm = EnergyBalanceModel::new(1.0, 0.3, 0.61, 280.0).unwrap();
31//! // Integrate temperature for a year; it relaxes to equilibrium.
32//! for _ in 0..100 {
33//!     ebm.step(1.0);
34//! }
35//! assert!(ebm.temperature().is_finite());
36//! ```
37#![forbid(unsafe_code)]
38
39mod chemistry_3d;
40mod error;
41mod gcm;
42mod radiative_transfer;
43
44pub use chemistry_3d::Tracer3D;
45pub use error::ClimateError;
46pub use gcm::AtmosphereGcm;
47pub use radiative_transfer::{Band, CorrelatedKBand, CorrelatedKRt, MultiBandRadiativeTransfer};
48
49/// Stefan–Boltzmann constant (W·m⁻²·K⁻⁴).
50pub const SIGMA: f64 = tpt_sci_units::STEFAN_BOLTZMANN.value();
51/// Pre-industrial CO₂ reference (ppm).
52pub const CO2_PREINDUSTRIAL: f64 = 280.0;
53
54/// 0-D global energy-balance climate model.
55///
56/// `C·dT/dt = (1−α)·S/4 − ε·σ·T⁴ + ΔF(CO₂)`, where `C` is the heat capacity
57/// (J·m⁻²·K⁻¹), `α` the planetary albedo, `ε` the effective emissivity, `S` the
58/// solar constant, and `ΔF = 5.35·ln(C/C0)`.
59#[derive(Debug, Clone)]
60pub struct EnergyBalanceModel {
61    /// Heat capacity `C` (J·m⁻²·K⁻¹); ~ocean mixed layer equivalent.
62    pub heat_capacity: f64,
63    /// Planetary albedo `α` (0..1).
64    pub albedo: f64,
65    /// Effective longwave emissivity `ε` (0..1).
66    pub emissivity: f64,
67    /// Solar constant `S` (W/m²).
68    pub solar_constant: f64,
69    /// Current CO₂ concentration (ppm).
70    pub co2: f64,
71    /// Global-mean surface temperature `T` (K).
72    pub t: f64,
73}
74
75impl EnergyBalanceModel {
76    /// Construct a validated EBM at temperature `t0`.
77    ///
78    /// # Errors
79    ///
80    /// Returns [`ClimateError::InvalidModel`] if `t0 <= 0`, `albedo` outside
81    /// `[0,1]`, `emissivity <= 0`, or `co2 <= 0`.
82    pub fn new(
83        heat_capacity: f64,
84        albedo: f64,
85        emissivity: f64,
86        co2: f64,
87    ) -> Result<Self, ClimateError> {
88        if heat_capacity <= 0.0 {
89            return Err(ClimateError::InvalidModel(
90                "heat capacity must be > 0".into(),
91            ));
92        }
93        if !(0.0..=1.0).contains(&albedo) {
94            return Err(ClimateError::InvalidModel("albedo must be in [0,1]".into()));
95        }
96        if emissivity <= 0.0 {
97            return Err(ClimateError::InvalidModel("emissivity must be > 0".into()));
98        }
99        if co2 <= 0.0 {
100            return Err(ClimateError::InvalidModel("CO2 must be > 0".into()));
101        }
102        Ok(Self {
103            heat_capacity,
104            albedo,
105            emissivity,
106            solar_constant: 1361.0,
107            co2,
108            t: 288.0,
109        })
110    }
111
112    /// Current CO₂ radiative forcing `ΔF = 5.35·ln(C/C0)` (W/m²).
113    #[must_use]
114    pub fn forcing(&self) -> f64 {
115        5.35 * (self.co2 / CO2_PREINDUSTRIAL).ln()
116    }
117
118    /// Net top-of-atmosphere flux (W/m²), `> 0` warms.
119    #[must_use]
120    pub fn net_flux(&self) -> f64 {
121        (1.0 - self.albedo) * self.solar_constant / 4.0 - self.emissivity * SIGMA * self.t.powi(4)
122            + self.forcing()
123    }
124
125    /// Current temperature (K).
126    #[must_use]
127    pub fn temperature(&self) -> f64 {
128        self.t
129    }
130
131    /// Advance the EBM by `dt` seconds.
132    ///
133    /// Uses a linearised backward-Euler update: the radiative loss is
134    /// differentiated about the current `T`, which gives
135    /// `ΔT = dt·F(T) / (C + 4·dt·ε·σ·T³)`. This is unconditionally stable for the
136    /// radiative relaxation, so a large `dt` relative to `C / (4εσT³)` cannot
137    /// make the solution oscillate or diverge. For `dt` much smaller than that
138    /// time scale it agrees with explicit Euler to first order.
139    pub fn step(&mut self, dt: f64) {
140        let f = self.net_flux();
141        let damping = self.heat_capacity + 4.0 * dt * self.emissivity * SIGMA * self.t.powi(3);
142        self.t += dt * f / damping;
143        if self.t < 0.0 {
144            self.t = 0.0;
145        }
146    }
147
148    /// Equilibrium temperature (where `net_flux = 0`), solved by a few fixed-point
149    /// Newton iterations from the current `t`.
150    #[must_use]
151    pub fn equilibrium_temperature(&self) -> f64 {
152        let mut t = self.t.max(1.0);
153        for _ in 0..50 {
154            let f = (1.0 - self.albedo) * self.solar_constant / 4.0
155                - self.emissivity * SIGMA * t.powi(4)
156                + self.forcing();
157            let df = -4.0 * self.emissivity * SIGMA * t.powi(3);
158            t = (t - f / df).max(1.0);
159        }
160        t
161    }
162}
163
164/// Single-layer grey-atmosphere radiative temperature: with a grey gas of
165/// emissivity `eps`, the surface temperature `Ts = (S·(1−α)/(4·σ·(1−eps/2)))^(1/4)`.
166///
167/// # Errors
168///
169/// Returns [`ClimateError::InvalidModel`] if `s <= 0`, `alpha` is outside
170/// `[0, 1]`, or `eps` is outside `[0, 1)`.
171pub fn grey_radiative_transfer(s: f64, alpha: f64, eps: f64) -> Result<f64, ClimateError> {
172    if s.is_nan() || s <= 0.0 {
173        return Err(ClimateError::InvalidModel("S must be > 0".into()));
174    }
175    if !(0.0..=1.0).contains(&alpha) {
176        return Err(ClimateError::InvalidModel(
177            "albedo must be in [0, 1]".into(),
178        ));
179    }
180    if !(0.0..1.0).contains(&eps) {
181        return Err(ClimateError::InvalidModel("eps must be in [0, 1)".into()));
182    }
183    Ok(((s * (1.0 - alpha)) / (4.0 * SIGMA * (1.0 - eps / 2.0))).powf(0.25))
184}
185
186/// A minimal atmospheric-chemistry box: `dC/dt = P − k·C` (constant production
187/// `P`, first-order loss `k`). Models e.g. a well-mixed CH₄-like tracer.
188#[derive(Debug, Clone)]
189pub struct ChemistryBox {
190    /// Concentration (ppb-ish, arbitrary units).
191    pub concentration: f64,
192    /// Constant production rate `P`.
193    pub production: f64,
194    /// First-order loss coefficient `k` (1/s).
195    pub loss: f64,
196}
197
198impl ChemistryBox {
199    /// Construct a validated box.
200    ///
201    /// # Errors
202    ///
203    /// Returns [`ClimateError::InvalidModel`] if `loss < 0` or `concentration < 0`.
204    pub fn new(concentration: f64, production: f64, loss: f64) -> Result<Self, ClimateError> {
205        if concentration < 0.0 {
206            return Err(ClimateError::InvalidModel(
207                "concentration must be >= 0".into(),
208            ));
209        }
210        if loss < 0.0 {
211            return Err(ClimateError::InvalidModel("loss must be >= 0".into()));
212        }
213        Ok(Self {
214            concentration,
215            production,
216            loss,
217        })
218    }
219
220    /// Steady-state concentration `C* = P/k` (with `k > 0`).
221    #[must_use]
222    pub fn steady_state(&self) -> f64 {
223        if self.loss > 0.0 {
224            self.production / self.loss
225        } else {
226            f64::INFINITY
227        }
228    }
229
230    /// Advance by `dt`.
231    pub fn step(&mut self, dt: f64) {
232        self.concentration += dt * (self.production - self.loss * self.concentration);
233        if self.concentration < 0.0 {
234            self.concentration = 0.0;
235        }
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    use approx::assert_abs_diff_eq;
243
244    #[test]
245    fn ebm_relaxes_to_equilibrium() {
246        let mut ebm = EnergyBalanceModel::new(1.0e7, 0.3, 0.61, 280.0).unwrap();
247        for _ in 0..2000 {
248            ebm.step(1.0);
249        }
250        // Doubling CO2 raises equilibrium temperature vs pre-industrial.
251        let teq = ebm.equilibrium_temperature();
252        assert!(teq.is_finite() && teq > 250.0);
253        let ebm2 = EnergyBalanceModel::new(1.0e7, 0.3, 0.61, 560.0).unwrap();
254        let teq2 = ebm2.equilibrium_temperature();
255        assert!(teq2 > teq, "doubling CO2 should warm the EBM");
256    }
257
258    #[test]
259    fn grey_transfer_monotonic_in_greenhouse() {
260        let clear = grey_radiative_transfer(1361.0, 0.3, 0.0).unwrap();
261        let greenhouse = grey_radiative_transfer(1361.0, 0.3, 0.5).unwrap();
262        assert!(greenhouse > clear);
263    }
264
265    #[test]
266    fn chemistry_reaches_steady_state() {
267        let mut c = ChemistryBox::new(0.0, 1.0, 0.1).unwrap();
268        for _ in 0..1000 {
269            c.step(0.1);
270        }
271        assert_abs_diff_eq!(c.concentration, c.steady_state(), epsilon = 1e-3);
272    }
273}