1use crate::value::Value;
10use std::collections::BTreeMap;
11
12const C: f64 = 299_792_458.0;
14
15const C_KM_S: f64 = C / 1000.0;
17
18pub const MPC_IN_METERS: f64 = 3.085677581e22;
20
21const H0_KM_S_MPC: f64 = 67.4;
23
24fn h0_per_second() -> f64 {
26 H0_KM_S_MPC * 1000.0 / MPC_IN_METERS
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub enum Curvature {
32 Open,
33 Flat,
34 Closed,
35}
36
37impl Curvature {
38 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#[derive(Debug, Clone, Copy, PartialEq)]
50pub enum FlrwInterceptError {
51 InvalidBeta(f64),
53 InvalidCosmologicalEpoch { scale_factor: f64, hubble_param: f64 },
55 BeyondCosmologicalHorizon {
57 recession_velocity_km_s: f64,
58 max_interceptor_speed_km_s: f64,
59 hubble_horizon_mpc: f64,
60 },
61 NoInterceptSolution,
63}
64
65#[derive(Debug, Clone, PartialEq)]
67pub struct ComovingInterceptSolution {
68 pub unit_direction: [f64; 3],
70 pub intercept_comoving_pos_mpc: [f64; 3],
72 pub time_to_intercept_s: f64,
74 pub launch_scale_factor: f64,
76 pub arrival_scale_factor_est: f64,
78 pub hubble_recession_km_s: f64,
80 pub trajectory_assumption: &'static str,
82}
83
84#[derive(Debug, Clone, PartialEq)]
86pub struct FlrwMetric {
87 pub scale_factor: f64,
89 pub curvature: Curvature,
91 pub hubble_param: f64,
93}
94
95impl FlrwMetric {
96 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 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 pub fn physical_distance(&self, comoving_r: f64) -> f64 {
119 self.scale_factor * comoving_r
120 }
121
122 pub fn redshift(&self, a_emit: f64) -> f64 {
124 self.scale_factor / a_emit - 1.0
125 }
126
127 pub fn hubble_velocity(&self, distance_m: f64) -> f64 {
130 self.hubble_param * distance_m
131 }
132
133 pub fn redshift_to_distance(&self, z: f64) -> f64 {
136 C * z / self.hubble_param
137 }
138
139 pub fn distance_to_redshift(&self, distance_m: f64) -> f64 {
141 self.hubble_param * distance_m / C
142 }
143
144 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 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 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 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 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
306pub 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#[derive(Debug, Clone, PartialEq)]
322pub struct RedshiftObservation {
323 pub z: f64,
325 pub comoving_distance_mpc: f64,
327 pub physical_distance_mpc: f64,
329 pub recession_velocity_km_s: f64,
331}
332
333pub 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, recession_velocity_km_s: v_km_s,
345 }
346}
347
348#[derive(Debug, Clone, Copy, PartialEq)]
354pub struct FloatingOrigin {
355 pub origin_mpc: [f64; 3],
357}
358
359impl FloatingOrigin {
360 pub fn new(origin: [f64; 3]) -> Self {
362 Self { origin_mpc: origin }
363 }
364
365 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 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 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 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); 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 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 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}