Skip to main content

qualia_core_db/solvers/calculus/
mechanics.rs

1//! Hamiltonian mechanics primitives with invariant diagnostics.
2
3use super::analysis::{AnalysisError, Vector};
4
5/// Canonical Poisson bracket of two phase-space functions.
6pub fn canonical_poisson_bracket<const N: usize>(
7    df_dq: Vector<N>,
8    df_dp: Vector<N>,
9    dg_dq: Vector<N>,
10    dg_dp: Vector<N>,
11) -> Result<f64, AnalysisError> {
12    Ok(df_dq.dot(dg_dp)? - df_dp.dot(dg_dq)?)
13}
14
15#[repr(C)]
16#[derive(Debug, Clone, Copy, PartialEq)]
17pub struct PhaseState<const N: usize> {
18    pub q: Vector<N>,
19    pub p: Vector<N>,
20}
21
22/// One Stormer-Verlet symplectic step.
23pub fn stormer_verlet_step<const N: usize, F, G>(
24    state: &mut PhaseState<N>,
25    step: f64,
26    potential_gradient: F,
27    kinetic_gradient: G,
28) -> Result<(), AnalysisError>
29where
30    F: Fn(Vector<N>) -> Vector<N>,
31    G: Fn(Vector<N>) -> Vector<N>,
32{
33    if !step.is_finite() || step == 0.0 {
34        return Err(AnalysisError::InvalidDomain);
35    }
36    state.q.validate()?;
37    state.p.validate()?;
38    let half_force = potential_gradient(state.q).scale(-0.5 * step)?;
39    state.p = state.p.add(half_force);
40    state.q = state.q.add(kinetic_gradient(state.p).scale(step)?);
41    state.p = state.p.add(potential_gradient(state.q).scale(-0.5 * step)?);
42    state.q.validate()?;
43    state.p.validate()
44}
45
46#[repr(C)]
47#[derive(Debug, Clone, Copy, PartialEq)]
48pub struct InvariantDrift {
49    pub initial: f64,
50    pub final_value: f64,
51    pub absolute_drift: f64,
52    pub relative_drift: f64,
53}
54
55/// Relative drift of an invariant between `initial` and `final_value`.
56pub fn invariant_drift(initial: f64, final_value: f64) -> Result<InvariantDrift, AnalysisError> {
57    if !initial.is_finite() || !final_value.is_finite() {
58        return Err(AnalysisError::NonFinite);
59    }
60    let absolute_drift = (final_value - initial).abs();
61    Ok(InvariantDrift {
62        initial,
63        final_value,
64        absolute_drift,
65        relative_drift: absolute_drift / initial.abs().max(f64::MIN_POSITIVE),
66    })
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    fn oscillator_energy(state: PhaseState<1>) -> f64 {
74        0.5 * (state.q.data[0].powi(2) + state.p.data[0].powi(2))
75    }
76
77    #[test]
78    fn poisson_bracket_is_antisymmetric() {
79        let fq = Vector::new([1.0, 2.0]);
80        let fp = Vector::new([3.0, 4.0]);
81        let gq = Vector::new([-2.0, 1.0]);
82        let gp = Vector::new([0.5, 3.0]);
83        let fg = canonical_poisson_bracket(fq, fp, gq, gp).unwrap();
84        let gf = canonical_poisson_bracket(gq, gp, fq, fp).unwrap();
85        assert_eq!(fg, -gf);
86    }
87
88    #[test]
89    fn stormer_verlet_is_time_reversible_and_bounds_energy_drift() {
90        let initial = PhaseState {
91            q: Vector::new([1.0]),
92            p: Vector::new([0.0]),
93        };
94        let mut state = initial;
95        for _ in 0..10_000 {
96            stormer_verlet_step(&mut state, 0.01, |q| q, |p| p).unwrap();
97        }
98        let drift = invariant_drift(oscillator_energy(initial), oscillator_energy(state)).unwrap();
99        assert!(drift.absolute_drift < 2e-5);
100
101        for _ in 0..10_000 {
102            stormer_verlet_step(&mut state, -0.01, |q| q, |p| p).unwrap();
103        }
104        assert!(state.q.distance(initial.q).unwrap() < 1e-12);
105        assert!(state.p.distance(initial.p).unwrap() < 1e-12);
106    }
107}