Skip to main content

vle_steam/
lib.rs

1//! # `vle-steam` — IAPWS-IF97 industrial water/steam properties
2//!
3//! Steam tables are the single most-used thermodynamic reference in chemical
4//! engineering practice — sizing reboilers and condensers, steam-header
5//! balances, flash-steam recovery, turbine and valve calculations. Every
6//! printed steam table in a modern handbook is *computed from* one open
7//! standard, the **IAPWS Industrial Formulation 1997 (IF97)**, so this crate
8//! implements that standard directly rather than interpolating tabulated data.
9//!
10//! This is, in effect, "VLE for water only": a companion to the multicomponent
11//! [`vle-thermo`](https://crates.io/crates/vle-thermo) engine, kept as a
12//! separate crate because IF97 is a self-contained formulation with zero
13//! coupling to the mixture-EOS machinery — and dependency-free (pure `f64`
14//! math), so it stays trivially portable to a static-library / FFI build.
15//!
16//! ## What is implemented
17//!
18//! | Region | Physical domain | Equation |
19//! |---|---|---|
20//! | 1 | Compressed / subcooled liquid, 273.15–623.15 K | Gibbs `g(p,T)` |
21//! | 2 | Superheated vapor, ≤ 1073.15 K, ≤ 100 MPa | Gibbs `g(p,T)` |
22//! | 3 | Near-critical, 623.15–863.15 K above B23 | Helmholtz `f(ρ,T)` |
23//! | 4 | **Saturation line**, 273.15–647.096 K | closed-form both ways |
24//! | 5 | High-T steam, 1073.15–2273.15 K, ≤ 50 MPa | Gibbs `g(p,T)` |
25//!
26//! Plus IF97 backward equations `T(p,h)` and `T(p,s)` for regions 1 and 2
27//! (all three sub-regions each), which seed a short Newton polish on the
28//! forward equation — so a PH or PS flash costs a polynomial evaluation and
29//! two or three refinement steps rather than a bracketed search. Regions 3
30//! and 5 still solve `T` by bracketed iteration on the forward surface.
31//! Property derivatives are analytic throughout, never finite differences.
32//!
33//! Beyond the thermodynamic surface, the crate implements the three IAPWS
34//! transport/interfacial releases in their **industrial** form — viscosity
35//! ([`viscosity`], R12-08), thermal conductivity ([`thermal_conductivity`],
36//! R15-11, critical enhancement included) and surface tension
37//! ([`surface_tension`], R1-76(2014)) — plus the derived Prandtl number,
38//! kinematic viscosity and thermal diffusivity. See [`transport`].
39//!
40//! ## Units
41//!
42//! The public API takes **T in K** and **P in kPa absolute** (the repo canon,
43//! matching `vle-thermo`) and returns **mass-basis** properties — what every
44//! steam-table user expects:
45//!
46//! - specific enthalpy `h`, internal energy `u` — **kJ/kg**
47//! - specific entropy `s`, heat capacities `cp`, `cv` — **kJ/(kg·K)**
48//! - specific volume `v` — **m³/kg**; density `ρ` — **kg/m³**
49//! - speed of sound `w` — **m/s**
50//!
51//! Internally the IF97 equations run in their native units (MPa, kJ/kg);
52//! conversion happens once at the API boundary. Every function documents its
53//! units per the project's units rule.
54//!
55//! ## References
56//!
57//! - IAPWS. *Revised Release on the IAPWS Industrial Formulation 1997 for the
58//!   Thermodynamic Properties of Water and Steam*; IAPWS R7-97(2012), 2012.
59//! - Wagner, W.; Kretzschmar, H.-J. *International Steam Tables*, 3rd ed.;
60//!   Springer: Berlin, 2019.
61
62mod backward;
63mod coefficients;
64mod props;
65mod region1;
66mod region2;
67mod region3;
68pub mod region4;
69mod region5;
70pub mod regions;
71mod series;
72mod solve;
73mod state;
74pub mod transport;
75
76pub use props::Props;
77pub use state::{
78    MolarState, Phase, SatProps, SteamState, latent_heat, latent_heat_at_p, sat_p, sat_t,
79};
80
81use core::fmt;
82
83// ── Fundamental constants (IAPWS R7-97(2012) §1) ─────────────────────────
84
85/// Specific gas constant of ordinary water, **kJ/(kg·K)**.
86///
87/// `R = 0.461526 kJ/(kg·K)` — the IF97 value (Eq. 1). Note this is the
88/// *specific* (mass-basis) constant, not the molar `R` the engine uses.
89pub const R: f64 = 0.461526;
90
91/// Critical temperature of water, **K** (R7-97 §1).
92pub const T_C: f64 = 647.096;
93
94/// Critical pressure of water, **MPa** (R7-97 §1).
95pub const P_C_MPA: f64 = 22.064;
96
97/// Critical density of water, **kg/m³** (R7-97 §1).
98pub const RHO_C: f64 = 322.0;
99
100/// Molar mass of water, **kg/kmol** (IAPWS value) — used by the `.molar()`
101/// view to convert mass-basis properties to the engine's molar canon.
102pub const M_WATER: f64 = 18.015268;
103
104// ── Error type ───────────────────────────────────────────────────────────
105
106/// Errors returned by the state constructors and property queries.
107///
108/// The crate is dependency-free, so this hand-rolls [`fmt::Display`] and
109/// [`std::error::Error`] instead of deriving them with `thiserror`.
110#[derive(Debug, Clone, PartialEq)]
111pub enum SteamError {
112    /// A `(T, p)` (or derived) state point fell outside the IF97 validity
113    /// envelope. Carries the offending temperature (**K**) and pressure
114    /// (**kPa**).
115    OutOfRange {
116        /// Temperature in **K**.
117        t: f64,
118        /// Pressure in **kPa absolute**.
119        p: f64,
120    },
121    /// A quality (vapor fraction) argument was outside `0 ≤ x ≤ 1`.
122    InvalidQuality(f64),
123    /// A saturation query was requested outside `273.15 K ≤ T ≤ 647.096 K`
124    /// (or the equivalent pressure range).
125    OutOfSaturationRange(f64),
126    /// An iterative inner solve (e.g. region-3 density) failed to converge.
127    NoConvergence(&'static str),
128    /// A quantity that is defined **per phase** was requested at a two-phase
129    /// state. Transport properties are the case in point: there is no
130    /// meaningful quality-weighted viscosity or thermal conductivity of a
131    /// boiling mixture — the phases differ by more than an order of magnitude
132    /// and the mixture value depends on the flow regime, which is not
133    /// thermodynamics. Read the per-phase values off [`SatProps`] instead.
134    TwoPhase(&'static str),
135}
136
137impl fmt::Display for SteamError {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        match self {
140            SteamError::OutOfRange { t, p } => {
141                write!(f, "state (T={t} K, P={p} kPa) is outside the IF97 range")
142            }
143            SteamError::InvalidQuality(x) => {
144                write!(f, "quality x={x} is outside [0, 1]")
145            }
146            SteamError::OutOfSaturationRange(v) => {
147                write!(f, "saturation query {v} is outside 273.15 K … 647.096 K")
148            }
149            SteamError::NoConvergence(what) => {
150                write!(f, "iterative solve did not converge: {what}")
151            }
152            SteamError::TwoPhase(what) => {
153                write!(f, "not defined for a two-phase state: {what}")
154            }
155        }
156    }
157}
158
159impl std::error::Error for SteamError {}
160
161// ── Unit-conversion helpers at the API boundary ──────────────────────────
162
163/// kPa → MPa (IF97's native pressure unit).
164#[inline]
165pub(crate) fn kpa_to_mpa(p_kpa: f64) -> f64 {
166    p_kpa * 1e-3
167}
168
169/// MPa → kPa (repo-canonical pressure unit).
170#[inline]
171pub(crate) fn mpa_to_kpa(p_mpa: f64) -> f64 {
172    p_mpa * 1e3
173}
174
175// ── Re-exports: the flat public surface ──────────────────────────────────
176
177pub use region4::{d_psat_d_t as psat_derivative_mpa, psat as psat_mpa, tsat as tsat_mpa};
178pub use regions::{Region, region_of};
179
180/// Saturation pressure at temperature `t`.
181///
182/// # Arguments
183/// * `t` — Temperature in **K**, valid on `273.15 ≤ t ≤ 647.096`.
184///
185/// # Returns
186/// Saturation pressure in **kPa absolute** (repo canon).
187pub fn psat(t: f64) -> Result<f64, SteamError> {
188    if !(region4::T_MIN..=region4::T_MAX).contains(&t) {
189        return Err(SteamError::OutOfSaturationRange(t));
190    }
191    Ok(mpa_to_kpa(region4::psat(t)))
192}
193
194/// Saturation temperature at pressure `p`.
195///
196/// # Arguments
197/// * `p` — Pressure in **kPa absolute**, valid between the triple- and
198///   critical-point saturation pressures.
199///
200/// # Returns
201/// Saturation temperature in **K**.
202pub fn tsat(p: f64) -> Result<f64, SteamError> {
203    let p_mpa = kpa_to_mpa(p);
204    if !(region4::P_MIN_MPA..=region4::P_MAX_MPA).contains(&p_mpa) {
205        return Err(SteamError::OutOfSaturationRange(p));
206    }
207    Ok(region4::tsat(p_mpa))
208}
209
210/// Analytic derivative `dPsat/dT` of the saturation curve.
211///
212/// # Arguments
213/// * `t` — Temperature in **K**.
214///
215/// # Returns
216/// `dPsat/dT` in **kPa/K**.
217pub fn psat_derivative(t: f64) -> Result<f64, SteamError> {
218    if !(region4::T_MIN..=region4::T_MAX).contains(&t) {
219        return Err(SteamError::OutOfSaturationRange(t));
220    }
221    Ok(mpa_to_kpa(region4::d_psat_d_t(t)))
222}
223
224/// Dynamic viscosity at a single-phase state.
225///
226/// # Arguments
227/// * `t` — Temperature in **K**.
228/// * `p` — Pressure in **kPa absolute**.
229///
230/// # Returns
231/// Dynamic viscosity in **Pa·s**.
232///
233/// IAPWS R12-08, industrial form (`μ₂ = 1`, densities from IF97 — §3 of that
234/// release). Returns [`SteamError::TwoPhase`] on the saturation line, where
235/// viscosity is a per-phase quantity; use [`SatProps::mu_f`] / [`SatProps::mu_g`].
236pub fn viscosity(t: f64, p: f64) -> Result<f64, SteamError> {
237    let st = SteamState::tp(t, p)?;
238    if st.phase == Phase::TwoPhase {
239        return Err(SteamError::TwoPhase("viscosity"));
240    }
241    Ok(viscosity_rho_t(st.rho, t))
242}
243
244/// Dynamic viscosity from density and temperature — the form IAPWS R12-08 is
245/// written in, and the one region-3 callers already have.
246///
247/// # Arguments
248/// * `rho` — Density in **kg/m³**.
249/// * `t` — Temperature in **K**.
250///
251/// # Returns
252/// Dynamic viscosity in **Pa·s**.
253pub fn viscosity_rho_t(rho: f64, t: f64) -> f64 {
254    transport::viscosity_bar(rho, t) * 1e-6 // µPa·s → Pa·s
255}
256
257/// Thermal conductivity at a single-phase state.
258///
259/// # Arguments
260/// * `t` — Temperature in **K**.
261/// * `p` — Pressure in **kPa absolute**.
262///
263/// # Returns
264/// Thermal conductivity in **W/(m·K)**.
265///
266/// IAPWS R15-11, industrial form — `c_p`, `κ` and `ζ = (∂ρ̄/∂p̄)_T̄` from IF97,
267/// with the reference-temperature compressibility from that release's Eq. (25).
268/// The critical enhancement `λ₂` is included everywhere except region 5, where
269/// R15-11 §3.4 sets it to zero. Returns [`SteamError::TwoPhase`] on the
270/// saturation line; use [`SatProps::k_f`] / [`SatProps::k_g`].
271pub fn thermal_conductivity(t: f64, p: f64) -> Result<f64, SteamError> {
272    let st = SteamState::tp(t, p)?;
273    if st.phase == Phase::TwoPhase {
274        return Err(SteamError::TwoPhase("thermal conductivity"));
275    }
276    let region = st.region;
277    // R15-11 §3.4 footnote 3: in region 5 the critical enhancement is zero.
278    let enhanced = region != Region::Five;
279    let dr_dp = if enhanced {
280        transport::drho_dp(t, p, region)?
281    } else {
282        0.0
283    };
284    let (l0, l1, l2) =
285        transport::thermal_conductivity_parts(t, st.rho, st.cp, st.cv, dr_dp, enhanced);
286    Ok((l0 * l1 + l2) * 1e-3) // mW/(m·K) → W/(m·K)
287}
288
289pub use transport::surface_tension;
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294    use approx::assert_relative_eq;
295
296    /// R15-11 **Tables 7–9** — the *industrial* program-verification tables,
297    /// keyed on IF97 regions 1, 2 and 3. These are the ones an IF97-based
298    /// implementation must reproduce; the release's Tables 4–5 were generated
299    /// with IAPWS-95 and are not reachable from here.
300    ///
301    /// Asserted term by term (`λ₀`, `λ₁`, `λ₂` and the total), because the
302    /// tables publish the breakdown — so a mistake in any one factor is
303    /// localized rather than hidden inside a total that lands close.
304    #[test]
305    fn r15_11_industrial_tables_7_to_9() {
306        // (T K, p kPa, λ mW/(m·K), λ₀, λ₁, λ₂)
307        let tp_cases = [
308            // Table 7 — region 1
309            (
310                620.0,
311                20_000.0,
312                0.481485195e3,
313                0.484911627e2,
314                0.966869008e1,
315                0.126391714e2,
316            ),
317            (
318                620.0,
319                50_000.0,
320                0.545038940e3,
321                0.484911627e2,
322                0.111212177e2,
323                0.575816285e1,
324            ),
325            // Table 8 — region 2
326            (
327                650.0,
328                300.0,
329                0.522311024e2,
330                0.518787461e2,
331                0.100678943e1,
332                0.129246457e-3,
333            ),
334            (
335                800.0,
336                50_000.0,
337                0.177709914e3,
338                0.698329394e2,
339                0.244965343e1,
340                0.664341394e1,
341            ),
342        ];
343        for (t, p, lam, l0e, l1e, l2e) in tp_cases {
344            let st = SteamState::tp(t, p).unwrap();
345            let dr = transport::drho_dp(t, p, st.region).unwrap();
346            let (l0, l1, l2) =
347                transport::thermal_conductivity_parts(t, st.rho, st.cp, st.cv, dr, true);
348            assert_relative_eq!(l0, l0e, max_relative = 1e-8);
349            assert_relative_eq!(l1, l1e, max_relative = 1e-6);
350            assert_relative_eq!(l2, l2e, max_relative = 1e-6);
351            assert_relative_eq!(l0 * l1 + l2, lam, max_relative = 1e-6);
352            assert_relative_eq!(
353                thermal_conductivity(t, p).unwrap(),
354                lam * 1e-3,
355                max_relative = 1e-6
356            );
357        }
358        // Table 9 — region 3, given as (ρ, T) rather than (p, T)
359        for (t, rho, lam, l0e, l1e, l2e) in [
360            (
361                647.35,
362                222.0,
363                0.366879411e3,
364                0.515764797e2,
365                0.348407362e1,
366                0.187183159e3,
367            ),
368            (
369                647.35,
370                322.0,
371                0.124182415e4,
372                0.515764797e2,
373                0.496819532e1,
374                0.985582122e3,
375            ),
376        ] {
377            let pr = region3::props_rho_t(rho, t);
378            let dr = 1.0 / region3::dp_drho(rho, t);
379            let (l0, l1, l2) =
380                transport::thermal_conductivity_parts(t, rho, pr.cp, pr.cv, dr, true);
381            assert_relative_eq!(l0, l0e, max_relative = 1e-8);
382            assert_relative_eq!(l1, l1e, max_relative = 1e-6);
383            assert_relative_eq!(l2, l2e, max_relative = 1e-5);
384            assert_relative_eq!(l0 * l1 + l2, lam, max_relative = 1e-5);
385        }
386    }
387
388    /// The published `(∂ρ/∂p)_T` column of Tables 7–9 — asserting the analytic
389    /// derivative directly, not only through the conductivity it feeds.
390    #[test]
391    fn drho_dp_matches_published_column() {
392        // (T K, p kPa, (∂ρ/∂p)_T in kg·m⁻³·MPa⁻¹)
393        for (t, p, expected) in [
394            (620.0, 20_000.0, 0.520937820e1),
395            (620.0, 50_000.0, 0.184869007e1),
396            (650.0, 300.0, 0.336351419e1),
397            (800.0, 50_000.0, 0.661484493e1),
398        ] {
399            let region = SteamState::tp(t, p).unwrap().region;
400            // (kg/m³)/kPa → (kg/m³)/MPa
401            let got = transport::drho_dp(t, p, region).unwrap() * 1e3;
402            assert_relative_eq!(got, expected, max_relative = 1e-6);
403        }
404        for (t, rho, expected) in [
405            (647.35, 222.0, 0.177778595e3),
406            (647.35, 322.0, 0.692651138e4),
407        ] {
408            let got = 1.0 / region3::dp_drho(rho, t) * 1e3;
409            assert_relative_eq!(got, expected, max_relative = 1e-5);
410        }
411    }
412
413    /// The published viscosity column of Tables 7–9 — confirming this crate's
414    /// R12-08 industrial viscosity is the one R15-11's `λ₂` was built on.
415    #[test]
416    fn viscosity_matches_r15_11_column() {
417        for (t, p, expected_upa) in [
418            (620.0, 20_000.0, 0.709051068e2),
419            (620.0, 50_000.0, 0.841527945e2),
420            (650.0, 300.0, 0.234877453e2),
421            (800.0, 50_000.0, 0.393727534e2),
422        ] {
423            let got = viscosity(t, p).unwrap() * 1e6; // Pa·s → µPa·s
424            assert_relative_eq!(got, expected_upa, max_relative = 1e-6);
425        }
426    }
427
428    /// Transport properties are per-phase: a two-phase state must refuse
429    /// rather than quietly average.
430    #[test]
431    fn two_phase_transport_is_refused() {
432        let tsat = tsat(100.0).unwrap();
433        assert!(matches!(
434            viscosity(tsat, 100.0),
435            Err(SteamError::TwoPhase(_))
436        ));
437        assert!(matches!(
438            thermal_conductivity(tsat, 100.0),
439            Err(SteamError::TwoPhase(_))
440        ));
441    }
442
443    #[test]
444    fn public_psat_in_kpa() {
445        // Table 35 value, converted to kPa: 0.353658941e-2 MPa = 3.53658941 kPa.
446        assert_relative_eq!(psat(300.0).unwrap(), 3.53658941, max_relative = 1e-8);
447    }
448
449    #[test]
450    fn public_tsat_in_kpa() {
451        // Table 36: Tsat(0.1 MPa = 100 kPa) = 372.755919 K.
452        assert_relative_eq!(tsat(100.0).unwrap(), 372.755919, max_relative = 1e-8);
453    }
454
455    #[test]
456    fn saturation_range_guards() {
457        assert!(matches!(
458            psat(260.0),
459            Err(SteamError::OutOfSaturationRange(_))
460        ));
461        assert!(matches!(
462            psat(700.0),
463            Err(SteamError::OutOfSaturationRange(_))
464        ));
465    }
466
467    /// Region-boundary continuity: neighbouring regions must agree on `v, h, s`
468    /// to IF97's stated inter-region consistency (well within 0.1%).
469    #[test]
470    fn region_boundary_continuity() {
471        // 2 ↔ 3 seam: the B23 line at T = 700 K.
472        {
473            let t = 700.0;
474            let p = mpa_to_kpa(regions::b23_p(t));
475            let r2 = region2::props(t, p);
476            let r3 = region3::props_tp(t, p).unwrap();
477            assert_relative_eq!(r2.v, r3.v, max_relative = 1e-3);
478            assert_relative_eq!(r2.h, r3.h, max_relative = 1e-3);
479            assert_relative_eq!(r2.s, r3.s, max_relative = 1e-3);
480        }
481        // 1 ↔ 3 seam: the 623.15 K isotherm at 50 MPa.
482        {
483            let (t, p) = (623.15, 50_000.0);
484            let r1 = region1::props(t, p);
485            let r3 = region3::props_tp(t, p).unwrap();
486            assert_relative_eq!(r1.v, r3.v, max_relative = 1e-3);
487            assert_relative_eq!(r1.h, r3.h, max_relative = 1e-3);
488            assert_relative_eq!(r1.s, r3.s, max_relative = 1e-3);
489        }
490        // 2 ↔ 5 seam: the 1073.15 K isotherm at 10 MPa.
491        {
492            let (t, p) = (1073.15, 10_000.0);
493            let r2 = region2::props(t, p);
494            let r5 = region5::props(t, p);
495            assert_relative_eq!(r2.v, r5.v, max_relative = 1e-3);
496            assert_relative_eq!(r2.h, r5.h, max_relative = 1e-3);
497            assert_relative_eq!(r2.s, r5.s, max_relative = 1e-3);
498        }
499    }
500}