Skip to main content

aria_engine_core/
state.rs

1use num_complex::Complex64;
2use serde::{Deserialize, Serialize};
3
4use crate::graph::Graph;
5
6/// Full Aria state — the discrete Spec variables.
7///
8/// Observable core: ⟨ψ, z, G, t⟩.
9/// prev_res is auxiliary history for Inv2 only (TLA prevRes).
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct State {
12    /// Optical field amplitudes ψ ∈ C^N — 𝔸1
13    pub psi: Vec<Complex64>,
14    /// JEPA latent z ∈ Z — 𝔸2
15    pub z: Vec<f64>,
16    /// Experience/thought graph G — 𝔸3
17    pub g: Graph,
18    /// Discrete step counter t ∈ N
19    pub t: u64,
20    /// Auxiliary: previous residual for Inv2
21    pub prev_res: f64,
22    /// Initial field energy ‖ψ₀‖₂ — cached for Inv1
23    pub energy_0: f64,
24}
25
26impl State {
27    /// Compute the current field energy ‖ψ‖₂.
28    pub fn energy(&self) -> f64 {
29        field_energy(&self.psi)
30    }
31
32    /// Compute the current JEPA residual:
33    /// Res(ψ, z, t) = d(z, P(I(ψ), a_t))
34    ///
35    /// This is computed by the Predictor backend; see engine for usage.
36    /// Here we provide the distance function used in Inv2 comparison.
37    pub fn residual(&self, predicted_z: &[f64]) -> f64 {
38        euclidean_distance(&self.z, predicted_z)
39    }
40}
41
42/// Euclidean distance in Z (compensated summation — see [`field_energy`]).
43pub fn euclidean_distance(a: &[f64], b: &[f64]) -> f64 {
44    compensated_sqrt(a.iter().zip(b.iter()).map(|(x, y)| (x - y) * (x - y)))
45}
46
47/// Compute ‖ψ‖₂ energy of a complex vector.
48///
49/// Uses Neumaier compensated summation. A plain `sum()` drifts by O(N·ε) per
50/// evaluation, and that drift lands directly on Inv1's equality check; at
51/// N = 1024 and long runs it eventually exceeds the 1e-10 tolerance even
52/// though the underlying unitary evolution is fine. Compensation keeps the
53/// error at O(ε) independent of N.
54pub fn field_energy(psi: &[Complex64]) -> f64 {
55    compensated_sqrt(psi.iter().map(num_complex::Complex::norm_sqr))
56}
57
58/// √(Σ terms) with Neumaier compensation.
59fn compensated_sqrt<I: Iterator<Item = f64>>(terms: I) -> f64 {
60    let mut sum = 0.0f64;
61    let mut c = 0.0f64; // running compensation
62    for x in terms {
63        let t = sum + x;
64        if sum.abs() >= x.abs() {
65            c += (sum - t) + x;
66        } else {
67            c += (x - t) + sum;
68        }
69        sum = t;
70    }
71    (sum + c).sqrt()
72}