#![allow(
clippy::needless_range_loop,
clippy::many_single_char_names,
clippy::similar_names
)]
use core::f64::consts::TAU;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ConjunctionGeometry {
pub relative_position: [f64; 3],
pub relative_velocity: [f64; 3],
pub primary_covariance: [[f64; 3]; 3],
pub secondary_covariance: [[f64; 3]; 3],
pub primary_radius: f64,
pub secondary_radius: f64,
}
impl ConjunctionGeometry {
#[must_use]
pub const fn new(
relative_position: [f64; 3],
relative_velocity: [f64; 3],
primary_covariance: [[f64; 3]; 3],
secondary_covariance: [[f64; 3]; 3],
primary_radius: f64,
secondary_radius: f64,
) -> Self {
Self {
relative_position,
relative_velocity,
primary_covariance,
secondary_covariance,
primary_radius,
secondary_radius,
}
}
pub fn project(&self) -> Result<EncounterPlane, ConjunctionError> {
let v = self.relative_velocity;
let vmag = libm::sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
if vmag <= 0.0 || !vmag.is_finite() {
return Err(ConjunctionError::DegenerateEncounterVelocity);
}
let uv = [v[0] / vmag, v[1] / vmag, v[2] / vmag];
let helper = if libm::fabs(uv[0]) < 0.9 {
[1.0, 0.0, 0.0]
} else {
[0.0, 1.0, 0.0]
};
let e1 = normalize3(cross3(&uv, &helper));
let e2 = cross3(&uv, &e1);
let mut c = [[0.0; 3]; 3];
for i in 0..3 {
for j in 0..3 {
c[i][j] = self.primary_covariance[i][j] + self.secondary_covariance[i][j];
}
}
let r = self.relative_position;
let miss = [dot3(&e1, &r), dot3(&e2, &r)];
let cov = [
[bilinear3(&c, &e1, &e1), bilinear3(&c, &e1, &e2)],
[bilinear3(&c, &e2, &e1), bilinear3(&c, &e2, &e2)],
];
let radius = self.primary_radius + self.secondary_radius;
EncounterPlane::new(miss, cov, radius)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EncounterPlane {
miss: [f64; 2],
covariance: [[f64; 2]; 2],
radius: f64,
}
impl EncounterPlane {
pub fn new(
miss: [f64; 2],
covariance: [[f64; 2]; 2],
radius: f64,
) -> Result<Self, ConjunctionError> {
if radius < 0.0 || !radius.is_finite() {
return Err(ConjunctionError::InvalidHardBodyRadius);
}
let off = f64::midpoint(covariance[0][1], covariance[1][0]);
let cov = [[covariance[0][0], off], [off, covariance[1][1]]];
let (lambda_min, _) = eigenvalues_2x2(&cov);
if lambda_min <= 0.0
|| lambda_min.is_nan()
|| !cov[0][0].is_finite()
|| !cov[1][1].is_finite()
{
return Err(ConjunctionError::NonPositiveDefiniteCovariance);
}
Ok(Self {
miss,
covariance: cov,
radius,
})
}
pub fn from_diagonal(
miss_x: f64,
miss_y: f64,
sigma_x: f64,
sigma_y: f64,
radius: f64,
) -> Result<Self, ConjunctionError> {
if sigma_x <= 0.0 || sigma_y <= 0.0 {
return Err(ConjunctionError::NonPositiveDefiniteCovariance);
}
Self::new(
[miss_x, miss_y],
[[sigma_x * sigma_x, 0.0], [0.0, sigma_y * sigma_y]],
radius,
)
}
#[must_use]
pub const fn miss(&self) -> [f64; 2] {
self.miss
}
#[must_use]
pub const fn covariance(&self) -> [[f64; 2]; 2] {
self.covariance
}
#[must_use]
pub const fn radius(&self) -> f64 {
self.radius
}
#[must_use]
pub fn probability_foster(&self) -> f64 {
if self.radius <= 0.0 {
return 0.0;
}
let (det, inv) = self.inverse();
let inv_sqrt_det = 1.0 / libm::sqrt(det);
let m = self.miss;
let rr = self.radius;
let cc = bilinear2(&inv, &m, &m);
let n = self.angular_samples();
let dphi = TAU / usize_as_f64(n);
let mut acc = 0.0;
for k in 0..n {
let phi = (usize_as_f64(k) + 0.5) * dphi;
let u = [libm::cos(phi), libm::sin(phi)];
let aa = bilinear2(&inv, &u, &u); let bb = bilinear2(&inv, &u, &m); let mu = bb / aa;
let s = libm::sqrt(aa * 0.5);
let radial = (libm::exp(-0.5 * aa * mu * mu)
- libm::exp(-0.5 * aa * (rr - mu) * (rr - mu)))
/ aa
+ mu * 0.5 * libm::sqrt(TAU / aa) * (libm::erf(s * (rr - mu)) + libm::erf(s * mu));
acc += libm::exp(-0.5 * (cc - bb * bb / aa)) * radial;
}
clamp_unit(acc * dphi * inv_sqrt_det / TAU)
}
#[must_use]
pub fn probability_patera(&self) -> f64 {
if self.radius <= 0.0 {
return 0.0;
}
let l00 = libm::sqrt(self.covariance[0][0]);
let l10 = self.covariance[1][0] / l00;
let l11 = libm::sqrt(self.covariance[1][1] - l10 * l10);
let w00 = 1.0 / l00;
let w11 = 1.0 / l11;
let w10 = -l10 / (l00 * l11);
let a0 = -(w00 * self.miss[0]);
let a1 = -(w10 * self.miss[0] + w11 * self.miss[1]);
let rr = self.radius;
let n = self.angular_samples();
let dt = TAU / usize_as_f64(n);
let mut acc = 0.0;
for k in 0..n {
let t = (usize_as_f64(k) + 0.5) * dt;
let (ct, st) = (libm::cos(t), libm::sin(t));
let s1 = a0 + rr * w00 * ct;
let s2 = a1 + rr * (w10 * ct + w11 * st);
let s1p = -rr * w00 * st;
let s2p = rr * (-w10 * st + w11 * ct);
let r2 = s1 * s1 + s2 * s2;
let h = if r2 < 1e-8 {
0.5 - r2 / 8.0 + r2 * r2 / 48.0
} else {
(1.0 - libm::exp(-0.5 * r2)) / r2
};
acc += h * (s1 * s2p - s2 * s1p);
}
clamp_unit(acc * dt / TAU)
}
#[must_use]
pub fn probability_chan(&self) -> f64 {
if self.radius <= 0.0 {
return 0.0;
}
let (det, inv) = self.inverse();
let u = self.radius * self.radius / libm::sqrt(det);
let v = bilinear2(&inv, &self.miss, &self.miss);
let (a, b) = (0.5 * v, 0.5 * u);
let ln_b = libm::log(b);
let ln_a = libm::log(a); let mut ln_q = -b; let mut ln_pj = -a; let mut cdf_j = 0.0; let mut pc = 0.0;
let imax = poisson_terms(b);
for i in 1..=imax {
let fi = usize_as_f64(i);
let ln_fi = libm::log(fi);
ln_q += ln_b - ln_fi; cdf_j += libm::exp(ln_pj); let term = libm::exp(ln_q) * cdf_j;
pc += term;
ln_pj += ln_a - ln_fi; if fi > b && term < 1e-18 * pc {
break;
}
}
clamp_unit(pc)
}
#[must_use]
pub fn probability_max(&self) -> f64 {
let eval = |log_k: f64| -> f64 {
let k = libm::exp(log_k);
let scaled = Self {
miss: self.miss,
covariance: [
[self.covariance[0][0] * k, self.covariance[0][1] * k],
[self.covariance[1][0] * k, self.covariance[1][1] * k],
],
radius: self.radius,
};
scaled.probability_foster()
};
let (lo, hi) = (-25.0, 25.0);
let steps = 48usize;
let mut best_x = lo;
let mut best_f = eval(lo);
for i in 1..=steps {
let x = lo + (hi - lo) * usize_as_f64(i) / usize_as_f64(steps);
let f = eval(x);
if f > best_f {
best_f = f;
best_x = x;
}
}
let width = (hi - lo) / usize_as_f64(steps);
let (mut a, mut b) = (best_x - width, best_x + width);
let gr = 0.5 * (libm::sqrt(5.0) - 1.0);
let (mut c, mut d) = (b - gr * (b - a), a + gr * (b - a));
let (mut fc, mut fd) = (eval(c), eval(d));
for _ in 0..64 {
if fc > fd {
b = d;
d = c;
fd = fc;
c = b - gr * (b - a);
fc = eval(c);
} else {
a = c;
c = d;
fc = fd;
d = a + gr * (b - a);
fd = eval(d);
}
if libm::fabs(b - a) < 1e-10 {
break;
}
}
best_f.max(fc).max(fd)
}
fn inverse(&self) -> (f64, [[f64; 2]; 2]) {
let c = &self.covariance;
let det = c[0][0] * c[1][1] - c[0][1] * c[1][0];
let inv = [
[c[1][1] / det, -c[0][1] / det],
[-c[1][0] / det, c[0][0] / det],
];
(det, inv)
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
fn angular_samples(&self) -> usize {
let (lambda_min, lambda_max) = eigenvalues_2x2(&self.covariance);
let aspect = libm::sqrt(lambda_max / lambda_min);
(16.0 * aspect).clamp(1024.0, 262_144.0) as usize
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConjunctionError {
DegenerateEncounterVelocity,
NonPositiveDefiniteCovariance,
InvalidHardBodyRadius,
}
impl core::fmt::Display for ConjunctionError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::DegenerateEncounterVelocity => {
write!(
f,
"relative velocity is zero or non-finite; no encounter plane is defined"
)
}
Self::NonPositiveDefiniteCovariance => {
write!(
f,
"projected covariance is not positive-definite (degenerate uncertainty)"
)
}
Self::InvalidHardBodyRadius => {
write!(f, "combined hard-body radius is negative or non-finite")
}
}
}
}
impl core::error::Error for ConjunctionError {}
fn eigenvalues_2x2(c: &[[f64; 2]; 2]) -> (f64, f64) {
let (a, d) = (c[0][0], c[1][1]);
let b = f64::midpoint(c[0][1], c[1][0]);
let half_trace = f64::midpoint(a, d);
let radius = libm::sqrt(0.25 * (a - d) * (a - d) + b * b);
(half_trace - radius, half_trace + radius)
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
fn poisson_terms(mean: f64) -> usize {
let n = mean + 50.0 * libm::sqrt(mean + 1.0) + 64.0;
(n as usize).min(1 << 20)
}
fn bilinear2(m: &[[f64; 2]; 2], u: &[f64; 2], v: &[f64; 2]) -> f64 {
u[0] * (m[0][0] * v[0] + m[0][1] * v[1]) + u[1] * (m[1][0] * v[0] + m[1][1] * v[1])
}
fn bilinear3(m: &[[f64; 3]; 3], u: &[f64; 3], v: &[f64; 3]) -> f64 {
let mut acc = 0.0;
for i in 0..3 {
for j in 0..3 {
acc += u[i] * m[i][j] * v[j];
}
}
acc
}
fn dot3(a: &[f64; 3], b: &[f64; 3]) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn cross3(a: &[f64; 3], b: &[f64; 3]) -> [f64; 3] {
[
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
}
fn normalize3(a: [f64; 3]) -> [f64; 3] {
let n = libm::sqrt(dot3(&a, &a));
[a[0] / n, a[1] / n, a[2] / n]
}
fn clamp_unit(p: f64) -> f64 {
p.clamp(0.0, 1.0)
}
#[allow(clippy::cast_precision_loss)]
fn usize_as_f64(n: usize) -> f64 {
n as f64
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::float_cmp,
clippy::cast_precision_loss,
clippy::too_many_lines,
// Reference covariances and probabilities are transcribed verbatim from the source CDM files
// and papers; keep every digit for provenance even though f64 cannot resolve the last few, and
// do not sprinkle digit separators through primary-source data.
clippy::excessive_precision,
clippy::unreadable_literal
)]
use super::*;
type CaraCase = (
[f64; 3],
[f64; 3],
[[f64; 3]; 3],
[[f64; 3]; 3],
f64,
f64,
&'static str,
);
fn grid_probability(plane: &EncounterPlane, n: usize) -> f64 {
let (det, inv) = plane.inverse();
let norm = 1.0 / (TAU * libm::sqrt(det));
let r = plane.radius();
let step = 2.0 * r / n as f64;
let m = plane.miss();
let mut acc = 0.0;
for iy in 0..n {
let y = -r + (iy as f64 + 0.5) * step;
for ix in 0..n {
let x = -r + (ix as f64 + 0.5) * step;
if x * x + y * y <= r * r {
let d = [x - m[0], y - m[1]];
acc += norm * libm::exp(-0.5 * bilinear2(&inv, &d, &d));
}
}
}
acc * step * step
}
#[test]
fn foster_patera_and_grid_agree_across_geometries() {
let cases = [
(0.0, 0.0, 50.0, 50.0, 20.0, 4000, "circular, centred"),
(30.0, 40.0, 50.0, 50.0, 20.0, 4000, "circular, off-centre"),
(10.0, 25.0, 30.0, 90.0, 15.0, 4000, "3:1 elongated"),
(14.9, 0.0, 20.0, 60.0, 15.0, 5000, "grazing miss ≈ R"),
(100.0, 0.0, 40.0, 120.0, 10.0, 4000, "far off-centre"),
];
let mut worst_fp = 0.0_f64;
let mut worst_fg = 0.0_f64;
for (mx, my, sx, sy, r, n, label) in cases {
let plane = EncounterPlane::from_diagonal(mx, my, sx, sy, r).unwrap();
let foster = plane.probability_foster();
let patera = plane.probability_patera();
let grid = grid_probability(&plane, n);
let fp = (foster - patera).abs() / foster;
let fg = (foster - grid).abs() / foster;
worst_fp = worst_fp.max(fp);
worst_fg = worst_fg.max(fg);
println!(
"{label:22}: Pc={foster:.6e} |Foster−Patera|/Pc={fp:.2e} |Foster−grid|/Pc={fg:.2e}"
);
assert!(fp < 1e-9, "{label}: Foster vs Patera {fp:.2e}");
assert!(fg < 5e-4, "{label}: Foster vs grid {fg:.2e}");
}
println!("worst: Foster–Patera {worst_fp:.2e}, Foster–grid {worst_fg:.2e}");
}
#[test]
fn chan_reproduces_published_reference_values() {
let cases = [
(0.0, 10.0, 25.0, 50.0, 5.0, 9.754e-3, "Chan 01"),
(10.0, 0.0, 25.0, 50.0, 5.0, 9.189e-3, "Chan 02"),
(0.0, 10.0, 25.0, 75.0, 5.0, 6.586e-3, "Chan 03"),
(10.0, 0.0, 25.0, 75.0, 5.0, 6.135e-3, "Chan 04"),
(0.0, 1000.0, 1000.0, 3000.0, 10.0, 1.577e-5, "Chan 05"),
(1000.0, 0.0, 1000.0, 3000.0, 10.0, 1.011e-5, "Chan 06"),
(0.0, 10000.0, 1000.0, 3000.0, 10.0, 6.443e-8, "Chan 07"),
(10000.0, 0.0, 1000.0, 3000.0, 10.0, 3.216e-27, "Chan 08"),
(0.0, 10000.0, 1000.0, 10000.0, 10.0, 3.033e-6, "Chan 09"),
(10000.0, 0.0, 1000.0, 10000.0, 10.0, 9.645e-28, "Chan 10"),
(0.0, 5000.0, 1000.0, 3000.0, 50.0, 1.039e-4, "Chan 11"),
(5000.0, 0.0, 1000.0, 3000.0, 50.0, 1.556e-9, "Chan 12"),
(
84.875546,
60.583685,
57.918666,
152.8814468,
10.3,
1.8934e-3,
"CSM 1",
),
(
-692.362272,
4475.456261,
193.454603,
562.027293,
13.2,
2.2880e-20,
"CDM 2",
),
(
-3.8872073,
0.1591646,
1.4101830,
114.2585190,
15.0,
3.1264e-2,
"Alfano 3 (Chan)",
),
];
let mut worst = 0.0_f64;
for (mx, my, sx, sy, r, reference, label) in cases {
let plane = EncounterPlane::from_diagonal(mx, my, sx, sy, r).unwrap();
let chan = plane.probability_chan();
let rel = (chan - reference).abs() / reference;
worst = worst.max(rel);
println!("{label:16}: ref={reference:.4e} chan={chan:.4e} rel={rel:.2e}");
assert!(
rel < 1e-3,
"{label}: Chan {chan:.4e} vs ref {reference:.4e} = {rel:.2e}"
);
}
println!("worst Chan relative error vs published (4-sig-fig) references: {worst:.2e}");
}
#[test]
fn alfano_cara_cases_reproduce_published_reference() {
let cases: [CaraCase; 10] = [
(
[-0.502165, -0.497806, 4.999966],
[-0.009963, 0.010037, -0.000001],
rtn(
1.988970273925819e1,
-3.524140813027809e2,
6.496749385722737e3,
0.0,
0.0,
1.205039522307600e0,
),
rtn(
1.989074842319444e1,
-3.524310089952797e2,
6.496894829253188e3,
-9.767348673026151e-21,
6.463165376425425e-19,
1.204674647143796e0,
),
15.0,
0.146749549,
"CARA 01",
),
(
[-0.502163, -0.497792, 4.999966],
[-0.009963, 0.010037, -0.000001],
rtn(
1.988970262612387e1,
-3.524140803158783e2,
6.496749387784603e3,
0.0,
0.0,
1.205039521089100e0,
),
rtn(
1.989074830997710e1,
-3.524310080076631e2,
6.496894831316016e3,
-8.716498422838784e-20,
9.405936919789482e-19,
1.204674645925095e0,
),
4.0,
0.006222267,
"CARA 02",
),
(
[-2.751685, -0.487898, 2.752074],
[-11.365912, 0.051787, -11.356027],
rtn(
1.988980036134080e1,
-3.524149328959712e2,
6.496747606851101e3,
0.0,
0.0,
1.205040573210700e0,
),
rtn(
1.746930568576392e1,
-3.305057350225742e2,
6.542324010830698e3,
-1.279563505801461e-15,
-4.449721840993348e-13,
1.177810899317289e0,
),
15.0,
0.100351176,
"CARA 03",
),
(
[-37.720379, -128.952321, -3.757988],
[0.018266, -0.005344, 0.000250],
rtn(
4.080844572465061e-1,
4.674493755532058e1,
6.024200059574752e3,
0.0,
0.0,
4.593629039291300e-2,
),
rtn(
4.078489163619697e-1,
4.672853966111639e1,
6.024412056804277e3,
8.207065180527589e-18,
3.523840694673876e-18,
4.596631194107787e-2,
),
15.0,
0.049323406,
"CARA 04",
),
(
[1.008140, -2.117599, 0.706652],
[-0.300002, -0.001116, 0.424270],
rtn(
4.777224467280041e-1,
-8.519384381202406e1,
1.580759742365653e4,
0.0,
0.0,
7.845896810140191e-2,
),
rtn(
4.710007645702890e-1,
-8.457040115987763e1,
1.580846029392646e4,
-1.748541090564049e-13,
-2.121117864684052e-11,
7.846753355604119e-2,
),
10.0,
0.044487386,
"CARA 05",
),
(
[-1.023573, -2.110003, -0.706847],
[-0.100006, 0.001133, 0.141439],
rtn(
4.777224465446061e1,
-8.519384379508079e3,
1.580759742368094e6,
0.0,
0.0,
3.551023949974670e0,
),
rtn(
4.754421287113225e1,
-8.498287373777353e3,
1.580789400229213e6,
5.141187961466009e-10,
-6.830025434112486e-9,
3.551139141711098e0,
),
10.0,
0.004335455,
"CARA 06",
),
(
[0.440517, -3.134352, 0.340075],
[0.136067, 0.003780, -0.141425],
rtn(
3.451363822699375e3,
-6.727558503785931e5,
1.316025642426085e8,
0.0,
0.0,
3.550903989987834e2,
),
rtn(
3.475004257748021e3,
-6.750594898692167e5,
1.316000293638659e8,
5.564041494210414e-8,
8.331824119522935e-9,
3.551481937268812e2,
),
10.0,
0.000158147,
"CARA 07",
),
(
[-1.381103, -2.008757, -1.666274],
[-0.000426, -0.000311, 0.000727],
rtn(
2.730011483545464e0,
-7.798527087944655e1,
2.665962873957034e3,
-6.338020386298382e-13,
-7.062822549031012e-12,
4.153963500401933e-1,
),
rtn(
2.729944919062438e0,
-7.798412102927176e1,
2.665964447851581e3,
-6.731837309814637e-12,
1.225114454328491e-11,
4.153969295672138e-1,
),
4.0,
0.036948008,
"CARA 08",
),
(
[-5.035858, 7.313429, -0.000420],
[-0.001712, -0.001179, -0.000000],
rtn(
1.020887925177703e1,
-2.755254218552751e1,
7.470382860526989e1,
2.171526847227767e-14,
1.976582959806184e-13,
4.300813243978246e-2,
),
rtn(
1.020890130430932e1,
-2.755270298941628e1,
7.470453231276690e1,
-1.325051179890124e-13,
3.318135696761537e-13,
4.300744509946160e-2,
),
6.0,
0.290146291,
"CARA 09",
),
(
[0.000421, -76.126083, 0.000000],
[0.084255, 0.000000, 0.000000],
rtn(
2.741843786640948e1,
-4.036901902356651e3,
6.965222505462344e5,
0.0,
0.0,
1.542470821442500e-1,
),
rtn(
2.741843786543052e1,
-4.036901902333630e3,
6.965222505447816e5,
0.0,
0.0,
1.542470821440900e-1,
),
4.0,
0.002672026,
"CARA 11",
),
];
let mut worst = 0.0_f64;
for (rpos, rvel, c1, c2, hbr, reference, label) in cases {
let geom = ConjunctionGeometry::new(rpos, rvel, c1, c2, 0.5 * hbr, 0.5 * hbr);
let plane = geom.project().unwrap();
let foster = plane.probability_foster();
let patera = plane.probability_patera();
let rel = (foster - reference).abs() / reference;
worst = worst.max(rel);
assert!(
(foster - patera).abs() / foster < 1e-8,
"{label}: Foster vs Patera"
);
println!(
"{label}: ref={reference:.9e} foster={foster:.9e} patera={patera:.9e} rel={rel:.2e}"
);
assert!(
rel < 3e-4,
"{label}: {foster:.6e} vs ref {reference:.6e} = {rel:.2e}"
);
}
println!("worst CARA relative error (Foster vs published reference): {worst:.2e}");
}
#[test]
fn chan_degrades_where_patera_stays_exact_for_extreme_ellipses() {
let a3 = EncounterPlane::from_diagonal(-3.8872073, 0.1591646, 1.4101830, 114.2585190, 15.0)
.unwrap();
let (p3, c3) = (a3.probability_patera(), a3.probability_chan());
println!("Alfano 3 (81:1): exact≈0.10038 patera={p3:.5e} chan={c3:.5e}");
assert!(
(p3 - 0.10038).abs() < 1e-4,
"Patera should match the exact reference: {p3:.5e}"
);
assert!(
c3 < 0.5 * p3,
"Chan must visibly under-predict here: {c3:.5e} vs {p3:.5e}"
);
let a5 = EncounterPlane::from_diagonal(-1.2217895, 2.1230067, 0.0373279, 177.8109003, 10.0)
.unwrap();
let (p5, c5) = (a5.probability_patera(), a5.probability_chan());
let f5 = a5.probability_foster();
println!(
"Alfano 5 (4764:1): exact≈0.044510 patera={p5:.5e} foster={f5:.5e} chan={c5:.5e}"
);
assert!(
(p5 - 0.044510).abs() < 1e-4,
"Patera should match the exact reference: {p5:.5e}"
);
assert!(
(f5 - 0.044510).abs() < 1e-4,
"Foster's analytic radial should too: {f5:.5e}"
);
assert!(c5 < 1e-10, "Chan collapses for this aspect ratio: {c5:.5e}");
}
#[test]
fn centred_conjunction_is_handled() {
let plane = EncounterPlane::from_diagonal(0.0, 0.0, 10.0, 30.0, 5.0).unwrap();
let foster = plane.probability_foster();
let patera = plane.probability_patera();
let grid = grid_probability(&plane, 4000);
println!("centred: foster={foster:.6e} patera={patera:.6e} grid={grid:.6e}");
assert!((foster - patera).abs() / foster < 1e-9);
assert!((foster - grid).abs() / foster < 5e-4);
}
#[test]
fn patera_takes_the_series_where_its_contour_weight_would_cancel() {
for r in [1e-6, 1e-5, 5e-5, 9.9e-5] {
let plane = EncounterPlane::from_diagonal(0.0, 0.0, 1.0, 1.0, r).unwrap();
let want = -libm::expm1(-0.5 * r * r);
let got = plane.probability_patera();
let rel = (got - want).abs() / want;
println!("R/sigma={r:e}: patera={got:.17e} exact={want:.17e} rel={rel:.2e}");
assert!(
rel < 1e-13,
"R/sigma={r:e}: {got:.17e} vs exact {want:.17e} (rel {rel:.2e})"
);
}
}
#[test]
fn ill_posed_inputs_are_rejected() {
assert_eq!(
EncounterPlane::new([0.0, 0.0], [[1.0, 2.0], [2.0, 1.0]], 5.0),
Err(ConjunctionError::NonPositiveDefiniteCovariance)
);
assert_eq!(
EncounterPlane::from_diagonal(0.0, 0.0, 0.0, 10.0, 5.0),
Err(ConjunctionError::NonPositiveDefiniteCovariance)
);
assert_eq!(
EncounterPlane::from_diagonal(0.0, 0.0, 10.0, 10.0, -1.0),
Err(ConjunctionError::InvalidHardBodyRadius)
);
let geom = ConjunctionGeometry::new(
[1.0, 2.0, 3.0],
[0.0, 0.0, 0.0],
[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
1.0,
1.0,
);
assert_eq!(
geom.project(),
Err(ConjunctionError::DegenerateEncounterVelocity)
);
assert_eq!(
EncounterPlane::from_diagonal(0.0, 0.0, -3.0, 10.0, 5.0),
Err(ConjunctionError::NonPositiveDefiniteCovariance)
);
assert_eq!(
EncounterPlane::from_diagonal(0.0, 0.0, 10.0, -3.0, 5.0),
Err(ConjunctionError::NonPositiveDefiniteCovariance)
);
let rendered = [
ConjunctionError::DegenerateEncounterVelocity.to_string(),
ConjunctionError::NonPositiveDefiniteCovariance.to_string(),
ConjunctionError::InvalidHardBodyRadius.to_string(),
];
for (i, text) in rendered.iter().enumerate() {
assert!(!text.is_empty(), "error {i} renders as the empty string");
for other in &rendered[i + 1..] {
assert_ne!(text, other, "two errors render identically: {text:?}");
}
}
}
#[test]
fn the_encounter_basis_survives_a_velocity_along_each_axis() {
for v in [
[7000.0_f64, 0.0, 0.0],
[0.0, 7000.0, 0.0],
[0.0, 0.0, 7000.0],
[-7000.0, 0.0, 0.0],
[0.0, -7000.0, 0.0],
[4000.0, 4000.0, 4000.0],
] {
let geom = ConjunctionGeometry::new(
[300.0, -200.0, 150.0],
v,
identity3(9.0),
identity3(16.0),
2.0,
3.0,
);
let plane = geom
.project()
.unwrap_or_else(|e| panic!("velocity {v:?} should project cleanly, got {e}"));
let cov = plane.covariance();
assert!(
(cov[0][0] - 25.0).abs() < 1e-12
&& (cov[1][1] - 25.0).abs() < 1e-12
&& cov[0][1].abs() < 1e-12,
"velocity {v:?}: projected covariance {cov:?} is not 25·I"
);
let vmag = libm::sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
let r = [300.0, -200.0, 150.0];
let along = (r[0] * v[0] + r[1] * v[1] + r[2] * v[2]) / vmag;
let want = libm::sqrt(r[0] * r[0] + r[1] * r[1] + r[2] * r[2] - along * along);
let got = libm::sqrt(plane.miss()[0].powi(2) + plane.miss()[1].powi(2));
assert!(
(got - want).abs() < 1e-9,
"velocity {v:?}: |miss| {got} vs perpendicular component {want}"
);
}
}
#[test]
fn projection_drops_along_velocity_and_keeps_perpendicular() {
let along = ConjunctionGeometry::new(
[7.0, 0.0, 0.0],
[100.0, 0.0, 0.0],
identity3(4.0),
identity3(4.0),
2.0,
3.0,
);
let plane = along.project().unwrap();
let miss_mag = libm::sqrt(plane.miss()[0].powi(2) + plane.miss()[1].powi(2));
println!(
"along-velocity miss magnitude = {miss_mag:.3e} (expect ≈0), R={}",
plane.radius()
);
assert!(
miss_mag < 1e-12,
"along-track miss should project out: {miss_mag:.3e}"
);
assert!((plane.radius() - 5.0).abs() < 1e-12, "combined radius 2+3");
assert!((plane.covariance()[0][0] - 8.0).abs() < 1e-12);
let perp = ConjunctionGeometry::new(
[0.0, 0.0, 7.0],
[100.0, 0.0, 0.0],
identity3(4.0),
identity3(4.0),
2.0,
3.0,
);
let plane = perp.project().unwrap();
let miss_mag = libm::sqrt(plane.miss()[0].powi(2) + plane.miss()[1].powi(2));
assert!(
(miss_mag - 7.0).abs() < 1e-12,
"perpendicular miss preserved: {miss_mag:.3e}"
);
}
#[test]
fn max_probability_dominates_every_scaling() {
let plane = EncounterPlane::from_diagonal(200.0, 150.0, 300.0, 900.0, 20.0).unwrap();
let nominal = plane.probability_foster();
let pmax = plane.probability_max();
println!("nominal Pc={nominal:.6e} max Pc={pmax:.6e}");
assert!(pmax >= nominal * (1.0 - 1e-9), "max below nominal");
for k in [0.1_f64, 0.3, 0.5, 2.0, 5.0, 10.0] {
let scaled = EncounterPlane::new(
plane.miss(),
[
[plane.covariance()[0][0] * k, plane.covariance()[0][1] * k],
[plane.covariance()[1][0] * k, plane.covariance()[1][1] * k],
],
plane.radius(),
)
.unwrap();
let scaled_pc = scaled.probability_foster();
assert!(
pmax >= scaled_pc * (1.0 - 1e-6),
"max below scaling k={k}: {pmax:.6e} < {scaled_pc:.6e}"
);
}
assert!(pmax > nominal, "expected an interior maximum above nominal");
}
#[test]
fn the_dilution_maximum_is_the_closed_form_r_squared_over_e_d_squared() {
for (d, radius) in [
(1000.0_f64, 1.0_f64),
(1000.0, 5.0),
(250.0, 0.5),
(8000.0, 10.0),
] {
let plane = EncounterPlane::from_diagonal(d, 0.0, 3.0, 3.0, radius).unwrap();
let want = radius * radius / (core::f64::consts::E * d * d);
let got = plane.probability_max();
assert!(
(got - want).abs() < 1e-4 * want,
"d = {d}, R = {radius}: max Pc {got:e} vs R²/(e·d²) = {want:e}"
);
}
let a = EncounterPlane::from_diagonal(1000.0, 0.0, 3.0, 3.0, 2.0).unwrap();
let b = EncounterPlane::from_diagonal(7000.0, 0.0, 21.0, 21.0, 14.0).unwrap();
let (pa, pb) = (a.probability_max(), b.probability_max());
assert!(
(pa - pb).abs() < 1e-6 * pa,
"the maximum is not scale-free: {pa:e} vs {pb:e}"
);
for (miss, cov, radius) in [
(
[1200.0_f64, -500.0],
[[900.0_f64, 350.0], [350.0, 400.0]],
1.0,
),
([1000.0, 0.0], [[1.0e6, 0.0], [0.0, 1.0e6]], 1.0),
([100_000.0, 0.0], [[4.0, 1.5], [1.5, 1.0]], 1.0),
] {
let plane = EncounterPlane::new(miss, cov, radius).unwrap();
let det = cov[0][0] * cov[1][1] - cov[0][1] * cov[1][0];
let inv_m = [
(cov[1][1] * miss[0] - cov[0][1] * miss[1]) / det,
(-cov[1][0] * miss[0] + cov[0][0] * miss[1]) / det,
];
let v = miss[0] * inv_m[0] + miss[1] * inv_m[1];
let want = radius * radius / (core::f64::consts::E * v * libm::sqrt(det));
let got = plane.probability_max();
println!(
"log k* = {:.3}, max Pc = {got:e} vs R²/(e·v·√det) = {want:e}, rel {:.2e}",
libm::log(0.5 * v),
(got - want).abs() / want
);
assert!(
(got - want).abs() < 1e-5 * want,
"miss {miss:?}, C {cov:?}: max Pc {got:e} vs R²/(e·v·√det C) = {want:e}"
);
}
}
#[test]
fn the_angular_sample_count_follows_the_documented_aspect_law() {
for (sigma_x, sigma_y, want) in [
(400.0_f64, 2.0_f64, 3200_usize), (30.0, 1.0, 1024), (1.0, 1.0, 1024), (2.0, 250.0, 2000), (20_000.0, 1.0, 262_144), ] {
let plane = EncounterPlane::from_diagonal(0.0, 0.0, sigma_x, sigma_y, 1.0).unwrap();
let got = plane.angular_samples();
assert_eq!(
got, want,
"σ = ({sigma_x}, {sigma_y}): {got} samples, expected {want}"
);
}
let cov = [[400.0 * 400.0, 0.0], [0.0, 4.0]];
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
for k in 0..3600 {
let t = TAU * f64::from(k) / 3600.0;
let u = [libm::cos(t), libm::sin(t)];
let q = bilinear2(&cov, &u, &u);
lo = lo.min(q);
hi = hi.max(q);
}
assert!(
(lo - 4.0).abs() < 1e-6 && (hi - 160_000.0).abs() < 1e-3,
"{lo} {hi}"
);
}
#[test]
fn chan_is_summed_to_convergence_at_a_poisson_mean_of_six_hundred() {
let r = libm::sqrt(1200.0);
let plane = EncounterPlane::new([r, 0.0], [[1.0, 0.0], [0.0, 1.0]], r).unwrap();
let (chan, foster) = (plane.probability_chan(), plane.probability_foster());
println!(
"b = 600: chan = {chan:.12e}, foster = {foster:.12e}, rel = {:.2e}",
(chan - foster).abs() / foster
);
assert!(
(chan - 0.5).abs() < 0.05,
"the fixture should sit near Pc = ½, got {chan:e}"
);
assert!(
(chan - foster).abs() < 1e-12 * foster,
"chan {chan:.12e} vs foster {foster:.12e}: the series was cut inside its own distribution"
);
for (b, exact) in [
(600.0_f64, 0.494_241_164_077_836_69_f64),
(700.0, 0.494_668_433_352_817_46),
(743.0, 0.494_825_037_465_882_97),
(744.0, 0.494_828_517_017_779_75),
(745.0, 0.494_831_989_560_337_14),
(746.0, 0.494_835_455_117_055_96),
(800.0, 0.495_012_831_765_856_03),
(2000.0, 0.496_845_985_773_746_28),
(50_000.0, 0.499_369_216_081_007_09),
] {
let r = libm::sqrt(2.0 * b);
let plane = EncounterPlane::new([r, 0.0], [[1.0, 0.0], [0.0, 1.0]], r).unwrap();
let chan = plane.probability_chan();
println!(
"b = {b}: chan = {chan:.15e}, ncx2 = {exact:.15e}, rel = {:.2e}",
(chan - exact).abs() / exact
);
assert!(
(chan - exact).abs() < 1e-9 * exact,
"b = {b}: chan {chan:.15e} vs ncx2 {exact:.15e}"
);
}
}
#[test]
fn the_two_by_two_eigenvalues_carry_the_trace_and_the_determinant() {
for c in [
[[4.0, 0.0], [0.0, 1.0]],
[[1.0, 0.0], [0.0, 1.0]],
[[900.0, 250.0], [250.0, 400.0]],
[[1.0e-6, 3.0e-7], [3.0e-7, 5.0e-6]],
[[2.5, -1.75], [-1.75, 2.5]], [[7.0, 2.0], [1.0, 3.0]], ] {
let (lo, hi) = eigenvalues_2x2(&c);
let b = f64::midpoint(c[0][1], c[1][0]);
let (trace, det) = (c[0][0] + c[1][1], c[0][0] * c[1][1] - b * b);
let scale = trace.abs().max(1.0);
assert!(lo <= hi, "{c:?}: eigenvalues out of order, {lo} > {hi}");
assert!(
(lo + hi - trace).abs() < 1e-12 * scale,
"{c:?}: λ_min + λ_max = {} vs trace {trace}",
lo + hi
);
assert!(
(lo * hi - det).abs() < 1e-12 * scale * scale,
"{c:?}: λ_min·λ_max = {} vs det {det}",
lo * hi
);
for lambda in [lo, hi] {
let residual = lambda * lambda - trace * lambda + det;
assert!(
residual.abs() < 1e-11 * scale * scale,
"{c:?}: λ = {lambda} leaves χ(λ) = {residual}"
);
}
}
}
fn identity3(d: f64) -> [[f64; 3]; 3] {
[[d, 0.0, 0.0], [0.0, d, 0.0], [0.0, 0.0, d]]
}
fn rtn(rr: f64, rt: f64, tt: f64, rn: f64, tn: f64, nn: f64) -> [[f64; 3]; 3] {
[[rr, rt, rn], [rt, tt, tn], [rn, tn, nn]]
}
}