Skip to main content

qualia_core_db/domains/physical/
thermodynamics.rs

1//! Thermodynamics & Statistical Ensembles
2//! Implements pure Rust Markov Chain Monte Carlo (MCMC) sampling for macroscopic properties.
3
4/// State of a thermodynamic ensemble
5#[derive(Clone)]
6pub struct EnsembleState {
7    pub temperature: f64,
8    pub particles: usize,
9    pub total_energy: f64,
10}
11
12/// Computes thermodynamic macroscopic properties from discrete structures via MCMC.
13pub struct ThermodynamicSampler {
14    pub current_state: EnsembleState,
15}
16
17impl ThermodynamicSampler {
18    /// Creates a default `ThermodynamicSampler`.
19    pub fn new(initial_temp: f64, particles: usize) -> Self {
20        Self {
21            current_state: EnsembleState {
22                temperature: initial_temp,
23                particles,
24                total_energy: 0.0,
25            },
26        }
27    }
28
29    /// Performs a Metropolis-Hastings MCMC step
30    pub fn metropolis_step(&mut self, proposed_energy: f64, random_uniform: f64) -> bool {
31        let delta_e = proposed_energy - self.current_state.total_energy;
32
33        // Accept if energy decreases or strictly probabilistically according to Boltzmann distribution
34        let k_b = 8.617333262145e-5; // Boltzmann constant in eV/K
35        let beta = 1.0 / (k_b * self.current_state.temperature);
36
37        let acceptance_probability = if delta_e < 0.0 {
38            1.0
39        } else {
40            (-beta * delta_e).exp()
41        };
42
43        if random_uniform < acceptance_probability {
44            self.current_state.total_energy = proposed_energy;
45            true // Accepted
46        } else {
47            false // Rejected
48        }
49    }
50
51    /// Calculates macroscopic Gibbs Free Energy approximation
52    pub fn calculate_gibbs_free_energy(&self, enthalpy: f64, entropy: f64) -> f64 {
53        // G = H - TS
54        enthalpy - (self.current_state.temperature * entropy)
55    }
56}
57
58// ─── Off-grid energy: battery / solar / heat-transfer models ─────────────────────
59//
60// The resilience-energy scope: rigorous thermal/electrical state for off-grid energy
61// storage (lithium banks under fluctuating loads), dynamic solar harvesting (MPP
62// tracking across mixed arrays), and heat-transfer efficiency in constrained/mobile
63// infrastructure. All zero-heap (pure-scalar equivalent-circuit / I-V / U·A·ΔT models).
64
65/// An off-grid lithium pack as an `S`×`P` array of prismatic cells, modelled as a
66/// first-order equivalent circuit (OCV − I·R sag). Captures the "down to the internal
67/// 4-prismatic-cell architecture" requirement: terminal voltage and deliverable power
68/// depend on the series/parallel topology, per-cell internal resistance, and SoC under
69/// a fluctuating load.
70#[derive(Debug, Clone, Copy)]
71pub struct LithiumPack {
72    pub cells_series: u32,
73    pub cells_parallel: u32,
74    pub cell_internal_resistance_ohm: f64,
75    pub cell_capacity_ah: f64,
76}
77
78impl LithiumPack {
79    /// Open-circuit voltage of ONE cell at a state-of-charge (0..1): a linearised
80    /// Li-ion curve from ~3.0 V (empty) to ~4.2 V (full).
81    pub fn cell_ocv(&self, soc: f64) -> f64 {
82        3.0 + (4.2 - 3.0) * soc.clamp(0.0, 1.0)
83    }
84
85    /// Pack open-circuit voltage = series count × cell OCV.
86    pub fn pack_ocv(&self, soc: f64) -> f64 {
87        self.cells_series as f64 * self.cell_ocv(soc)
88    }
89
90    /// Pack internal resistance = R_cell × S / P (series adds, parallel divides).
91    pub fn pack_resistance(&self) -> f64 {
92        self.cell_internal_resistance_ohm * self.cells_series as f64
93            / self.cells_parallel.max(1) as f64
94    }
95
96    /// Terminal voltage under a load current (A): OCV minus the internal-resistance sag.
97    pub fn terminal_voltage(&self, soc: f64, load_current_a: f64) -> f64 {
98        self.pack_ocv(soc) - load_current_a * self.pack_resistance()
99    }
100
101    /// Power (W) actually delivered to the load at a given SoC and current.
102    pub fn deliverable_power(&self, soc: f64, load_current_a: f64) -> f64 {
103        self.terminal_voltage(soc, load_current_a).max(0.0) * load_current_a
104    }
105
106    /// Total pack capacity (Ah) = per-cell capacity × parallel count.
107    pub fn pack_capacity_ah(&self) -> f64 {
108        self.cell_capacity_ah * self.cells_parallel as f64
109    }
110}
111
112/// A solar panel on a simplified single-knee I-V curve (`I_sc` scales with irradiance;
113/// `fill_factor` sets the knee sharpness ∝ panel/impedance quality).
114#[derive(Debug, Clone, Copy)]
115pub struct SolarPanel {
116    pub short_circuit_current_a: f64,
117    pub open_circuit_voltage_v: f64,
118    pub fill_factor: f64,
119}
120
121impl SolarPanel {
122    /// Current (A) at an operating voltage on the I-V curve `I = I_sc·(1 − (V/V_oc)^p)`,
123    /// with `p` derived from the fill factor (higher FF ⇒ squarer knee).
124    pub fn current_at(&self, v: f64) -> f64 {
125        if v <= 0.0 {
126            return self.short_circuit_current_a;
127        }
128        if v >= self.open_circuit_voltage_v {
129            return 0.0;
130        }
131        let p = (1.0 / (1.0 - self.fill_factor.clamp(0.05, 0.95))).max(1.0);
132        self.short_circuit_current_a * (1.0 - (v / self.open_circuit_voltage_v).powf(p))
133    }
134
135    /// Maximum power point: scan the I-V curve for the voltage maximising `P = V·I`.
136    /// Returns `(v_mp, i_mp, p_mp)` — the dynamic-harvesting operating point an MPPT
137    /// controller would seek as irradiance/impedance shift.
138    pub fn max_power_point(&self, scan_steps: u32) -> (f64, f64, f64) {
139        let mut best = (0.0f64, 0.0f64, 0.0f64);
140        let n = scan_steps.max(2);
141        for k in 1..n {
142            let v = self.open_circuit_voltage_v * k as f64 / n as f64;
143            let i = self.current_at(v);
144            let p = v * i;
145            if p > best.2 {
146                best = (v, i, p);
147            }
148        }
149        best
150    }
151}
152
153/// Total MPP power (W) harvested from a mixed-topology array — the sum of each panel's
154/// independently-tracked maximum power point. Zero-heap (slice in, scalar out).
155pub fn array_mppt_power(panels: &[SolarPanel], scan_steps: u32) -> f64 {
156    panels.iter().map(|p| p.max_power_point(scan_steps).2).sum()
157}
158
159/// Conductive/convective heat-loss rate (W) through an envelope: `Q = U·A·ΔT`.
160pub fn heat_loss_rate(u_value_w_m2k: f64, area_m2: f64, delta_t_k: f64) -> f64 {
161    u_value_w_m2k * area_m2 * delta_t_k
162}
163
164/// Latent heat (J) of a phase change for `mass_kg` at specific latent heat
165/// `latent_heat_j_kg` — the multi-phase (boiling/condensing/melting) energy term that
166/// sits alongside the sensible `Q = U·A·ΔT` loss.
167pub fn phase_change_energy(mass_kg: f64, latent_heat_j_kg: f64) -> f64 {
168    mass_kg * latent_heat_j_kg
169}
170
171/// Thermal efficiency of a heating/cooling system delivering `useful_power_w` against
172/// an envelope loss `U·A·ΔT`: `η = useful / (useful + loss)`, in `0..1`. Models the
173/// efficiency drop-off in constrained / mobile / pop-up infrastructure (thin envelope
174/// ⇒ high U ⇒ low η).
175pub fn thermal_efficiency(
176    useful_power_w: f64,
177    u_value_w_m2k: f64,
178    area_m2: f64,
179    delta_t_k: f64,
180) -> f64 {
181    let loss = heat_loss_rate(u_value_w_m2k, area_m2, delta_t_k).abs();
182    let useful = useful_power_w.max(0.0);
183    if useful + loss <= 0.0 {
184        return 0.0;
185    }
186    useful / (useful + loss)
187}
188
189#[cfg(test)]
190mod offgrid_energy_tests {
191    use super::*;
192
193    #[test]
194    fn lithium_pack_sags_under_load() {
195        // 4S2P pack, 5 mΩ per cell, 100 Ah cells.
196        let pack = LithiumPack {
197            cells_series: 4,
198            cells_parallel: 2,
199            cell_internal_resistance_ohm: 0.005,
200            cell_capacity_ah: 100.0,
201        };
202        assert!((pack.pack_ocv(1.0) - 16.8).abs() < 1e-9); // 4 × 4.2
203        assert!((pack.pack_capacity_ah() - 200.0).abs() < 1e-9); // 100 × 2
204        let rest = pack.terminal_voltage(0.5, 0.0);
205        let loaded = pack.terminal_voltage(0.5, 50.0);
206        assert!(loaded < rest, "terminal voltage must sag under load");
207        // sag = I·R_pack = 50 × (0.005×4/2) = 0.5 V
208        assert!((rest - loaded - 0.5).abs() < 1e-9);
209        assert!(pack.deliverable_power(0.5, 50.0) > 0.0);
210    }
211
212    #[test]
213    fn solar_mpp_is_between_zero_and_isc_voc() {
214        let panel = SolarPanel {
215            short_circuit_current_a: 8.0,
216            open_circuit_voltage_v: 40.0,
217            fill_factor: 0.75,
218        };
219        let (v_mp, i_mp, p_mp) = panel.max_power_point(256);
220        assert!(p_mp > 0.0);
221        assert!(v_mp > 0.0 && v_mp < panel.open_circuit_voltage_v);
222        assert!(i_mp > 0.0 && i_mp < panel.short_circuit_current_a);
223        // MPP power < the I_sc·V_oc rectangle (fill factor < 1).
224        assert!(p_mp < panel.short_circuit_current_a * panel.open_circuit_voltage_v);
225        // An array of two identical panels harvests ~2× one panel.
226        let arr = array_mppt_power(&[panel, panel], 256);
227        assert!((arr - 2.0 * p_mp).abs() < 1e-6);
228    }
229
230    #[test]
231    fn thermal_efficiency_drops_with_worse_insulation() {
232        // Same delivered heat, thicker vs thinner envelope (lower vs higher U).
233        let good = thermal_efficiency(1000.0, 0.5, 10.0, 20.0); // U=0.5 → loss 100 W
234        let bad = thermal_efficiency(1000.0, 3.0, 10.0, 20.0); // U=3.0 → loss 600 W
235        assert!(
236            good > bad,
237            "lower U (better insulation) ⇒ higher efficiency"
238        );
239        assert!(good > 0.0 && good < 1.0 && bad > 0.0 && bad < 1.0);
240        // Multi-phase latent term is additive and sane.
241        assert!((phase_change_energy(2.0, 334_000.0) - 668_000.0).abs() < 1.0); // ice→water
242    }
243}