Skip to main content

vibe/physics/
domain_facets.rs

1//! Cross-Domain Constitutive Facets and Bond-Graph Ports.
2//!
3//! Provides biomechanical (Hill muscle), botanical/hydraulic (Allometric branch),
4//! mechanical structural (Fatigue & corrosion), and port-Hamiltonian energy
5//! conservation primitives for VibeScript physics.
6//!
7//! Reference: `AGENTS.md` Workstream W5 (§6.1–§6.2).
8
9use std::f64::consts::PI;
10
11/// Biomechanical muscle actuator facet based on Hill's three-element muscle model.
12///
13/// $$F_{\text{muscle}}(t) = F_{\max}\left[a(t)\cdot f_L(\tilde{l})\cdot f_V(\tilde{v}) + f_P(\tilde{l})\right]\cos\alpha_{\text{penn}}$$
14#[derive(Debug, Clone, Copy, PartialEq)]
15pub struct HillMuscleFacet {
16    /// Maximum isometric force at optimal fiber length (N).
17    pub max_isometric_force_n: f64,
18    /// Optimal muscle fiber length $L_0$ (m).
19    pub optimal_fiber_length_m: f64,
20    /// Elastic tendon slack length $L_s^T$ (m).
21    pub tendon_slack_length_m: f64,
22    /// Maximum contraction velocity normalized to $L_0$ ($s^{-1}$).
23    pub max_contraction_velocity_l0_s: f64,
24    /// Muscle fiber pennation angle with respect to tendon line of action (radians).
25    pub pennation_angle_rad: f64,
26}
27
28impl HillMuscleFacet {
29    /// Constructs a new Hill muscle facet.
30    pub const fn new(
31        max_isometric_force_n: f64,
32        optimal_fiber_length_m: f64,
33        tendon_slack_length_m: f64,
34        max_contraction_velocity_l0_s: f64,
35        pennation_angle_rad: f64,
36    ) -> Self {
37        Self {
38            max_isometric_force_n,
39            optimal_fiber_length_m,
40            tendon_slack_length_m,
41            max_contraction_velocity_l0_s,
42            pennation_angle_rad,
43        }
44    }
45
46    /// Evaluates the active normalized force-length relationship $f_L(\tilde{l})$.
47    ///
48    /// $$f_L(\tilde{l}) = \exp\left( - \left(\frac{\tilde{l} - 1.0}{0.45}\right)^2 \right)$$
49    #[inline]
50    pub fn active_force_length(l_norm: f64) -> f64 {
51        let delta = (l_norm - 1.0) / 0.45;
52        (-delta * delta).exp()
53    }
54
55    /// Evaluates the normalized force-velocity relationship $f_V(\tilde{v})$.
56    ///
57    /// Uses Hill's hyperbola for concentric shortening ($\tilde{v} < 0$) and an
58    /// eccentric plateau saturating up to 1.4 for lengthening ($\tilde{v} > 0$).
59    #[inline]
60    pub fn force_velocity(v_norm: f64) -> f64 {
61        if v_norm <= -1.0 {
62            0.0
63        } else if v_norm < 0.0 {
64            // Concentric shortening: Hill hyperbola (c = 0.25)
65            (1.0 + v_norm) / (1.0 - v_norm / 0.25)
66        } else {
67            // Eccentric lengthening: asymptotic plateau up to 1.4
68            1.0 + 0.4 * (v_norm / (v_norm + 0.1))
69        }
70    }
71
72    /// Evaluates the passive normalized force-length relationship $f_P(\tilde{l})$.
73    ///
74    /// Exponential tension curve engaged when fiber length exceeds optimal length ($\tilde{l} > 1.0$).
75    #[inline]
76    pub fn passive_force_length(l_norm: f64) -> f64 {
77        if l_norm <= 1.0 {
78            0.0
79        } else {
80            let dl = l_norm - 1.0;
81            (4.0 * dl).exp() - 1.0
82        }
83    }
84
85    /// Computes total muscle force transmitted to the tendon (N).
86    pub fn compute_tendon_force(
87        &self,
88        activation: f64,
89        fiber_length_m: f64,
90        fiber_velocity_m_s: f64,
91    ) -> f64 {
92        let a = activation.clamp(0.0, 1.0);
93        let l_opt = self.optimal_fiber_length_m.max(1e-9);
94        let l_norm = fiber_length_m / l_opt;
95        let v_max = self.max_contraction_velocity_l0_s * l_opt;
96        let v_norm = fiber_velocity_m_s / v_max.max(1e-9);
97
98        let f_l = Self::active_force_length(l_norm);
99        let f_v = Self::force_velocity(v_norm);
100        let f_p = Self::passive_force_length(l_norm);
101
102        let active_passive = (a * f_l * f_v + f_p).max(0.0);
103        let force = self.max_isometric_force_n * active_passive * self.pennation_angle_rad.cos();
104        force.max(0.0)
105    }
106}
107
108/// Botanical morphogenesis allometric scaling laws and xylem transpiration hydraulics.
109#[derive(Debug, Clone, Copy, PartialEq)]
110pub struct AllometricBranchLaw {
111    /// Allometric branching exponent $\gamma \in [2.0, 3.0]$ (Murray's Law default: 2.49).
112    pub gamma: f64,
113    /// West-Brown-Enquist (WBE) radius scaling exponent $a \approx 1/3$.
114    pub wbe_radius_exp: f64,
115    /// West-Brown-Enquist (WBE) length scaling exponent $b \approx 2/3$.
116    pub wbe_length_exp: f64,
117}
118
119impl Default for AllometricBranchLaw {
120    fn default() -> Self {
121        Self {
122            gamma: 2.49,
123            wbe_radius_exp: 1.0 / 3.0,
124            wbe_length_exp: 2.0 / 3.0,
125        }
126    }
127}
128
129impl AllometricBranchLaw {
130    /// Computes child branch radii given a parent radius and split ratio $\eta \in [0.0, 1.0]$.
131    ///
132    /// $$r_{\text{parent}}^\gamma = r_{\text{child},1}^\gamma + r_{\text{child},2}^\gamma$$
133    pub fn child_radii_from_split(&self, parent_radius: f64, split_ratio: f64) -> (f64, f64) {
134        let eta = split_ratio.clamp(0.0, 1.0);
135        let inv_gamma = 1.0 / self.gamma.max(1e-6);
136        let r_p = parent_radius.max(0.0);
137        let r1 = r_p * eta.powf(inv_gamma);
138        let r2 = r_p * (1.0 - eta).powf(inv_gamma);
139        (r1, r2)
140    }
141
142    /// Verifies Da Vinci / Murray conservation residual: $|r_{\text{parent}}^\gamma - \sum r_{\text{child}}^\gamma|$.
143    pub fn verify_da_vinci_conservation(&self, parent_radius: f64, child_radii: &[f64]) -> f64 {
144        let sum_children: f64 = child_radii.iter().map(|&r| r.max(0.0).powf(self.gamma)).sum();
145        let parent_pow = parent_radius.max(0.0).powf(self.gamma);
146        (parent_pow - sum_children).abs()
147    }
148
149    /// Evaluates golden-angle phyllotaxis direction vector for primordium / leaf node $n$.
150    ///
151    /// $$\theta_n = n \cdot 137.50776405^\circ, \quad r_n = c \sqrt{n}$$
152    pub fn phyllotaxis_direction(index: u32, scale_c: f64) -> [f64; 3] {
153        let n_f = index as f64;
154        let golden_angle_rad = 137.50776405 * (PI / 180.0);
155        let theta = n_f * golden_angle_rad;
156        let r = scale_c * n_f.sqrt();
157        [r * theta.cos(), r * theta.sin(), 0.0]
158    }
159
160    /// Evaluates Darcy-Hagen-Poiseuille xylem transpiration flux density ($m \cdot s^{-1}$).
161    ///
162    /// $$J_w = -K_h \left(\frac{\Delta\Psi}{\Delta z} + \rho g\right)$$
163    pub fn darcy_transpiration_flux(
164        conductance_k: f64,
165        psi_soil_mpa: f64,
166        psi_leaf_mpa: f64,
167        height_m: f64,
168    ) -> f64 {
169        let dz = height_m.max(1e-4);
170        let delta_psi_pa = (psi_leaf_mpa - psi_soil_mpa) * 1e6;
171        let rho_g = 1000.0 * 9.80665; // Pa / m
172        let gradient = (delta_psi_pa / dz) + rho_g;
173        -conductance_k * gradient
174    }
175}
176
177/// Mechanical structural fatigue and galvanic corrosion constitutive law.
178#[derive(Debug, Clone, Copy, PartialEq)]
179pub struct FatigueCorrosionLaw {
180    /// Fatigue strength coefficient $\sigma_f'$ (MPa).
181    pub fatigue_strength_coeff_mpa: f64,
182    /// Basquin fatigue exponent $b$ (typically $-0.05$ to $-0.15$).
183    pub basquin_exponent_b: f64,
184    /// Paris-Erdogan crack growth coefficient $C$ ($m \cdot \text{cycle}^{-1} \cdot (\text{MPa}\sqrt{m})^{-m}$).
185    pub paris_coefficient_c: f64,
186    /// Paris-Erdogan crack growth exponent $m$ (typically $2.0$ to $4.0$).
187    pub paris_exponent_m: f64,
188}
189
190impl FatigueCorrosionLaw {
191    /// Constructs a new fatigue and corrosion law instance.
192    pub const fn new(
193        fatigue_strength_coeff_mpa: f64,
194        basquin_exponent_b: f64,
195        paris_coefficient_c: f64,
196        paris_exponent_m: f64,
197    ) -> Self {
198        Self {
199            fatigue_strength_coeff_mpa,
200            basquin_exponent_b,
201            paris_coefficient_c,
202            paris_exponent_m,
203        }
204    }
205
206    /// Evaluates Basquin S-N high-cycle fatigue cycles to failure $N_f$.
207    ///
208    /// $$\sigma_a = \sigma_f' (2 N_f)^b \implies N_f = \frac{1}{2}\left(\frac{\sigma_a}{\sigma_f'}\right)^{1/b}$$
209    pub fn cycles_to_failure_basquin(&self, stress_amplitude_mpa: f64) -> f64 {
210        if stress_amplitude_mpa <= 0.0 {
211            return f64::INFINITY;
212        }
213        let ratio = stress_amplitude_mpa / self.fatigue_strength_coeff_mpa.max(1e-9);
214        let inv_b = 1.0 / self.basquin_exponent_b;
215        0.5 * ratio.powf(inv_b)
216    }
217
218    /// Evaluates Paris-Erdogan subcritical crack growth per cycle $\frac{da}{dN}$ (m/cycle).
219    ///
220    /// $$\frac{da}{dN} = C (\Delta K)^m$$
221    pub fn crack_growth_per_cycle(&self, delta_k_mpa_sqrt_m: f64) -> f64 {
222        if delta_k_mpa_sqrt_m <= 0.0 {
223            0.0
224        } else {
225            self.paris_coefficient_c * delta_k_mpa_sqrt_m.powf(self.paris_exponent_m)
226        }
227    }
228
229    /// Evaluates Faraday-Arrhenius galvanic corrosion mass loss rate (kg/s).
230    ///
231    /// $$\frac{dm}{dt} = \frac{j \cdot A \cdot M}{z F} \cdot \exp\left(-\frac{E_a}{R}\left(\frac{1}{T} - \frac{1}{T_0}\right)\right)$$
232    pub fn corrosion_mass_loss_rate_kg_s(
233        &self,
234        current_density_a_m2: f64,
235        area_m2: f64,
236        molar_mass_kg_mol: f64,
237        valence_z: f64,
238        temp_k: f64,
239    ) -> f64 {
240        const FARADAY_C_PER_MOL: f64 = 96485.33212;
241        const GAS_CONSTANT_R: f64 = 8.314462618;
242        const ACTIVATION_ENERGY_J_PER_MOL: f64 = 35000.0;
243        const T_REF_K: f64 = 298.15;
244
245        let current_a = current_density_a_m2.max(0.0) * area_m2.max(0.0);
246        let z = valence_z.max(1.0);
247        let faraday_rate = (current_a * molar_mass_kg_mol.max(0.0)) / (z * FARADAY_C_PER_MOL);
248
249        let t = temp_k.max(1.0);
250        let arrhenius =
251            (-(ACTIVATION_ENERGY_J_PER_MOL / GAS_CONSTANT_R) * (1.0 / t - 1.0 / T_REF_K)).exp();
252        faraday_rate * arrhenius
253    }
254}
255
256/// Physical energy domain of a port-Hamiltonian bond graph port.
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub enum PortDomain {
259    MechanicalTranslational,
260    MechanicalRotational,
261    Electrical,
262    Hydraulic,
263    Thermal,
264    Chemical,
265}
266
267/// Bond-graph energy-conjugated port ($e, f$) for port-Hamiltonian conservation.
268#[derive(Debug, Clone, Copy, PartialEq)]
269pub struct BondGraphPort {
270    pub domain: PortDomain,
271    pub effort: f64,
272    pub flow: f64,
273}
274
275impl BondGraphPort {
276    /// Constructs a new bond-graph energy port.
277    pub const fn new(domain: PortDomain, effort: f64, flow: f64) -> Self {
278        Self {
279            domain,
280            effort,
281            flow,
282        }
283    }
284
285    /// Evaluates the instantaneous energy power flow $P = e \cdot f$ (Watts).
286    #[inline]
287    pub fn instantaneous_power(&self) -> f64 {
288        self.effort * self.flow
289    }
290
291    /// Verifies Dirac structure junction power conservation: $\sum_k e_k f_k = 0$.
292    pub fn verify_dirac_junction_power_balance(
293        ports: &[BondGraphPort],
294        tolerance: f64,
295    ) -> Result<f64, f64> {
296        let net_power: f64 = ports.iter().map(|p| p.instantaneous_power()).sum();
297        if net_power.abs() <= tolerance.abs() {
298            Ok(net_power)
299        } else {
300            Err(net_power)
301        }
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308
309    #[test]
310    fn test_hill_muscle_facet_mechanics() {
311        let muscle = HillMuscleFacet::new(1000.0, 0.1, 0.2, 10.0, 0.0);
312
313        // Optimal fiber length at rest should give max active force
314        let f_opt = HillMuscleFacet::active_force_length(1.0);
315        assert!((f_opt - 1.0).abs() < 1e-6);
316
317        // Isometric active contraction at L0
318        let force_isometric = muscle.compute_tendon_force(1.0, 0.1, 0.0);
319        assert!((force_isometric - 1000.0).abs() < 1e-4);
320
321        // Concentric shortening reduces active force
322        let force_shortening = muscle.compute_tendon_force(1.0, 0.1, -0.5);
323        assert!(force_shortening < force_isometric);
324
325        // Eccentric lengthening increases force up to plateau
326        let force_eccentric = muscle.compute_tendon_force(1.0, 0.1, 0.5);
327        assert!(force_eccentric > force_isometric);
328    }
329
330    #[test]
331    fn test_allometric_branching_and_da_vinci() {
332        let law = AllometricBranchLaw::default();
333        let (r1, r2) = law.child_radii_from_split(0.10, 0.5);
334        let res = law.verify_da_vinci_conservation(0.10, &[r1, r2]);
335        assert!(res < 1e-9);
336
337        let phyll = AllometricBranchLaw::phyllotaxis_direction(5, 0.02);
338        assert!(phyll[0] != 0.0 || phyll[1] != 0.0);
339    }
340
341    #[test]
342    fn test_fatigue_and_corrosion() {
343        let law = FatigueCorrosionLaw::new(800.0, -0.10, 1e-11, 3.0);
344        let cycles = law.cycles_to_failure_basquin(400.0);
345        assert!(cycles > 1e2);
346
347        let crack_rate = law.crack_growth_per_cycle(25.0);
348        assert!(crack_rate > 0.0);
349
350        let loss_rate = law.corrosion_mass_loss_rate_kg_s(10.0, 0.05, 0.055845, 2.0, 298.15);
351        assert!(loss_rate > 0.0);
352    }
353
354    #[test]
355    fn test_bond_graph_dirac_junction() {
356        let p_in = BondGraphPort::new(PortDomain::Electrical, 100.0, 2.0); // +200 W
357        let p_mech = BondGraphPort::new(PortDomain::MechanicalTranslational, 50.0, -4.0); // -200 W
358        let ports = [p_in, p_mech];
359
360        let balance = BondGraphPort::verify_dirac_junction_power_balance(&ports, 1e-6);
361        assert!(balance.is_ok());
362    }
363}