1use crate::value::Value;
7use std::collections::BTreeMap;
8
9pub const C0_VACUUM_M_S: f64 = 299_792_458.0;
13
14const C: f64 = C0_VACUUM_M_S;
16
17pub const PULSAR_DISPERSION_CONSTANT_MS_GHZ2: f64 = 4.148808;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub enum CelestialBodyClass {
23 TerrestrialPlanet,
24 GasGiant,
25 IceGiant,
26 DwarfPlanet,
27 NaturalSatellite,
28 MinorBodyIrregular,
29 Star,
30 CompactRelativistic,
31 BlackHole,
32 Megastructure,
33 FictionalWorld,
34}
35
36impl CelestialBodyClass {
37 pub fn as_str(&self) -> &'static str {
39 match self {
40 Self::TerrestrialPlanet => "TerrestrialPlanet",
41 Self::GasGiant => "GasGiant",
42 Self::IceGiant => "IceGiant",
43 Self::DwarfPlanet => "DwarfPlanet",
44 Self::NaturalSatellite => "NaturalSatellite",
45 Self::MinorBodyIrregular => "MinorBodyIrregular",
46 Self::Star => "Star",
47 Self::CompactRelativistic => "CompactRelativistic",
48 Self::BlackHole => "BlackHole",
49 Self::Megastructure => "Megastructure",
50 Self::FictionalWorld => "FictionalWorld",
51 }
52 }
53
54 pub fn from_str(s: &str) -> Option<Self> {
56 match s {
57 "TerrestrialPlanet" => Some(Self::TerrestrialPlanet),
58 "GasGiant" => Some(Self::GasGiant),
59 "IceGiant" => Some(Self::IceGiant),
60 "DwarfPlanet" => Some(Self::DwarfPlanet),
61 "NaturalSatellite" => Some(Self::NaturalSatellite),
62 "MinorBodyIrregular" => Some(Self::MinorBodyIrregular),
63 "Star" => Some(Self::Star),
64 "CompactRelativistic" => Some(Self::CompactRelativistic),
65 "BlackHole" => Some(Self::BlackHole),
66 "Megastructure" => Some(Self::Megastructure),
67 "FictionalWorld" => Some(Self::FictionalWorld),
68 _ => None,
69 }
70 }
71
72 pub fn has_solid_surface(&self) -> bool {
74 matches!(
75 self,
76 Self::TerrestrialPlanet
77 | Self::DwarfPlanet
78 | Self::NaturalSatellite
79 | Self::MinorBodyIrregular
80 | Self::Megastructure
81 | Self::FictionalWorld
82 )
83 }
84
85 pub fn is_relativistic(&self) -> bool {
87 matches!(self, Self::CompactRelativistic | Self::BlackHole)
88 }
89}
90
91#[derive(Debug, Clone, PartialEq)]
93pub enum ReferenceSurface {
94 Biaxial { a: f64, c: f64 },
96 Triaxial { a: f64, b: f64, c: f64 },
98 Equipotential { name: String },
100 Mesh { name: String },
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
106pub enum CausalConeRelation {
107 PastCausalEnvelope,
109 FutureCausalEnvelope,
111 DispersedMediumArrival,
113 SpacelikeElsewhere,
115}
116
117#[allow(non_upper_case_globals)]
118impl CausalConeRelation {
119 pub const PastLightCone: Self = Self::PastCausalEnvelope;
121 pub const FutureLightCone: Self = Self::FutureCausalEnvelope;
123}
124
125#[derive(Debug, Clone, Copy, PartialEq)]
127pub struct EmfMediumSpec {
128 pub group_refractive_index: f64,
130 pub phase_refractive_index: f64,
132 pub carrier_freq_hz: f64,
134 pub dispersion_measure_pc_cm3: f64,
136}
137
138impl EmfMediumSpec {
139 pub const fn vacuum() -> Self {
141 Self {
142 group_refractive_index: 1.0,
143 phase_refractive_index: 1.0,
144 carrier_freq_hz: 0.0,
145 dispersion_measure_pc_cm3: 0.0,
146 }
147 }
148
149 pub fn cold_plasma(
154 carrier_freq_hz: f64,
155 plasma_freq_hz: f64,
156 dispersion_measure_pc_cm3: f64,
157 ) -> Result<Self, &'static str> {
158 if carrier_freq_hz <= 0.0 || plasma_freq_hz < 0.0 || carrier_freq_hz <= plasma_freq_hz {
159 return Err("carrier_freq_hz must exceed plasma_freq_hz >= 0");
160 }
161 let ratio_sq = (plasma_freq_hz / carrier_freq_hz) * (plasma_freq_hz / carrier_freq_hz);
162 let n_p = (1.0 - ratio_sq).sqrt();
163 let n_g = 1.0 / n_p;
164 Ok(Self {
165 group_refractive_index: n_g,
166 phase_refractive_index: n_p,
167 carrier_freq_hz,
168 dispersion_measure_pc_cm3,
169 })
170 }
171}
172
173#[derive(Debug, Clone, Copy, PartialEq)]
175pub struct MediumPropagationEstimate {
176 pub euclidean_distance_m: f64,
178 pub vacuum_light_time_s: f64,
180 pub shapiro_delay_s: f64,
182 pub medium_group_delay_s: f64,
184 pub causal_envelope_time_s: f64,
186 pub total_signal_arrival_time_s: f64,
188 pub group_velocity_m_s: f64,
190 pub phase_velocity_m_s: f64,
192 pub spacetime_interval_m2: f64,
194}
195
196#[derive(Debug, Clone, PartialEq)]
198pub struct GravitationalField {
199 pub mu: f64,
201 pub r_ref: f64,
203 pub jn: Vec<f64>,
205 pub schwarzschild_r: f64,
207 pub kerr_spin_a: f64,
209}
210
211impl GravitationalField {
212 pub fn newtonian(mu: f64, r_ref: f64) -> Self {
214 Self {
215 mu,
216 r_ref,
217 jn: Vec::new(),
218 schwarzschild_r: 0.0,
219 kerr_spin_a: 0.0,
220 }
221 }
222
223 pub fn kerr_horizon_r(&self) -> f64 {
226 if self.schwarzschild_r == 0.0 {
227 return 0.0;
228 }
229 let half_rs = self.schwarzschild_r / 2.0;
230 let disc = half_rs * half_rs - self.kerr_spin_a * self.kerr_spin_a;
231 if disc < 0.0 {
232 return 0.0; }
234 half_rs + disc.sqrt()
235 }
236
237 pub fn kerr_ergosphere_r(&self, theta: f64) -> f64 {
240 if self.schwarzschild_r == 0.0 {
241 return 0.0;
242 }
243 let half_rs = self.schwarzschild_r / 2.0;
244 let cos_theta = theta.cos();
245 let disc = half_rs * half_rs - self.kerr_spin_a * self.kerr_spin_a * cos_theta * cos_theta;
246 if disc < 0.0 {
247 return 0.0;
248 }
249 half_rs + disc.sqrt()
250 }
251
252 pub fn frame_dragging(&self, r: f64) -> f64 {
257 if self.schwarzschild_r == 0.0 || self.kerr_spin_a == 0.0 || r <= 0.0 {
258 return 0.0;
259 }
260 2.0 * self.mu * self.kerr_spin_a / (C0_VACUUM_M_S * r * r * r)
261 }
262
263 pub fn shapiro_delay_s(&self, r1_m: [f64; 3], r2_m: [f64; 3]) -> f64 {
268 if self.mu <= 0.0 {
269 return 0.0;
270 }
271 let r1 = (r1_m[0] * r1_m[0] + r1_m[1] * r1_m[1] + r1_m[2] * r1_m[2]).sqrt();
272 let r2 = (r2_m[0] * r2_m[0] + r2_m[1] * r2_m[1] + r2_m[2] * r2_m[2]).sqrt();
273 let dx = r2_m[0] - r1_m[0];
274 let dy = r2_m[1] - r1_m[1];
275 let dz = r2_m[2] - r1_m[2];
276 let big_r = (dx * dx + dy * dy + dz * dz).sqrt();
277 let denom = (r1 + r2 - big_r).max(1e-9);
278 let numer = (r1 + r2 + big_r).max(denom);
279 let c3 = C0_VACUUM_M_S * C0_VACUUM_M_S * C0_VACUUM_M_S;
280 (2.0 * self.mu / c3) * (numer / denom).ln()
281 }
282
283 pub fn emf_manifold_causal_interval_s(
292 &self,
293 r1_m: [f64; 3],
294 r2_m: [f64; 3],
295 coord_dt_s: f64,
296 medium: &EmfMediumSpec,
297 ) -> Result<(CausalConeRelation, MediumPropagationEstimate), &'static str> {
298 if medium.group_refractive_index < 1.0 || !medium.group_refractive_index.is_finite() {
299 return Err("Superluminal group velocity forbidden: group_refractive_index must be >= 1.0");
300 }
301 if medium.phase_refractive_index <= 0.0 || !medium.phase_refractive_index.is_finite() {
302 return Err("phase_refractive_index must be positive and finite");
303 }
304
305 let dx = r2_m[0] - r1_m[0];
306 let dy = r2_m[1] - r1_m[1];
307 let dz = r2_m[2] - r1_m[2];
308 let dist_m = (dx * dx + dy * dy + dz * dz).sqrt();
309
310 let vacuum_light_time_s = dist_m / C0_VACUUM_M_S;
311 let shapiro_s = self.shapiro_delay_s(r1_m, r2_m);
312 let causal_envelope_time_s = vacuum_light_time_s + shapiro_s;
313
314 let refractive_delay_s = vacuum_light_time_s * (medium.group_refractive_index - 1.0);
315 let dm_delay_s = if medium.dispersion_measure_pc_cm3 > 0.0 && medium.carrier_freq_hz > 0.0 {
316 pulsar_dispersion_delay_s(medium.dispersion_measure_pc_cm3, medium.carrier_freq_hz)?
317 } else {
318 0.0
319 };
320 let medium_group_delay_s = refractive_delay_s + dm_delay_s;
321 let total_signal_arrival_time_s = causal_envelope_time_s + medium_group_delay_s;
322
323 let group_velocity_m_s = C0_VACUUM_M_S / medium.group_refractive_index;
324 let phase_velocity_m_s = C0_VACUUM_M_S / medium.phase_refractive_index;
325
326 let abs_dt = coord_dt_s.abs();
327 let eff_vacuum_dt = (abs_dt - shapiro_s).max(0.0);
328 let spacetime_interval_m2 =
329 -(C0_VACUUM_M_S * eff_vacuum_dt) * (C0_VACUUM_M_S * eff_vacuum_dt) + dist_m * dist_m;
330
331 let relation = if abs_dt + 1e-12 < causal_envelope_time_s {
332 CausalConeRelation::SpacelikeElsewhere
333 } else if coord_dt_s < 0.0 {
334 CausalConeRelation::PastCausalEnvelope
335 } else if medium_group_delay_s > 0.0 && abs_dt + 1e-12 >= total_signal_arrival_time_s {
336 CausalConeRelation::DispersedMediumArrival
337 } else {
338 CausalConeRelation::FutureCausalEnvelope
339 };
340
341 Ok((
342 relation,
343 MediumPropagationEstimate {
344 euclidean_distance_m: dist_m,
345 vacuum_light_time_s,
346 shapiro_delay_s: shapiro_s,
347 medium_group_delay_s,
348 causal_envelope_time_s,
349 total_signal_arrival_time_s,
350 group_velocity_m_s,
351 phase_velocity_m_s,
352 spacetime_interval_m2,
353 },
354 ))
355 }
356}
357
358pub fn emf_manifold_causal_interval_s(
360 field: &GravitationalField,
361 r1_m: [f64; 3],
362 r2_m: [f64; 3],
363 coord_dt_s: f64,
364 medium: &EmfMediumSpec,
365) -> Result<(CausalConeRelation, MediumPropagationEstimate), &'static str> {
366 field.emf_manifold_causal_interval_s(r1_m, r2_m, coord_dt_s, medium)
367}
368
369#[derive(Debug, Clone, Copy, PartialEq)]
371pub struct PulsarAnchor {
372 pub id_hash: u64,
374 pub direction_unit: [f64; 3],
376 pub period_s: f64,
378 pub period_derivative: f64,
380 pub epoch_t0_s: f64,
382 pub carrier_freq_hz: f64,
384 pub dispersion_measure_pc_cm3: f64,
386}
387
388impl PulsarAnchor {
389 pub fn x_ray(
391 id_hash: u64,
392 direction_unit: [f64; 3],
393 period_s: f64,
394 period_derivative: f64,
395 epoch_t0_s: f64,
396 ) -> Self {
397 Self {
398 id_hash,
399 direction_unit,
400 period_s,
401 period_derivative,
402 epoch_t0_s,
403 carrier_freq_hz: 0.0,
404 dispersion_measure_pc_cm3: 0.0,
405 }
406 }
407
408 pub fn dispersion_delay_s(&self) -> Result<f64, &'static str> {
410 if self.dispersion_measure_pc_cm3 <= 0.0 || self.carrier_freq_hz <= 0.0 {
411 return Ok(0.0);
412 }
413 pulsar_dispersion_delay_s(self.dispersion_measure_pc_cm3, self.carrier_freq_hz)
414 }
415}
416
417pub fn pulsar_dispersion_delay_s(dm_pc_cm3: f64, freq_hz: f64) -> Result<f64, &'static str> {
421 if dm_pc_cm3 < 0.0 || !dm_pc_cm3.is_finite() {
422 return Err("dispersion_measure_pc_cm3 must be non-negative and finite");
423 }
424 if freq_hz <= 0.0 || !freq_hz.is_finite() {
425 return Err("carrier frequency freq_hz must be positive and finite");
426 }
427 let freq_ghz = freq_hz * 1.0e-9;
428 Ok((PULSAR_DISPERSION_CONSTANT_MS_GHZ2 * 1.0e-3) * dm_pc_cm3 / (freq_ghz * freq_ghz))
429}
430
431pub fn dual_band_dedisperse_delay_s(
435 dm_pc_cm3: f64,
436 freq_1_hz: f64,
437 freq_2_hz: f64,
438) -> Result<f64, &'static str> {
439 let dt1 = pulsar_dispersion_delay_s(dm_pc_cm3, freq_1_hz)?;
440 let dt2 = pulsar_dispersion_delay_s(dm_pc_cm3, freq_2_hz)?;
441 Ok(dt1 - dt2)
442}
443
444pub fn infer_dispersion_measure_dual_band(
447 toa_1_s: f64,
448 freq_1_hz: f64,
449 toa_2_s: f64,
450 freq_2_hz: f64,
451) -> Result<(f64, f64), &'static str> {
452 if freq_1_hz <= 0.0 || freq_2_hz <= 0.0 || (freq_1_hz - freq_2_hz).abs() < 1.0 {
453 return Err("dual-band frequencies must be distinct positive values in Hz");
454 }
455 let f1_ghz = freq_1_hz * 1.0e-9;
456 let f2_ghz = freq_2_hz * 1.0e-9;
457 let inv_diff = 1.0 / (f1_ghz * f1_ghz) - 1.0 / (f2_ghz * f2_ghz);
458 let k_s = PULSAR_DISPERSION_CONSTANT_MS_GHZ2 * 1.0e-3;
459 let dm = (toa_1_s - toa_2_s) / (k_s * inv_diff);
460 if dm < 0.0 || !dm.is_finite() {
461 return Err("inferred dispersion measure is negative or non-finite");
462 }
463 let dt1 = pulsar_dispersion_delay_s(dm, freq_1_hz)?;
464 let vacuum_toa_s = toa_1_s - dt1;
465 Ok((dm, vacuum_toa_s))
466}
467
468pub fn triangulate_from_pulsars(
478 anchors: &[PulsarAnchor; 4],
479 observed_phases: &[f64; 4],
480) -> Result<[f64; 3], &'static str> {
481 let mut vac_dt = [0.0_f64; 4];
482 let mut unit_dirs = [[0.0_f64; 3]; 4];
483
484 for i in 0..4 {
485 let a = &anchors[i];
486 if a.period_s <= 0.0 || !a.period_s.is_finite() {
487 return Err("pulsar period_s must be positive and finite");
488 }
489 let norm = (a.direction_unit[0] * a.direction_unit[0]
490 + a.direction_unit[1] * a.direction_unit[1]
491 + a.direction_unit[2] * a.direction_unit[2])
492 .sqrt();
493 if norm < 1e-12 {
494 return Err("pulsar direction_unit must be non-zero");
495 }
496 unit_dirs[i] = [
497 a.direction_unit[0] / norm,
498 a.direction_unit[1] / norm,
499 a.direction_unit[2] / norm,
500 ];
501 let dm_delay = a.dispersion_delay_s()?;
502 vac_dt[i] = observed_phases[i] * a.period_s - dm_delay;
504 }
505
506 let mut m = [[0.0_f64; 3]; 3];
508 let mut rhs = [0.0_f64; 3];
509 for row in 0..3 {
510 let i = row + 1;
511 m[row] = [
512 unit_dirs[0][0] - unit_dirs[i][0],
513 unit_dirs[0][1] - unit_dirs[i][1],
514 unit_dirs[0][2] - unit_dirs[i][2],
515 ];
516 rhs[row] = C0_VACUUM_M_S * (vac_dt[i] - vac_dt[0]);
517 }
518
519 solve_3x3(m, rhs)
520}
521
522fn solve_3x3(mut a: [[f64; 3]; 3], mut b: [f64; 3]) -> Result<[f64; 3], &'static str> {
523 for col in 0..3 {
524 let mut pivot_row = col;
525 let mut max_abs = a[col][col].abs();
526 for r in (col + 1)..3 {
527 let v = a[r][col].abs();
528 if v > max_abs {
529 max_abs = v;
530 pivot_row = r;
531 }
532 }
533 if max_abs < 1e-12 {
534 return Err("degenerate pulsar geometry: direction differences are coplanar");
535 }
536 if pivot_row != col {
537 a.swap(col, pivot_row);
538 b.swap(col, pivot_row);
539 }
540 let pivot = a[col][col];
541 for r in (col + 1)..3 {
542 let factor = a[r][col] / pivot;
543 for c in col..3 {
544 a[r][c] -= factor * a[col][c];
545 }
546 b[r] -= factor * b[col];
547 }
548 }
549
550 let mut x = [0.0_f64; 3];
551 for row in (0..3).rev() {
552 let mut sum = b[row];
553 for col in (row + 1)..3 {
554 sum -= a[row][col] * x[col];
555 }
556 x[row] = sum / a[row][row];
557 }
558 Ok(x)
559}
560
561#[derive(Debug, Clone)]
563pub struct CelestialBodyProfile {
564 pub name: String,
565 pub class: CelestialBodyClass,
566 pub usri: String,
567 pub mass_kg: f64,
568 pub equatorial_radius_m: f64,
569 pub rotation_period_s: f64,
570 pub surface: ReferenceSurface,
571 pub gravity: GravitationalField,
572}
573
574impl CelestialBodyProfile {
575 pub fn surface_gravity(&self) -> f64 {
577 self.gravity.mu / (self.equatorial_radius_m * self.equatorial_radius_m)
578 }
579
580 pub fn to_value(&self) -> Value {
582 let mut rec = BTreeMap::new();
583 rec.insert("name".into(), Value::String(self.name.clone()));
584 rec.insert("class".into(), Value::String(self.class.as_str().into()));
585 rec.insert("usri".into(), Value::String(self.usri.clone()));
586 rec.insert("mass_kg".into(), Value::F64(self.mass_kg));
587 rec.insert(
588 "equatorial_radius_m".into(),
589 Value::F64(self.equatorial_radius_m),
590 );
591 rec.insert(
592 "rotation_period_s".into(),
593 Value::F64(self.rotation_period_s),
594 );
595 rec.insert("surface_gravity".into(), Value::F64(self.surface_gravity()));
596 Value::Record(rec)
597 }
598}
599
600pub fn earth_profile() -> CelestialBodyProfile {
602 CelestialBodyProfile {
603 name: "Earth".into(),
604 class: CelestialBodyClass::TerrestrialPlanet,
605 usri: "urn:omni:v1:physical:observable:standard:sol:earth".into(),
606 mass_kg: 5.972e24,
607 equatorial_radius_m: 6_378_137.0,
608 rotation_period_s: 86_164.0905, surface: ReferenceSurface::Biaxial {
610 a: 6_378_137.0,
611 c: 6_356_752.3,
612 },
613 gravity: {
614 let mut g = GravitationalField::newtonian(3.986004418e14, 6_378_137.0);
615 g.jn = vec![-1.08263e-3, 2.57e-6]; g
617 },
618 }
619}
620
621pub fn mars_profile() -> CelestialBodyProfile {
623 CelestialBodyProfile {
624 name: "Mars".into(),
625 class: CelestialBodyClass::TerrestrialPlanet,
626 usri: "urn:omni:v1:physical:observable:standard:sol:mars".into(),
627 mass_kg: 6.4171e23,
628 equatorial_radius_m: 3_396_200.0,
629 rotation_period_s: 88_642.66, surface: ReferenceSurface::Biaxial {
631 a: 3_396_200.0,
632 c: 3_376_200.0,
633 },
634 gravity: {
635 let mut g = GravitationalField::newtonian(4.282837e13, 3_396_200.0);
636 g.jn = vec![-1.96045e-3];
637 g
638 },
639 }
640}
641
642pub fn jupiter_profile() -> CelestialBodyProfile {
644 CelestialBodyProfile {
645 name: "Jupiter".into(),
646 class: CelestialBodyClass::GasGiant,
647 usri: "urn:omni:v1:physical:observable:standard:sol:jupiter".into(),
648 mass_kg: 1.898e27,
649 equatorial_radius_m: 71_492_000.0, rotation_period_s: 35_718.0, surface: ReferenceSurface::Equipotential {
652 name: "1-bar level".into(),
653 },
654 gravity: GravitationalField::newtonian(1.26686534e17, 71_492_000.0),
655 }
656}
657
658pub fn saturn_profile() -> CelestialBodyProfile {
660 CelestialBodyProfile {
661 name: "Saturn".into(),
662 class: CelestialBodyClass::GasGiant,
663 usri: "urn:omni:v1:physical:observable:standard:sol:saturn".into(),
664 mass_kg: 5.683e26,
665 equatorial_radius_m: 60_268_000.0,
666 rotation_period_s: 38_352.0, surface: ReferenceSurface::Equipotential {
668 name: "1-bar level".into(),
669 },
670 gravity: GravitationalField::newtonian(3.7931187e16, 60_268_000.0),
671 }
672}
673
674pub fn moon_profile() -> CelestialBodyProfile {
676 CelestialBodyProfile {
677 name: "Moon".into(),
678 class: CelestialBodyClass::NaturalSatellite,
679 usri: "urn:omni:v1:physical:observable:standard:sol:earth:moon".into(),
680 mass_kg: 7.342e22,
681 equatorial_radius_m: 1_737_400.0,
682 rotation_period_s: 2_360_591.6, surface: ReferenceSurface::Biaxial {
684 a: 1_737_400.0,
685 c: 1_735_970.0,
686 },
687 gravity: GravitationalField::newtonian(4.9048695e12, 1_737_400.0),
688 }
689}
690
691pub fn europa_profile() -> CelestialBodyProfile {
693 CelestialBodyProfile {
694 name: "Europa".into(),
695 class: CelestialBodyClass::NaturalSatellite,
696 usri: "urn:omni:v1:physical:observable:standard:sol:jupiter:europa".into(),
697 mass_kg: 4.8e22,
698 equatorial_radius_m: 1_560_800.0,
699 rotation_period_s: 271_558.8, surface: ReferenceSurface::Biaxial {
701 a: 1_560_800.0,
702 c: 1_560_300.0,
703 },
704 gravity: GravitationalField::newtonian(3.202e12, 1_560_800.0),
705 }
706}
707
708pub fn neutron_star_profile() -> CelestialBodyProfile {
710 CelestialBodyProfile {
711 name: "Neutron Star (typical)".into(),
712 class: CelestialBodyClass::CompactRelativistic,
713 usri: "urn:omni:v1:physical:observable:standard:neutron-star".into(),
714 mass_kg: 2.8e30, equatorial_radius_m: 12_000.0, rotation_period_s: 0.001, surface: ReferenceSurface::Biaxial {
718 a: 12_000.0,
719 c: 11_990.0,
720 },
721 gravity: GravitationalField {
722 mu: 1.867e20,
723 r_ref: 12_000.0,
724 jn: vec![],
725 schwarzschild_r: 2.0 * 1.867e20 / (C * C), kerr_spin_a: 1000.0, },
728 }
729}
730
731pub fn sgr_a_profile() -> CelestialBodyProfile {
733 CelestialBodyProfile {
734 name: "Sagittarius A*".into(),
735 class: CelestialBodyClass::BlackHole,
736 usri: "urn:omni:v1:physical:observable:standard:milkyway:sgr-a".into(),
737 mass_kg: 8.26e36, equatorial_radius_m: 1.227e10, rotation_period_s: 1.0e4, surface: ReferenceSurface::Equipotential {
741 name: "event horizon".into(),
742 },
743 gravity: GravitationalField {
744 mu: 5.514e26,
745 r_ref: 1.227e10,
746 jn: vec![],
747 schwarzschild_r: 1.227e10, kerr_spin_a: 0.9 * 1.227e10 / 2.0, },
750 }
751}
752
753pub fn sun_profile() -> CelestialBodyProfile {
755 CelestialBodyProfile {
756 name: "Sun".into(),
757 class: CelestialBodyClass::Star,
758 usri: "urn:omni:v1:physical:observable:standard:sol:sun".into(),
759 mass_kg: 1.989e30,
760 equatorial_radius_m: 696_340_000.0,
761 rotation_period_s: 2_192_320.0, surface: ReferenceSurface::Equipotential {
763 name: "photosphere".into(),
764 },
765 gravity: GravitationalField::newtonian(1.32712440018e20, 6_963_400_000.0),
766 }
767}
768
769pub fn body_profile_by_name(name: &str) -> Option<CelestialBodyProfile> {
771 match name {
772 "earth" => Some(earth_profile()),
773 "mars" => Some(mars_profile()),
774 "jupiter" => Some(jupiter_profile()),
775 "saturn" => Some(saturn_profile()),
776 "moon" => Some(moon_profile()),
777 "europa" => Some(europa_profile()),
778 "neutron-star" => Some(neutron_star_profile()),
779 "sgr-a" => Some(sgr_a_profile()),
780 "sun" => Some(sun_profile()),
781 _ => None,
782 }
783}
784
785#[cfg(test)]
786mod tests {
787 use super::*;
788
789 #[test]
790 fn earth_surface_gravity() {
791 let earth = earth_profile();
792 let g = earth.surface_gravity();
793 assert!((g - 9.81).abs() < 0.1, "got {} expected ~9.81", g);
794 }
795
796 #[test]
797 fn mars_surface_gravity() {
798 let mars = mars_profile();
799 let g = mars.surface_gravity();
800 assert!((g - 3.71).abs() < 0.1, "got {} expected ~3.71", g);
801 }
802
803 #[test]
804 fn jupiter_surface_gravity() {
805 let j = jupiter_profile();
806 let g = j.surface_gravity();
807 assert!((g - 24.79).abs() < 1.0, "got {} expected ~24.79", g);
808 }
809
810 #[test]
811 fn moon_surface_gravity() {
812 let m = moon_profile();
813 let g = m.surface_gravity();
814 assert!((g - 1.62).abs() < 0.1, "got {} expected ~1.62", g);
815 }
816
817 #[test]
818 fn sun_surface_gravity() {
819 let s = sun_profile();
820 let g = s.surface_gravity();
821 assert!((g - 274.0).abs() < 10.0, "got {} expected ~274", g);
822 }
823
824 #[test]
825 fn neutron_star_has_schwarzschild() {
826 let ns = neutron_star_profile();
827 assert!(ns.gravity.schwarzschild_r > 0.0);
828 assert!(ns.gravity.kerr_spin_a > 0.0);
829 assert!(ns.class.is_relativistic());
830 }
831
832 #[test]
833 fn sgr_a_is_black_hole() {
834 let sgr = sgr_a_profile();
835 assert_eq!(sgr.class, CelestialBodyClass::BlackHole);
836 assert!(sgr.gravity.schwarzschild_r > 0.0);
837 assert!(sgr.gravity.kerr_horizon_r() > 0.0);
838 }
839
840 #[test]
841 fn body_profile_lookup() {
842 assert!(body_profile_by_name("earth").is_some());
843 assert!(body_profile_by_name("jupiter").is_some());
844 assert!(body_profile_by_name("sgr-a").is_some());
845 assert!(body_profile_by_name("pluto").is_none());
846 }
847
848 #[test]
849 fn europa_is_natural_satellite() {
850 let e = europa_profile();
851 assert_eq!(e.class, CelestialBodyClass::NaturalSatellite);
852 assert!(e.surface_gravity() < 2.0);
853 }
854
855 #[test]
856 fn class_has_solid_surface() {
857 assert!(CelestialBodyClass::TerrestrialPlanet.has_solid_surface());
858 assert!(!CelestialBodyClass::GasGiant.has_solid_surface());
859 assert!(CelestialBodyClass::Megastructure.has_solid_surface());
860 }
861
862 #[test]
863 fn class_is_relativistic() {
864 assert!(CelestialBodyClass::BlackHole.is_relativistic());
865 assert!(CelestialBodyClass::CompactRelativistic.is_relativistic());
866 assert!(!CelestialBodyClass::Star.is_relativistic());
867 }
868
869 #[test]
870 fn class_round_trip() {
871 for c in [
872 CelestialBodyClass::TerrestrialPlanet,
873 CelestialBodyClass::GasGiant,
874 CelestialBodyClass::BlackHole,
875 CelestialBodyClass::FictionalWorld,
876 ] {
877 assert_eq!(CelestialBodyClass::from_str(c.as_str()), Some(c));
878 }
879 }
880
881 #[test]
882 fn kerr_horizon_schwarzschild() {
883 let g = GravitationalField {
884 mu: 1.0,
885 r_ref: 1.0,
886 jn: vec![],
887 schwarzschild_r: 100.0,
888 kerr_spin_a: 0.0,
889 };
890 assert!((g.kerr_horizon_r() - 100.0).abs() < 1e-10);
891 }
892
893 #[test]
894 fn kerr_horizon_spinning() {
895 let g = GravitationalField {
896 mu: 1.0,
897 r_ref: 1.0,
898 jn: vec![],
899 schwarzschild_r: 100.0,
900 kerr_spin_a: 30.0,
901 };
902 assert!((g.kerr_horizon_r() - 90.0).abs() < 1e-10);
903 }
904
905 #[test]
906 fn kerr_ergosphere_at_equator() {
907 let g = GravitationalField {
908 mu: 1.0,
909 r_ref: 1.0,
910 jn: vec![],
911 schwarzschild_r: 100.0,
912 kerr_spin_a: 30.0,
913 };
914 let r_eq = g.kerr_ergosphere_r(std::f64::consts::PI / 2.0);
915 assert!((r_eq - 100.0).abs() < 1e-10);
916 }
917
918 #[test]
919 fn kerr_ergosphere_at_pole() {
920 let g = GravitationalField {
921 mu: 1.0,
922 r_ref: 1.0,
923 jn: vec![],
924 schwarzschild_r: 100.0,
925 kerr_spin_a: 30.0,
926 };
927 let r_pole = g.kerr_ergosphere_r(0.0);
928 assert!((r_pole - 90.0).abs() < 1e-10);
929 }
930
931 #[test]
932 fn frame_dragging_nonzero_and_dimensionally_exact() {
933 let g = GravitationalField {
934 mu: 3.986e14,
935 r_ref: 6_378_137.0,
936 jn: vec![],
937 schwarzschild_r: 0.00887,
938 kerr_spin_a: 3.3, };
940 let r = 6_800_000.0;
941 let omega = g.frame_dragging(r);
942 let expected = 2.0 * g.mu * g.kerr_spin_a / (C0_VACUUM_M_S * r * r * r);
943 assert!(omega > 0.0);
944 assert!((omega - expected).abs() < 1e-24);
945 assert!(omega > 1e-15 && omega < 1e-12, "omega = {}", omega);
947 }
948
949 #[test]
950 fn pulsar_dual_band_dedispersion_and_4_anchor_triangulation() {
951 let dm = 25.0; let f1 = 1.4e9; let f2 = 2.8e9; let diff_s = dual_band_dedisperse_delay_s(dm, f1, f2).unwrap();
955 let expected_s =
956 4.148808e-3 * dm * (1.0 / (1.4 * 1.4) - 1.0 / (2.8 * 2.8));
957 assert!((diff_s - expected_s).abs() < 1e-12);
958
959 let true_vac_toa = 1000.123456;
960 let toa1 = true_vac_toa + pulsar_dispersion_delay_s(dm, f1).unwrap();
961 let toa2 = true_vac_toa + pulsar_dispersion_delay_s(dm, f2).unwrap();
962 let (inferred_dm, inferred_vac_toa) =
963 infer_dispersion_measure_dual_band(toa1, f1, toa2, f2).unwrap();
964 assert!((inferred_dm - dm).abs() < 1e-9);
965 assert!((inferred_vac_toa - true_vac_toa).abs() < 1e-12);
966
967 let anchors = [
969 PulsarAnchor {
970 id_hash: 1,
971 direction_unit: [1.0, 0.0, 0.0],
972 period_s: 0.001557,
973 period_derivative: 1.0e-19,
974 epoch_t0_s: 0.0,
975 carrier_freq_hz: 1.4e9,
976 dispersion_measure_pc_cm3: 15.0,
977 },
978 PulsarAnchor {
979 id_hash: 2,
980 direction_unit: [0.0, 1.0, 0.0],
981 period_s: 0.005757,
982 period_derivative: 1.0e-20,
983 epoch_t0_s: 0.0,
984 carrier_freq_hz: 1.4e9,
985 dispersion_measure_pc_cm3: 32.0,
986 },
987 PulsarAnchor {
988 id_hash: 3,
989 direction_unit: [0.0, 0.0, 1.0],
990 period_s: 0.002145,
991 period_derivative: 1.0e-20,
992 epoch_t0_s: 0.0,
993 carrier_freq_hz: 2.0e9,
994 dispersion_measure_pc_cm3: 18.5,
995 },
996 PulsarAnchor::x_ray(
997 4,
998 [-1.0 / 3.0_f64.sqrt(), -1.0 / 3.0_f64.sqrt(), -1.0 / 3.0_f64.sqrt()],
999 0.003050,
1000 1.0e-20,
1001 0.0,
1002 ),
1003 ];
1004
1005 let true_pos_m = [1.5e8, -2.2e8, 0.85e8];
1006 let clock_bias_s = 0.00042; let mut observed_phases = [0.0_f64; 4];
1009 for i in 0..4 {
1010 let n = anchors[i].direction_unit;
1011 let geom_dt =
1012 -(n[0] * true_pos_m[0] + n[1] * true_pos_m[1] + n[2] * true_pos_m[2]) / C0_VACUUM_M_S;
1013 let dm_dt = anchors[i].dispersion_delay_s().unwrap();
1014 let total_dt = geom_dt + clock_bias_s + dm_dt;
1015 observed_phases[i] = total_dt / anchors[i].period_s;
1016 }
1017
1018 let solved_pos = triangulate_from_pulsars(&anchors, &observed_phases).unwrap();
1019 for axis in 0..3 {
1020 assert!(
1021 (solved_pos[axis] - true_pos_m[axis]).abs() < 1e-3,
1022 "axis {} mismatch: got {}, expected {}",
1023 axis,
1024 solved_pos[axis],
1025 true_pos_m[axis]
1026 );
1027 }
1028 }
1029
1030 #[test]
1031 fn emf_manifold_causal_cone_and_cold_plasma_dispersion() {
1032 let sun = sun_profile();
1033 let r1 = [-1.5e11, 7.0e8, 0.0];
1034 let r2 = [1.5e11, 7.0e8, 0.0];
1035
1036 let plasma = EmfMediumSpec::cold_plasma(1.5e9, 1.5e7, 40.0).unwrap();
1038 let (_, est_spacelike) = sun
1040 .gravity
1041 .emf_manifold_causal_interval_s(r1, r2, 100.0, &plasma)
1042 .unwrap();
1043 assert!(est_spacelike.group_velocity_m_s < C0_VACUUM_M_S);
1044 assert!(est_spacelike.phase_velocity_m_s > C0_VACUUM_M_S);
1045 let prod = est_spacelike.group_velocity_m_s * est_spacelike.phase_velocity_m_s;
1046 let c0_sq = C0_VACUUM_M_S * C0_VACUUM_M_S;
1047 assert!((prod - c0_sq).abs() / c0_sq < 1e-12);
1048 assert!(est_spacelike.shapiro_delay_s > 0.0);
1049
1050 let (rel_spacelike, _) = sun
1051 .gravity
1052 .emf_manifold_causal_interval_s(r1, r2, 100.0, &plasma)
1053 .unwrap();
1054 assert_eq!(rel_spacelike, CausalConeRelation::SpacelikeElsewhere);
1055
1056 let (rel_arrival, est_arrival) = sun
1057 .gravity
1058 .emf_manifold_causal_interval_s(
1059 r1,
1060 r2,
1061 est_spacelike.total_signal_arrival_time_s + 1.0,
1062 &plasma,
1063 )
1064 .unwrap();
1065 assert_eq!(rel_arrival, CausalConeRelation::DispersedMediumArrival);
1066 assert!(est_arrival.spacetime_interval_m2 < 0.0);
1067
1068 let bad_medium = EmfMediumSpec {
1070 group_refractive_index: 0.95,
1071 phase_refractive_index: 1.0,
1072 carrier_freq_hz: 1.0e9,
1073 dispersion_measure_pc_cm3: 0.0,
1074 };
1075 assert!(sun
1076 .gravity
1077 .emf_manifold_causal_interval_s(r1, r2, 2000.0, &bad_medium)
1078 .is_err());
1079 }
1080
1081 #[test]
1082 fn profile_to_value() {
1083 let earth = earth_profile();
1084 let v = earth.to_value();
1085 match v {
1086 Value::Record(r) => {
1087 assert_eq!(r.get("name"), Some(&Value::String("Earth".into())));
1088 assert!(r.contains_key("surface_gravity"));
1089 }
1090 _ => panic!("expected Record"),
1091 }
1092 }
1093}