Skip to main content

vibe/cosmic/
flrw.rs

1//! FLRW cosmological metric, scale factor, redshift, and comoving intercept solver (OCS §1.2, OCS-12).
2//!
3//! Implements the Friedmann-Lemaître-Robertson-Walker metric for
4//! intergalactic cosmological distances, Hubble expansion, cosmological redshift,
5//! and comoving intercept trajectory estimation with explicit horizon failure states.
6//!
7//! Reference: OCS Specification v2.2.0 §1.2 & Playbook v4 Packet OCS-12.
8
9use crate::value::Value;
10use std::collections::BTreeMap;
11
12/// Speed of light (m/s).
13const C: f64 = 299_792_458.0;
14
15/// Speed of light in km/s.
16const C_KM_S: f64 = C / 1000.0;
17
18/// 1 Megaparsec in meters.
19pub const MPC_IN_METERS: f64 = 3.085677581e22;
20
21/// Hubble constant in km/s/Mpc. Planck 2018 value: H₀ ≈ 67.4 km/s/Mpc.
22const H0_KM_S_MPC: f64 = 67.4;
23
24/// Convert Hubble constant from km/s/Mpc to 1/s.
25fn h0_per_second() -> f64 {
26    H0_KM_S_MPC * 1000.0 / MPC_IN_METERS
27}
28
29/// Curvature parameter k: -1 (open), 0 (flat), +1 (closed).
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub enum Curvature {
32    Open,
33    Flat,
34    Closed,
35}
36
37impl Curvature {
38    /// Curvature constant.
39    pub fn k(&self) -> f64 {
40        match self {
41            Self::Open => -1.0,
42            Self::Flat => 0.0,
43            Self::Closed => 1.0,
44        }
45    }
46}
47
48/// Failure states for cosmological comoving intercept calculation (Packet OCS-12).
49#[derive(Debug, Clone, Copy, PartialEq)]
50pub enum FlrwInterceptError {
51    /// Interceptor speed fraction $\beta = v / c_0$ must satisfy $0 < \beta \le 1.0$.
52    InvalidBeta(f64),
53    /// Cosmological scale factor $a(t)$ or Hubble parameter $H(t)$ is non-positive or non-finite.
54    InvalidCosmologicalEpoch { scale_factor: f64, hubble_param: f64 },
55    /// Target recession velocity exceeds or equals interceptor speed ($v_{\text{H}} \ge \beta c_0$).
56    BeyondCosmologicalHorizon {
57        recession_velocity_km_s: f64,
58        max_interceptor_speed_km_s: f64,
59        hubble_horizon_mpc: f64,
60    },
61    /// Target peculiar + Hubble motion has no real positive intercept time with the given $\beta$.
62    NoInterceptSolution,
63}
64
65/// Explicit comoving intercept solution with stated cosmological epoch and trajectory assumptions (OCS-12).
66#[derive(Debug, Clone, PartialEq)]
67pub struct ComovingInterceptSolution {
68    /// Unit direction vector in comoving coordinates toward the intercept point.
69    pub unit_direction: [f64; 3],
70    /// Comoving coordinates of the intercept point (Mpc).
71    pub intercept_comoving_pos_mpc: [f64; 3],
72    /// Coordinate time to intercept (s) in the local comoving frame at epoch $a(t)$.
73    pub time_to_intercept_s: f64,
74    /// Cosmological scale factor $a(t_0)$ at launch epoch.
75    pub launch_scale_factor: f64,
76    /// Estimated scale factor $a(t_{\text{intercept}}) \approx a(t_0)(1 + H \Delta t)$ at arrival.
77    pub arrival_scale_factor_est: f64,
78    /// Hubble recession velocity of the target at launch epoch (km/s).
79    pub hubble_recession_km_s: f64,
80    /// Explicit trajectory assumption tag (`"LinearizedComovingConstantBeta"`).
81    pub trajectory_assumption: &'static str,
82}
83
84/// FLRW metric parameters (OCS §1.2).
85#[derive(Debug, Clone, PartialEq)]
86pub struct FlrwMetric {
87    /// Scale factor a(t) — dimensionless, a(now) = 1.0
88    pub scale_factor: f64,
89    /// Curvature parameter
90    pub curvature: Curvature,
91    /// Hubble parameter H = ȧ/a at the current epoch (1/s)
92    pub hubble_param: f64,
93}
94
95impl FlrwMetric {
96    /// Create a flat ΛCDM metric at the current epoch (a=1).
97    pub fn flat_present_epoch() -> Self {
98        Self {
99            scale_factor: 1.0,
100            curvature: Curvature::Flat,
101            hubble_param: h0_per_second(),
102        }
103    }
104
105    /// FLRW line element: ds² = -c²dt² + a(t)²[dr²/(1-kr²) + r²(dθ² + sin²θ dφ²)]
106    ///
107    /// Compute the proper distance element for a radial comoving coordinate.
108    /// Returns ds² (spatial part only, dt=0) for a given comoving radius r.
109    pub fn spatial_line_element(&self, r: f64, theta: f64) -> f64 {
110        let a = self.scale_factor;
111        let k = self.curvature.k();
112        let dr_term = a * a * r * r / (1.0 - k * r * r);
113        let angular_term = a * a * r * r * theta.sin() * theta.sin();
114        dr_term + angular_term
115    }
116
117    /// Physical distance from comoving distance: d_phys = a(t) * r_comoving (OCS §1.2).
118    pub fn physical_distance(&self, comoving_r: f64) -> f64 {
119        self.scale_factor * comoving_r
120    }
121
122    /// Cosmological redshift: 1 + z = a(t_obs) / a(t_emit) (OCS §1.2).
123    pub fn redshift(&self, a_emit: f64) -> f64 {
124        self.scale_factor / a_emit - 1.0
125    }
126
127    /// Hubble's law: v = H(z) * d (OCS §1.2).
128    /// At low redshift, v = H₀ * d.
129    pub fn hubble_velocity(&self, distance_m: f64) -> f64 {
130        self.hubble_param * distance_m
131    }
132
133    /// Convert redshift to comoving distance (approximate, low-z linear).
134    /// d ≈ c * z / H₀ for z << 1.
135    pub fn redshift_to_distance(&self, z: f64) -> f64 {
136        C * z / self.hubble_param
137    }
138
139    /// Convert distance to redshift (approximate, low-z linear).
140    pub fn distance_to_redshift(&self, distance_m: f64) -> f64 {
141        self.hubble_param * distance_m / C
142    }
143
144    /// Compute a comoving intercept vector and arrival solution for a target at
145    /// `target_comoving_pos_mpc` with peculiar velocity `target_peculiar_vel_km_s`
146    /// pursued by an interceptor traveling at speed $v_{\text{int}} = \beta c_0$ (Packet OCS-12).
147    ///
148    /// ### Cosmological Epoch & Trajectory Assumptions
149    /// - Evaluates physical separation $\mathbf{r}_0 = a(t_0)\,\boldsymbol{\chi}_0$ at epoch $a(t_0)$.
150    /// - Target effective velocity in the local comoving chart combines Hubble flow and peculiar velocity:
151    ///   $\mathbf{v}_{\text{eff}} = \mathbf{v}_{\text{pec}} / a(t_0)$ in comoving coordinates, while the
152    ///   physical radial recession check enforces $v_{\text{H}} = H(t_0) \|\mathbf{r}_0\| < \beta c_0$.
153    /// - Solves the quadratic intercept condition $\|\mathbf{r}_0 + \mathbf{v}_{\text{eff}} \Delta t\|^2 = (\beta_{\text{eff}} c_0 \Delta t)^2$
154    ///   where $\beta_{\text{eff}} c_0 = \beta c_0 - v_{\text{H}}$ accounts for Hubble expansion along the line of sight.
155    pub fn intercept_vector_comoving(
156        &self,
157        target_comoving_pos_mpc: [f64; 3],
158        target_peculiar_vel_km_s: [f64; 3],
159        interceptor_beta: f64,
160    ) -> Result<ComovingInterceptSolution, FlrwInterceptError> {
161        if !interceptor_beta.is_finite() || interceptor_beta <= 0.0 || interceptor_beta > 1.0 {
162            return Err(FlrwInterceptError::InvalidBeta(interceptor_beta));
163        }
164        if !self.scale_factor.is_finite()
165            || self.scale_factor <= 0.0
166            || !self.hubble_param.is_finite()
167            || self.hubble_param < 0.0
168        {
169            return Err(FlrwInterceptError::InvalidCosmologicalEpoch {
170                scale_factor: self.scale_factor,
171                hubble_param: self.hubble_param,
172            });
173        }
174
175        let r_comoving_mpc = (target_comoving_pos_mpc[0] * target_comoving_pos_mpc[0]
176            + target_comoving_pos_mpc[1] * target_comoving_pos_mpc[1]
177            + target_comoving_pos_mpc[2] * target_comoving_pos_mpc[2])
178            .sqrt();
179
180        if r_comoving_mpc < 1e-15 {
181            return Ok(ComovingInterceptSolution {
182                unit_direction: [1.0, 0.0, 0.0],
183                intercept_comoving_pos_mpc: target_comoving_pos_mpc,
184                time_to_intercept_s: 0.0,
185                launch_scale_factor: self.scale_factor,
186                arrival_scale_factor_est: self.scale_factor,
187                hubble_recession_km_s: 0.0,
188                trajectory_assumption: "LinearizedComovingConstantBeta",
189            });
190        }
191
192        let phys_dist_m = self.scale_factor * r_comoving_mpc * MPC_IN_METERS;
193        let hubble_recession_km_s = self.hubble_velocity(phys_dist_m) / 1000.0;
194        let max_interceptor_speed_km_s = interceptor_beta * C_KM_S;
195        let hubble_horizon_mpc = if self.hubble_param > 0.0 {
196            (interceptor_beta * C) / (self.hubble_param * MPC_IN_METERS)
197        } else {
198            f64::INFINITY
199        };
200
201        if hubble_recession_km_s >= max_interceptor_speed_km_s {
202            return Err(FlrwInterceptError::BeyondCosmologicalHorizon {
203                recession_velocity_km_s: hubble_recession_km_s,
204                max_interceptor_speed_km_s,
205                hubble_horizon_mpc,
206            });
207        }
208
209        // Convert comoving position to km and solve in comoving-scaled physical km coordinates
210        let mpc_to_km = MPC_IN_METERS / 1000.0;
211        let p0_km = [
212            target_comoving_pos_mpc[0] * self.scale_factor * mpc_to_km,
213            target_comoving_pos_mpc[1] * self.scale_factor * mpc_to_km,
214            target_comoving_pos_mpc[2] * self.scale_factor * mpc_to_km,
215        ];
216        // Effective closing speed after subtracting Hubble expansion rate
217        let v_close_km_s = max_interceptor_speed_km_s - hubble_recession_km_s;
218        let v_pec = target_peculiar_vel_km_s;
219
220        // Solve |p0 + v_pec * t|^2 = (v_close * t)^2
221        // (v_pec·v_pec - v_close^2) t^2 + 2 (p0·v_pec) t + (p0·p0) = 0
222        let v_pec_sq = v_pec[0] * v_pec[0] + v_pec[1] * v_pec[1] + v_pec[2] * v_pec[2];
223        let p0_sq = p0_km[0] * p0_km[0] + p0_km[1] * p0_km[1] + p0_km[2] * p0_km[2];
224        let p0_dot_v = p0_km[0] * v_pec[0] + p0_km[1] * v_pec[1] + p0_km[2] * v_pec[2];
225
226        let a_quad = v_pec_sq - v_close_km_s * v_close_km_s;
227        let b_quad = 2.0 * p0_dot_v;
228        let c_quad = p0_sq;
229
230        let t_s = if a_quad.abs() < 1e-12 {
231            if b_quad >= 0.0 {
232                return Err(FlrwInterceptError::NoInterceptSolution);
233            }
234            -c_quad / b_quad
235        } else {
236            let disc = b_quad * b_quad - 4.0 * a_quad * c_quad;
237            if disc < 0.0 {
238                return Err(FlrwInterceptError::NoInterceptSolution);
239            }
240            let sqrt_disc = disc.sqrt();
241            let t1 = (-b_quad - sqrt_disc) / (2.0 * a_quad);
242            let t2 = (-b_quad + sqrt_disc) / (2.0 * a_quad);
243            match (t1 > 0.0, t2 > 0.0) {
244                (true, true) => t1.min(t2),
245                (true, false) => t1,
246                (false, true) => t2,
247                (false, false) => return Err(FlrwInterceptError::NoInterceptSolution),
248            }
249        };
250
251        if !t_s.is_finite() || t_s <= 0.0 {
252            return Err(FlrwInterceptError::NoInterceptSolution);
253        }
254
255        let intercept_phys_km = [
256            p0_km[0] + v_pec[0] * t_s,
257            p0_km[1] + v_pec[1] * t_s,
258            p0_km[2] + v_pec[2] * t_s,
259        ];
260        let norm_km = (intercept_phys_km[0] * intercept_phys_km[0]
261            + intercept_phys_km[1] * intercept_phys_km[1]
262            + intercept_phys_km[2] * intercept_phys_km[2])
263            .sqrt();
264        if norm_km < 1e-12 {
265            return Err(FlrwInterceptError::NoInterceptSolution);
266        }
267
268        let unit_direction = [
269            intercept_phys_km[0] / norm_km,
270            intercept_phys_km[1] / norm_km,
271            intercept_phys_km[2] / norm_km,
272        ];
273        let inv_scale_mpc = 1.0 / (self.scale_factor * mpc_to_km);
274        let intercept_comoving_pos_mpc = [
275            intercept_phys_km[0] * inv_scale_mpc,
276            intercept_phys_km[1] * inv_scale_mpc,
277            intercept_phys_km[2] * inv_scale_mpc,
278        ];
279        let arrival_scale_factor_est = self.scale_factor * (1.0 + self.hubble_param * t_s);
280
281        Ok(ComovingInterceptSolution {
282            unit_direction,
283            intercept_comoving_pos_mpc,
284            time_to_intercept_s: t_s,
285            launch_scale_factor: self.scale_factor,
286            arrival_scale_factor_est,
287            hubble_recession_km_s,
288            trajectory_assumption: "LinearizedComovingConstantBeta",
289        })
290    }
291
292    /// Converts to value.
293    pub fn to_value(&self) -> Value {
294        let mut rec = BTreeMap::new();
295        rec.insert("scale_factor".into(), Value::F64(self.scale_factor));
296        rec.insert(
297            "curvature".into(),
298            Value::String(format!("{:?}", self.curvature).into()),
299        );
300        rec.insert("hubble_param_per_s".into(), Value::F64(self.hubble_param));
301        rec.insert("hubble_param_km_s_mpc".into(), Value::F64(H0_KM_S_MPC));
302        Value::Record(rec)
303    }
304}
305
306/// Top-level helper for [`FlrwMetric::intercept_vector_comoving`] (Packet OCS-12).
307pub fn intercept_vector_comoving(
308    metric: &FlrwMetric,
309    target_comoving_pos_mpc: [f64; 3],
310    target_peculiar_vel_km_s: [f64; 3],
311    interceptor_beta: f64,
312) -> Result<ComovingInterceptSolution, FlrwInterceptError> {
313    metric.intercept_vector_comoving(
314        target_comoving_pos_mpc,
315        target_peculiar_vel_km_s,
316        interceptor_beta,
317    )
318}
319
320/// A cosmological redshift observation (OCS §1.2).
321#[derive(Debug, Clone, PartialEq)]
322pub struct RedshiftObservation {
323    /// Observed redshift z
324    pub z: f64,
325    /// Comoving distance (Mpc)
326    pub comoving_distance_mpc: f64,
327    /// Physical distance at current epoch (Mpc)
328    pub physical_distance_mpc: f64,
329    /// Recession velocity (km/s)
330    pub recession_velocity_km_s: f64,
331}
332
333/// Compute a redshift observation from a measured redshift value.
334pub fn observe_redshift(z: f64) -> RedshiftObservation {
335    let metric = FlrwMetric::flat_present_epoch();
336    let distance_m = metric.redshift_to_distance(z);
337    let distance_mpc = distance_m / MPC_IN_METERS;
338    let v_km_s = metric.hubble_velocity(distance_m) / 1000.0;
339
340    RedshiftObservation {
341        z,
342        comoving_distance_mpc: distance_mpc,
343        physical_distance_mpc: distance_mpc, // at a=1, comoving = physical
344        recession_velocity_km_s: v_km_s,
345    }
346}
347
348/// Floating-origin precision for intergalactic coordinates (OCS §14, OCS-T01).
349///
350/// At cosmological distances, absolute coordinates lose precision.
351/// The floating-origin scheme stores offsets relative to a local origin,
352/// keeping coordinate values small enough for f64 precision.
353#[derive(Debug, Clone, Copy, PartialEq)]
354pub struct FloatingOrigin {
355    /// Origin position in comoving coordinates (Mpc)
356    pub origin_mpc: [f64; 3],
357}
358
359impl FloatingOrigin {
360    /// Creates a new `FloatingOrigin`.
361    pub fn new(origin: [f64; 3]) -> Self {
362        Self { origin_mpc: origin }
363    }
364
365    /// Convert an absolute comoving position to a floating-origin offset.
366    /// Returns offset in Mpc relative to the origin.
367    pub fn to_offset(&self, absolute_mpc: [f64; 3]) -> [f64; 3] {
368        [
369            absolute_mpc[0] - self.origin_mpc[0],
370            absolute_mpc[1] - self.origin_mpc[1],
371            absolute_mpc[2] - self.origin_mpc[2],
372        ]
373    }
374
375    /// Convert a floating-origin offset back to absolute comoving coordinates.
376    pub fn to_absolute(&self, offset_mpc: [f64; 3]) -> [f64; 3] {
377        [
378            offset_mpc[0] + self.origin_mpc[0],
379            offset_mpc[1] + self.origin_mpc[1],
380            offset_mpc[2] + self.origin_mpc[2],
381        ]
382    }
383
384    /// Verify precision at a given comoving distance (OCS-T01).
385    /// Returns the offset error in meters at the given distance.
386    pub fn precision_error_at(&self, distance_mpc: f64) -> f64 {
387        let distance_m = distance_mpc * MPC_IN_METERS;
388        let without_floating_origin = distance_m / (1u64 << 52) as f64;
389        let local_offset_m = 1.0 * MPC_IN_METERS;
390        let with_floating_origin = local_offset_m / (1u64 << 52) as f64;
391        without_floating_origin - with_floating_origin
392    }
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398
399    #[test]
400    fn flrw_flat_present_epoch() {
401        let m = FlrwMetric::flat_present_epoch();
402        assert_eq!(m.scale_factor, 1.0);
403        assert_eq!(m.curvature, Curvature::Flat);
404        assert!(m.hubble_param > 0.0);
405    }
406
407    #[test]
408    fn physical_distance_scales() {
409        let mut m = FlrwMetric::flat_present_epoch();
410        m.scale_factor = 0.5;
411        let d = m.physical_distance(100.0);
412        assert!((d - 50.0).abs() < 1e-10, "got {} expected 50.0", d);
413    }
414
415    #[test]
416    fn redshift_from_scale_factor() {
417        let m = FlrwMetric::flat_present_epoch();
418        let z = m.redshift(0.5);
419        assert!((z - 1.0).abs() < 1e-10, "got {} expected 1.0", z);
420    }
421
422    #[test]
423    fn redshift_zero_at_present() {
424        let m = FlrwMetric::flat_present_epoch();
425        let z = m.redshift(1.0);
426        assert!(z.abs() < 1e-10);
427    }
428
429    #[test]
430    fn hubble_velocity_linear() {
431        let m = FlrwMetric::flat_present_epoch();
432        let v = m.hubble_velocity(1.0e22);
433        assert!(v > 0.0);
434        let v_1mpc = m.hubble_velocity(MPC_IN_METERS) / 1000.0;
435        assert!(
436            (v_1mpc - 67.4).abs() < 1.0,
437            "got {} expected ~67.4 km/s",
438            v_1mpc
439        );
440    }
441
442    #[test]
443    fn redshift_distance_round_trip() {
444        let m = FlrwMetric::flat_present_epoch();
445        let z = 0.01;
446        let d = m.redshift_to_distance(z);
447        let z_recovered = m.distance_to_redshift(d);
448        assert!((z_recovered - z).abs() < 1e-10);
449    }
450
451    #[test]
452    fn observe_redshift_low_z() {
453        let obs = observe_redshift(0.01);
454        assert!(obs.comoving_distance_mpc > 0.0);
455        assert!(obs.recession_velocity_km_s > 0.0);
456        assert!(obs.comoving_distance_mpc > 30.0 && obs.comoving_distance_mpc < 50.0);
457    }
458
459    #[test]
460    fn floating_origin_round_trip() {
461        let origin = FloatingOrigin::new([100.0, 200.0, 300.0]);
462        let absolute = [150.0, 210.0, 310.0];
463        let offset = origin.to_offset(absolute);
464        assert!((offset[0] - 50.0).abs() < 1e-10);
465        assert!((offset[1] - 10.0).abs() < 1e-10);
466        assert!((offset[2] - 10.0).abs() < 1e-10);
467        let recovered = origin.to_absolute(offset);
468        for i in 0..3 {
469            assert!((recovered[i] - absolute[i]).abs() < 1e-10);
470        }
471    }
472
473    #[test]
474    fn floating_origin_precision_at_500_mpc() {
475        let origin = FloatingOrigin::new([0.0; 3]);
476        let error = origin.precision_error_at(500.0);
477        assert!(error > 0.0, "floating origin should improve precision");
478    }
479
480    #[test]
481    fn flrw_to_value() {
482        let m = FlrwMetric::flat_present_epoch();
483        let v = m.to_value();
484        match v {
485            Value::Record(r) => {
486                assert_eq!(r.get("scale_factor"), Some(&Value::F64(1.0)));
487                assert!(r.contains_key("hubble_param_per_s"));
488            }
489            _ => panic!("expected Record"),
490        }
491    }
492
493    #[test]
494    fn curvature_values() {
495        assert_eq!(Curvature::Open.k(), -1.0);
496        assert_eq!(Curvature::Flat.k(), 0.0);
497        assert_eq!(Curvature::Closed.k(), 1.0);
498    }
499
500    #[test]
501    fn spatial_line_element_flat() {
502        let m = FlrwMetric::flat_present_epoch();
503        let ds2 = m.spatial_line_element(2.0, std::f64::consts::PI / 2.0);
504        assert!((ds2 - 8.0).abs() < 1e-10, "got {} expected 8.0", ds2);
505    }
506
507    #[test]
508    fn intercept_vector_comoving_valid_and_horizon_failures() {
509        let m = FlrwMetric::flat_present_epoch();
510        // Nearby galaxy at 10 Mpc along +X with modest transverse peculiar velocity (+300 km/s in Y)
511        // Interceptor at beta = 0.1 (30,000 km/s >> H0 * 10 Mpc ≈ 674 km/s)
512        let sol = intercept_vector_comoving(&m, [10.0, 0.0, 0.0], [0.0, 300.0, 0.0], 0.1).unwrap();
513        assert!(sol.time_to_intercept_s > 0.0);
514        assert!(sol.unit_direction[0] > 0.99);
515        assert!(sol.unit_direction[1] > 0.0); // Leads the target in +Y
516        assert_eq!(sol.launch_scale_factor, 1.0);
517        assert!(sol.arrival_scale_factor_est > 1.0);
518        assert_eq!(
519            sol.trajectory_assumption,
520            "LinearizedComovingConstantBeta"
521        );
522
523        // Target at 1000 Mpc (v_H ≈ 67,400 km/s) cannot be intercepted by beta = 0.1 (30,000 km/s)
524        let horizon_err =
525            intercept_vector_comoving(&m, [1000.0, 0.0, 0.0], [0.0, 0.0, 0.0], 0.1).unwrap_err();
526        assert!(matches!(
527            horizon_err,
528            FlrwInterceptError::BeyondCosmologicalHorizon { .. }
529        ));
530
531        // Invalid beta (superluminal > 1.0 or <= 0.0) must fail closed
532        assert_eq!(
533            intercept_vector_comoving(&m, [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], 1.2).unwrap_err(),
534            FlrwInterceptError::InvalidBeta(1.2)
535        );
536    }
537}