use spacelab_autodiff::Scalar;
use crate::light_time::SPEED_OF_LIGHT;
use crate::multistatic::{TdoaGeometry, tdoa};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RadiometricError {
EmptyRampTable,
RampTableNotOrdered {
index: usize,
},
EpochOutsideRampTable {
epoch: f64,
first: f64,
last: f64,
},
NonPositiveInterval {
seconds: f64,
},
UnrepresentableModulus {
component: i32,
},
EmptyCoronaSeries,
NonPositiveExponent {
exponent: f64,
},
NonPositiveFrequency {
hertz: f64,
},
LineOfSightInsideTheSun {
impact_parameter: f64,
},
}
impl core::fmt::Display for RadiometricError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::EmptyRampTable => write!(f, "a ramp table with no segments spans no epoch"),
Self::RampTableNotOrdered { index } => {
write!(f, "ramp segment {index} is not after the one before it")
}
Self::EpochOutsideRampTable { epoch, first, last } => write!(
f,
"epoch {epoch} is outside the ramp table's span [{first}, {last}]"
),
Self::NonPositiveInterval { seconds } => {
write!(f, "an interval of {seconds} s is not positive")
}
Self::UnrepresentableModulus { component } => write!(
f,
"lowest ranging component {component} gives a modulus 2^({component}+6) that is not finite and positive"
),
Self::EmptyCoronaSeries => {
write!(f, "an electron-density series with no terms is not a model")
}
Self::NonPositiveExponent { exponent } => write!(
f,
"electron-density exponent {exponent} is not positive and finite"
),
Self::NonPositiveFrequency { hertz } => {
write!(f, "carrier frequency {hertz} Hz is not positive and finite")
}
Self::LineOfSightInsideTheSun { impact_parameter } => write!(
f,
"the line of sight passes {impact_parameter} m from the Sun's centre, inside the photosphere"
),
}
}
}
impl core::error::Error for RadiometricError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Band {
S,
X,
Ka,
}
impl Band {
#[must_use]
pub const fn uplink_denominator(self) -> f64 {
match self {
Self::S => 221.0,
Self::X => 749.0,
Self::Ka => 3599.0,
}
}
#[must_use]
pub const fn downlink_numerator(self) -> f64 {
match self {
Self::S => 240.0,
Self::X => 880.0,
Self::Ka => 3344.0,
}
}
#[must_use]
pub const fn turnaround_ratio(self, downlink: Self) -> f64 {
downlink.downlink_numerator() / self.uplink_denominator()
}
#[must_use]
pub const fn range_conversion_factor(self) -> f64 {
Self::S.uplink_denominator() / (2.0 * self.uplink_denominator())
}
}
pub const CASSINI_KA_TURNAROUND_RATIO: f64 = 14.0 / 15.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RampSegment {
pub start: f64,
pub end: f64,
pub start_frequency: f64,
pub rate: f64,
}
impl RampSegment {
fn frequency_at<S: Scalar>(&self, epoch: S) -> S {
S::from_f64(self.start_frequency)
+ S::from_f64(self.rate) * (epoch - S::from_f64(self.start))
}
fn integral<S: Scalar>(&self, from: S, to: S) -> S {
let span = to - from;
let at_from = S::from_f64(self.start_frequency)
+ S::from_f64(self.rate) * (from - S::from_f64(self.start));
span * (at_from + S::from_f64(self.rate) * span / S::from_f64(2.0))
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RampTable<'a> {
segments: &'a [RampSegment],
}
impl<'a> RampTable<'a> {
pub fn new(segments: &'a [RampSegment]) -> Result<Self, RadiometricError> {
if segments.is_empty() {
return Err(RadiometricError::EmptyRampTable);
}
for (index, segment) in segments.iter().enumerate() {
if segment.end <= segment.start
|| !segment.start.is_finite()
|| !segment.end.is_finite()
{
return Err(RadiometricError::RampTableNotOrdered { index });
}
if index > 0 && segment.start < segments[index - 1].end {
return Err(RadiometricError::RampTableNotOrdered { index });
}
}
Ok(Self { segments })
}
#[must_use]
pub const fn segments(&self) -> &'a [RampSegment] {
self.segments
}
#[must_use]
pub fn first(&self) -> f64 {
self.segments[0].start
}
#[must_use]
pub fn last(&self) -> f64 {
self.segments[self.segments.len() - 1].end
}
#[allow(clippy::float_cmp)]
fn segment_at(&self, epoch: f64) -> Result<&'a RampSegment, RadiometricError> {
self.segments
.iter()
.find(|s| epoch >= s.start && epoch < s.end)
.or_else(|| self.segments.last().filter(|s| epoch == s.end))
.ok_or_else(|| self.outside(epoch))
}
fn outside(&self, epoch: f64) -> RadiometricError {
RadiometricError::EpochOutsideRampTable {
epoch,
first: self.first(),
last: self.last(),
}
}
pub fn frequency_at<S: Scalar>(&self, epoch: S) -> Result<S, RadiometricError> {
Ok(self.segment_at(epoch.value())?.frequency_at(epoch))
}
pub fn integral<S: Scalar>(&self, from: S, to: S) -> Result<S, RadiometricError> {
let (a, b) = (from.value(), to.value());
if b <= a || !a.is_finite() || !b.is_finite() {
return Err(RadiometricError::NonPositiveInterval { seconds: b - a });
}
let mut total = S::from_f64(0.0);
let mut covered = from;
for segment in self.segments.iter().filter(|s| s.end > a && s.start < b) {
if segment.start > covered.value() {
return Err(self.outside(covered.value()));
}
let stop = if segment.end < b {
S::from_f64(segment.end)
} else {
to
};
total = total + segment.integral(covered, stop);
covered = stop;
}
if covered.value() < b {
return Err(self.outside(covered.value()));
}
Ok(total)
}
}
pub fn range_modulus(lowest_ranging_component: i32) -> Result<f64, RadiometricError> {
let modulus = libm::exp2(f64::from(lowest_ranging_component) + 6.0);
if modulus.is_finite() && modulus > 0.0 {
Ok(modulus)
} else {
Err(RadiometricError::UnrepresentableModulus {
component: lowest_ranging_component,
})
}
}
pub fn sequential_range<S: Scalar>(
table: &RampTable<'_>,
uplink: Band,
transmit: S,
receive: S,
lowest_ranging_component: i32,
) -> Result<S, RadiometricError> {
let modulus = range_modulus(lowest_ranging_component)?;
let cycles = table.integral(transmit, receive)?;
let units = S::from_f64(uplink.range_conversion_factor()) * cycles;
let wraps = libm::floor(units.value() / modulus);
Ok(units - S::from_f64(modulus * wraps))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DopplerSignature {
Subtracted,
Added,
}
impl DopplerSignature {
const fn sign(self) -> f64 {
match self {
Self::Subtracted => -1.0,
Self::Added => 1.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DopplerReference {
pub frequency: f64,
pub band: Band,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DopplerLink {
pub uplink: Band,
pub downlink: Band,
pub reference: DopplerReference,
pub signature: DopplerSignature,
pub count_interval: f64,
}
pub fn averaged_doppler<S: Scalar>(
table: &RampTable<'_>,
link: DopplerLink,
transmit_start: S,
transmit_end: S,
) -> Result<S, RadiometricError> {
if link.count_interval <= 0.0 || !link.count_interval.is_finite() {
return Err(RadiometricError::NonPositiveInterval {
seconds: link.count_interval,
});
}
let cycles = table.integral(transmit_start, transmit_end)?;
let reference_term =
S::from_f64(link.reference.band.turnaround_ratio(link.downlink) * link.reference.frequency);
let ramp_term = S::from_f64(
link.signature.sign() * link.uplink.turnaround_ratio(link.downlink) / link.count_interval,
) * cycles;
Ok(reference_term + ramp_term)
}
pub fn measured_frequency<S: Scalar>(
table: &RampTable<'_>,
uplink: Band,
downlink: Band,
transmit_epoch: S,
transmit_rate: S,
) -> Result<S, RadiometricError> {
let transmitted = table.frequency_at(transmit_epoch)?;
Ok(S::from_f64(uplink.turnaround_ratio(downlink)) * transmitted * transmit_rate)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Quasar {
pub right_ascension: f64,
pub declination: f64,
}
impl Quasar {
#[must_use]
pub fn direction(self) -> [f64; 3] {
let (sin_dec, cos_dec) = (libm::sin(self.declination), libm::cos(self.declination));
let (sin_ra, cos_ra) = (
libm::sin(self.right_ascension),
libm::cos(self.right_ascension),
);
[cos_dec * cos_ra, cos_dec * sin_ra, sin_dec]
}
}
#[must_use]
pub fn delta_dor<S: Scalar>(satellite: &[S; 6], geometry: &TdoaGeometry, quasar: Quasar) -> S {
let source = quasar.direction();
let first = geometry.first().station.position;
let second = geometry.second().station.position;
let projected = (second[0] - first[0]) * source[0]
+ (second[1] - first[1]) * source[1]
+ (second[2] - first[2]) * source[2];
tdoa(satellite, geometry) + S::from_f64(projected / SPEED_OF_LIGHT)
}
pub const SOLAR_RADIUS: f64 = 696e6;
pub const PLASMA_DELAY_COEFFICIENT: f64 = 40.3;
const ASTRONOMICAL_UNIT: f64 = 1.495_978_707e11;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CoronaTerm {
pub coefficient: f64,
pub exponent: f64,
}
pub const AKSIM_PAVLOV_2022: [CoronaTerm; 1] = [CoronaTerm {
coefficient: 1.31
* 5.97e6
* (ASTRONOMICAL_UNIT / SOLAR_RADIUS)
* (ASTRONOMICAL_UNIT / SOLAR_RADIUS),
exponent: 2.0,
}];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlasmaSignature {
GroupDelay,
PhaseAdvance,
}
impl PlasmaSignature {
const fn sign(self) -> f64 {
match self {
Self::GroupDelay => 1.0,
Self::PhaseAdvance => -1.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CoronaSeries<'a> {
terms: &'a [CoronaTerm],
}
impl<'a> CoronaSeries<'a> {
pub fn new(terms: &'a [CoronaTerm]) -> Result<Self, RadiometricError> {
if terms.is_empty() {
return Err(RadiometricError::EmptyCoronaSeries);
}
for term in terms {
if term.exponent <= 0.0 || !term.exponent.is_finite() {
return Err(RadiometricError::NonPositiveExponent {
exponent: term.exponent,
});
}
}
Ok(Self { terms })
}
#[must_use]
pub const fn terms(&self) -> &'a [CoronaTerm] {
self.terms
}
#[must_use]
pub fn electron_density<S: Scalar>(&self, radius: S) -> S {
let scaled = radius * S::from_f64(1.0 / SOLAR_RADIUS);
let mut total = S::from_f64(0.0);
for term in self.terms {
total = total + S::from_f64(term.coefficient) * scaled.powf(-term.exponent);
}
total
}
}
pub fn solar_corona_delay<S: Scalar>(
series: &CoronaSeries<'_>,
transmitter_from_sun: &[S; 3],
receiver_from_sun: &[S; 3],
frequency: f64,
signature: PlasmaSignature,
) -> Result<S, RadiometricError> {
if frequency <= 0.0 || !frequency.is_finite() {
return Err(RadiometricError::NonPositiveFrequency { hertz: frequency });
}
let to_transmitter = [
transmitter_from_sun[0] - receiver_from_sun[0],
transmitter_from_sun[1] - receiver_from_sun[1],
transmitter_from_sun[2] - receiver_from_sun[2],
];
let to_sun = [
-receiver_from_sun[0],
-receiver_from_sun[1],
-receiver_from_sun[2],
];
let alpha = angle_between(&to_sun, &to_transmitter);
let beta = angle_between(receiver_from_sun, transmitter_from_sun);
let impact = norm(receiver_from_sun) * alpha.sin();
if impact.value() < SOLAR_RADIUS || !impact.value().is_finite() {
return Err(RadiometricError::LineOfSightInsideTheSun {
impact_parameter: impact.value(),
});
}
let half_pi = S::from_f64(core::f64::consts::FRAC_PI_2);
let lower = alpha - half_pi;
let upper = beta + alpha - half_pi;
let mut column = S::from_f64(0.0);
for term in series.terms {
let scale =
S::from_f64(libm::pow(SOLAR_RADIUS, term.exponent)) * impact.powf(1.0 - term.exponent);
column = column
+ S::from_f64(term.coefficient)
* scale
* cosine_power_integral(lower, upper, term.exponent - 2.0);
}
Ok(S::from_f64(signature.sign() * PLASMA_DELAY_COEFFICIENT / (frequency * frequency)) * column)
}
fn norm<S: Scalar>(v: &[S; 3]) -> S {
(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt()
}
fn angle_between<S: Scalar>(a: &[S; 3], b: &[S; 3]) -> S {
let cross = [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
let dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
norm(&cross).atan2(dot)
}
fn cosine_power_integral<S: Scalar>(lower: S, upper: S, power: f64) -> S {
match integer_power(power) {
Some(n) => integer_cosine_power_integral(lower, upper, n),
None => tanh_sinh_cosine_power_integral(lower, upper, power),
}
}
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "the guard immediately preceding admits only whole numbers in [0, 64]"
)]
#[expect(
clippy::float_cmp,
reason = "exact integrality is the question being asked"
)]
fn integer_power(power: f64) -> Option<u32> {
((0.0..=64.0).contains(&power) && libm::trunc(power) == power).then_some(power as u32)
}
fn integer_cosine_power_integral<S: Scalar>(lower: S, upper: S, power: u32) -> S {
let parity = power % 2;
let mut integral = if parity == 0 {
upper - lower
} else {
upper.sin() - lower.sin()
};
for n in (parity..=power).step_by(2).skip(1) {
let order = f64::from(n);
let boundary = |x: S| x.cos().powf(order - 1.0) * x.sin() * S::from_f64(1.0 / order);
integral =
boundary(upper) - boundary(lower) + S::from_f64((order - 1.0) / order) * integral;
}
integral
}
const TANH_SINH_STEP: f64 = 0.0625;
const TANH_SINH_HALF_NODES: i32 = 52;
fn tanh_sinh_cosine_power_integral<S: Scalar>(lower: S, upper: S, power: f64) -> S {
let half = (upper - lower) * S::from_f64(0.5);
let middle = (upper + lower) * S::from_f64(0.5);
let mut total = S::from_f64(0.0);
for k in -TANH_SINH_HALF_NODES..=TANH_SINH_HALF_NODES {
let t = f64::from(k) * TANH_SINH_STEP;
let u = core::f64::consts::FRAC_PI_2 * libm::sinh(t);
let node = libm::tanh(u);
let weight = core::f64::consts::FRAC_PI_2 * libm::cosh(t) / (libm::cosh(u) * libm::cosh(u));
let theta = middle + half * S::from_f64(node);
total = total + S::from_f64(weight) * theta.cos().powf(power);
}
half * total * S::from_f64(TANH_SINH_STEP)
}
#[cfg(test)]
mod tests {
#![allow(clippy::float_cmp, clippy::unwrap_used)]
use super::*;
use crate::multistatic::Terminal;
use spacelab_autodiff::Dual;
const TUDAT_RAMPS: [RampSegment; 4] = [
RampSegment {
start: 1.0,
end: 5.0,
start_frequency: 10.0,
rate: 1.0,
},
RampSegment {
start: 5.0,
end: 9.0,
start_frequency: 5.0,
rate: 2.0,
},
RampSegment {
start: 9.0,
end: 10.0,
start_frequency: 10.0,
rate: 1.0,
},
RampSegment {
start: 10.0,
end: 15.0,
start_frequency: 2.0,
rate: 3.0,
},
];
fn tudat_table() -> RampTable<'static> {
RampTable::new(&TUDAT_RAMPS).unwrap()
}
#[test]
fn the_ramp_integral_reproduces_tudats_own_trapezoids() {
let table = tudat_table();
for (from, to, expected) in [
(2.0, 4.0, 2.0 * (11.0 + 13.0) / 2.0),
(5.0, 7.0, 2.0 * (5.0 + 9.0) / 2.0),
(7.0, 9.0, 2.0 * (9.0 + 13.0) / 2.0),
(5.0, 9.0, 4.0 * (5.0 + 13.0) / 2.0),
(
2.0,
13.0,
(3.0 * (11.0 + 14.0)
+ 4.0 * (5.0 + 13.0)
+ 1.0 * (11.0 + 10.0)
+ 3.0 * (2.0 + 11.0))
/ 2.0,
),
] {
let got: f64 = table.integral(from, to).unwrap();
assert!(
(got - expected).abs() <= 8.0 * f64::EPSILON * expected.abs(),
"integral({from}, {to}) = {got}, Tudat's trapezoid is {expected}"
);
}
}
#[test]
fn a_shared_boundary_belongs_to_the_ramp_that_is_starting() {
let table = tudat_table();
for (epoch, expected) in [
(1.0, 10.0),
(2.0, 11.0),
(5.0, 5.0),
(9.0, 10.0),
(13.0, 11.0),
(15.0, 17.0),
] {
assert_eq!(
table.frequency_at(epoch).unwrap(),
expected,
"frequency at {epoch}"
);
}
assert_eq!(table.first(), 1.0);
assert_eq!(table.last(), 15.0);
assert_eq!(table.segments().len(), 4);
}
#[test]
fn every_turnaround_ratio_is_moyers_table() {
for (up, down, expected) in [
(Band::S, Band::S, 240.0 / 221.0),
(Band::S, Band::X, 880.0 / 221.0),
(Band::S, Band::Ka, 3344.0 / 221.0),
(Band::X, Band::S, 240.0 / 749.0),
(Band::X, Band::X, 880.0 / 749.0),
(Band::X, Band::Ka, 3344.0 / 749.0),
(Band::Ka, Band::S, 240.0 / 3599.0),
(Band::Ka, Band::X, 880.0 / 3599.0),
(Band::Ka, Band::Ka, 3344.0 / 3599.0),
] {
assert_eq!(
up.turnaround_ratio(down),
expected,
"{up:?} up, {down:?} down"
);
}
assert_ne!(
Band::X.turnaround_ratio(Band::S),
Band::S.turnaround_ratio(Band::X)
);
assert_ne!(
CASSINI_KA_TURNAROUND_RATIO,
Band::Ka.turnaround_ratio(Band::Ka)
);
assert_eq!(CASSINI_KA_TURNAROUND_RATIO, 14.0 / 15.0);
}
#[test]
fn the_range_conversion_factor_is_moyers_three_cases() {
assert_eq!(Band::S.range_conversion_factor(), 0.5);
assert_eq!(Band::X.range_conversion_factor(), 221.0 / (749.0 * 2.0));
assert_eq!(Band::Ka.range_conversion_factor(), 221.0 / (3599.0 * 2.0));
}
#[test]
fn a_constant_exciter_makes_range_units_the_round_trip_times_the_scale() {
let flat = [RampSegment {
start: 0.0,
end: 1_000.0,
start_frequency: 7.2e9,
rate: 0.0,
}];
let table = RampTable::new(&flat).unwrap();
let (transmit, receive) = (10.0, 410.0);
let expected = Band::X.range_conversion_factor() * 7.2e9 * (receive - transmit);
let modulus = range_modulus(30).unwrap();
let got: f64 = sequential_range(&table, Band::X, transmit, receive, 30).unwrap();
let unwrapped = got + modulus * libm::floor(expected / modulus);
assert!(
(unwrapped - expected).abs() <= 1e-6 * expected,
"range units {unwrapped} against the closed form {expected}"
);
assert!(
got >= 0.0 && got < modulus,
"the observable lies in one period"
);
}
#[test]
fn the_ranging_modulus_is_two_to_the_component_plus_six() {
assert_eq!(range_modulus(0).unwrap(), 64.0);
assert_eq!(range_modulus(-6).unwrap(), 1.0);
assert_eq!(range_modulus(14).unwrap(), 1_048_576.0);
assert_eq!(
range_modulus(1_018),
Err(RadiometricError::UnrepresentableModulus { component: 1_018 })
);
assert_eq!(range_modulus(-1_080).unwrap(), libm::exp2(-1074.0));
assert_eq!(
range_modulus(-1_081),
Err(RadiometricError::UnrepresentableModulus { component: -1_081 })
);
}
#[test]
fn the_integrals_derivative_is_the_frequency_at_the_moving_endpoint() {
let table = tudat_table();
let from = Dual::<1>::constant(5.5);
let to = Dual::<1>::variable(7.5, 0);
let integral = table.integral(from, to).unwrap();
let expected = table.frequency_at(7.5).unwrap();
assert!(
(integral.grad()[0] - expected).abs() < 1e-12,
"d/d(to) = {}, f_T(7.5) = {expected}",
integral.grad()[0]
);
let from = Dual::<1>::variable(5.5, 0);
let to = Dual::<1>::constant(7.5);
let integral = table.integral(from, to).unwrap();
let expected = table.frequency_at(5.5).unwrap();
assert!(
(integral.grad()[0] + expected).abs() < 1e-12,
"d/d(from) = {}, −f_T(5.5) = {}",
integral.grad()[0],
-expected
);
let from = Dual::<1>::constant(5.5);
let to = Dual::<1>::variable(9.0, 0);
let integral = table.integral(from, to).unwrap();
assert!(
(integral.grad()[0] - 13.0).abs() < 1e-12,
"d/d(to) at a segment boundary = {}, the left limit is 13",
integral.grad()[0]
);
assert_eq!(table.frequency_at(9.0).unwrap(), 10.0);
let from = Dual::<1>::variable(5.0, 0);
let to = Dual::<1>::constant(7.5);
let integral = table.integral(from, to).unwrap();
assert!(
(integral.grad()[0] + 5.0).abs() < 1e-12,
"d/d(from) at a segment boundary = {}, and −f_T(5) is −5",
integral.grad()[0]
);
}
#[test]
fn a_doppler_count_over_a_flat_exciter_is_the_two_terms_by_hand() {
let flat = [RampSegment {
start: 0.0,
end: 10_000.0,
start_frequency: 7.15e9,
rate: 0.0,
}];
let table = RampTable::new(&flat).unwrap();
let link = DopplerLink {
uplink: Band::X,
downlink: Band::X,
reference: DopplerReference {
frequency: 7.15e9,
band: Band::X,
},
signature: DopplerSignature::Subtracted,
count_interval: 60.0,
};
let quiet: f64 = averaged_doppler(&table, link, 100.0, 160.0).unwrap();
assert!(
quiet.abs() < 1e-3,
"a range rate of zero should give no count, got {quiet}"
);
let stretched: f64 = averaged_doppler(&table, link, 100.0, 160.001).unwrap();
let expected = -Band::X.turnaround_ratio(Band::X) * 7.15e9 * 0.001 / 60.0;
assert!(
(stretched - expected).abs() < 1e-6 * expected.abs(),
"count {stretched} against the hand-formed {expected}"
);
let added = DopplerLink {
signature: DopplerSignature::Added,
..link
};
let other: f64 = averaged_doppler(&table, added, 100.0, 160.001).unwrap();
let reference_term = Band::X.turnaround_ratio(Band::X) * 7.15e9;
assert!(
(other + stretched - 2.0 * reference_term).abs() < 1e-3,
"the two conventions straddle the reference term"
);
}
#[test]
fn the_reference_band_is_not_the_transmitted_band() {
let flat = [RampSegment {
start: 0.0,
end: 10_000.0,
start_frequency: 7.15e9,
rate: 0.0,
}];
let table = RampTable::new(&flat).unwrap();
let base = DopplerLink {
uplink: Band::X,
downlink: Band::X,
reference: DopplerReference {
frequency: 2.1e9,
band: Band::S,
},
signature: DopplerSignature::Subtracted,
count_interval: 60.0,
};
let swapped = DopplerLink {
reference: DopplerReference {
frequency: 2.1e9,
band: Band::X,
},
..base
};
let a: f64 = averaged_doppler(&table, base, 100.0, 160.0).unwrap();
let b: f64 = averaged_doppler(&table, swapped, 100.0, 160.0).unwrap();
let expected =
(Band::S.turnaround_ratio(Band::X) - Band::X.turnaround_ratio(Band::X)) * 2.1e9;
assert!(
(a - b - expected).abs() < 1e-3,
"swapping the reference band moved the count by {}, expected {expected}",
a - b
);
}
#[test]
fn a_gap_between_two_ramps_is_reported_rather_than_interpolated() {
let gapped = [
RampSegment {
start: 0.0,
end: 5.0,
start_frequency: 100.0,
rate: 0.0,
},
RampSegment {
start: 7.0,
end: 12.0,
start_frequency: 100.0,
rate: 0.0,
},
];
let table = RampTable::new(&gapped).unwrap();
assert_eq!(
table.integral(1.0, 9.0),
Err(RadiometricError::EpochOutsideRampTable {
epoch: 5.0,
first: 0.0,
last: 12.0
})
);
assert!(table.integral(1.0, 4.0).is_ok());
assert!(table.integral(7.5, 9.0).is_ok());
assert!(matches!(
table.frequency_at(6.0),
Err(RadiometricError::EpochOutsideRampTable { .. })
));
assert_eq!(
tudat_table().integral(13.0, 20.0),
Err(RadiometricError::EpochOutsideRampTable {
epoch: 15.0,
first: 1.0,
last: 15.0
})
);
}
#[test]
fn a_table_that_could_answer_twice_is_refused_at_construction() {
assert_eq!(RampTable::new(&[]), Err(RadiometricError::EmptyRampTable));
let backwards = [RampSegment {
start: 5.0,
end: 1.0,
start_frequency: 1.0,
rate: 0.0,
}];
assert_eq!(
RampTable::new(&backwards),
Err(RadiometricError::RampTableNotOrdered { index: 0 })
);
let degenerate = [RampSegment {
start: 5.0,
end: 5.0,
start_frequency: 1.0,
rate: 0.0,
}];
assert_eq!(
RampTable::new(°enerate),
Err(RadiometricError::RampTableNotOrdered { index: 0 })
);
let overlapping = [
RampSegment {
start: 0.0,
end: 5.0,
start_frequency: 1.0,
rate: 0.0,
},
RampSegment {
start: 4.0,
end: 9.0,
start_frequency: 2.0,
rate: 0.0,
},
];
assert_eq!(
RampTable::new(&overlapping),
Err(RadiometricError::RampTableNotOrdered { index: 1 })
);
let touching = [
RampSegment {
start: 0.0,
end: 5.0,
start_frequency: 1.0,
rate: 0.0,
},
RampSegment {
start: 5.0,
end: 9.0,
start_frequency: 2.0,
rate: 0.0,
},
];
assert!(RampTable::new(&touching).is_ok());
let nan = [RampSegment {
start: f64::NAN,
end: 5.0,
start_frequency: 1.0,
rate: 0.0,
}];
assert_eq!(
RampTable::new(&nan),
Err(RadiometricError::RampTableNotOrdered { index: 0 })
);
}
#[test]
fn an_interval_that_does_not_run_forwards_is_refused() {
let table = tudat_table();
assert_eq!(
table.integral(7.0, 7.0),
Err(RadiometricError::NonPositiveInterval { seconds: 0.0 })
);
assert_eq!(
table.integral(9.0, 7.0),
Err(RadiometricError::NonPositiveInterval { seconds: -2.0 })
);
assert!(matches!(
table.integral(f64::NAN, 7.0),
Err(RadiometricError::NonPositiveInterval { .. })
));
let link = DopplerLink {
uplink: Band::X,
downlink: Band::X,
reference: DopplerReference {
frequency: 7.15e9,
band: Band::X,
},
signature: DopplerSignature::Subtracted,
count_interval: 0.0,
};
assert_eq!(
averaged_doppler(&table, link, 2.0, 4.0),
Err(RadiometricError::NonPositiveInterval { seconds: 0.0 })
);
}
fn conjunction(impact: f64) -> ([f64; 3], [f64; 3]) {
const ALONG: [f64; 3] = [2.0 / 7.0, 3.0 / 7.0, 6.0 / 7.0];
let across = [3.0, 6.0, -4.0].map(|c: f64| c / libm::sqrt(61.0));
let depth = -1.5 * ASTRONOMICAL_UNIT;
let base = ASTRONOMICAL_UNIT - depth;
let offset =
impact * base / libm::sqrt(ASTRONOMICAL_UNIT * ASTRONOMICAL_UNIT - impact * impact);
let mut receiver = [0.0; 3];
let mut transmitter = [0.0; 3];
for axis in 0..3 {
receiver[axis] = ASTRONOMICAL_UNIT * ALONG[axis];
transmitter[axis] = depth * ALONG[axis] + offset * across[axis];
}
(receiver, transmitter)
}
fn column_by_quadrature(series: &CoronaSeries<'_>, from: &[f64; 3], to: &[f64; 3]) -> f64 {
const INTERVALS: u32 = 200_000;
let count = f64::from(INTERVALS);
let step = [
(to[0] - from[0]) / count,
(to[1] - from[1]) / count,
(to[2] - from[2]) / count,
];
let length = libm::sqrt(
(to[0] - from[0]) * (to[0] - from[0])
+ (to[1] - from[1]) * (to[1] - from[1])
+ (to[2] - from[2]) * (to[2] - from[2]),
);
let at = |i: u32| {
let f = f64::from(i);
let point = [
from[0] + step[0] * f,
from[1] + step[1] * f,
from[2] + step[2] * f,
];
let r = libm::sqrt(point[0] * point[0] + point[1] * point[1] + point[2] * point[2]);
series.electron_density(r)
};
let mut total = at(0) + at(INTERVALS);
for i in 1..INTERVALS {
total += at(i) * if i % 2 == 0 { 2.0 } else { 4.0 };
}
total * length / (3.0 * count)
}
#[test]
fn the_corona_closed_form_matches_a_line_integral_taken_in_arc_length() {
let (receiver, transmitter) = conjunction(10.0 * SOLAR_RADIUS);
for exponent in [2.0, 3.0, 4.0, 6.0, 2.7] {
let terms = [CoronaTerm {
coefficient: AKSIM_PAVLOV_2022[0].coefficient,
exponent,
}];
let series = CoronaSeries::new(&terms).unwrap();
let expected = column_by_quadrature(&series, &transmitter, &receiver);
let delay: f64 = solar_corona_delay(
&series,
&transmitter,
&receiver,
8.4e9,
PlasmaSignature::GroupDelay,
)
.unwrap();
let column = delay * 8.4e9 * 8.4e9 / PLASMA_DELAY_COEFFICIENT;
assert!(
(column - expected).abs() < 1e-8 * expected,
"k = {exponent}: closed form {column:.9e} against the quadrature {expected:.9e}"
);
}
}
#[test]
fn the_column_does_not_depend_on_which_end_is_called_the_receiver() {
let (receiver, transmitter) = conjunction(4.0 * SOLAR_RADIUS);
let series = CoronaSeries::new(&AKSIM_PAVLOV_2022).unwrap();
let forward: f64 = solar_corona_delay(
&series,
&transmitter,
&receiver,
8.4e9,
PlasmaSignature::GroupDelay,
)
.unwrap();
let reversed: f64 = solar_corona_delay(
&series,
&receiver,
&transmitter,
8.4e9,
PlasmaSignature::GroupDelay,
)
.unwrap();
assert!(
(forward - reversed).abs() < 1e-12 * forward,
"{forward} one way, {reversed} the other"
);
}
#[test]
fn the_two_integration_paths_agree_where_both_apply() {
for (lower, upper) in [(-0.7, 0.4), (-1.55, 1.55), (0.2, 1.5), (-1.5, -0.1)] {
for power in 0..=6u32 {
let exact = integer_cosine_power_integral(lower, upper, power);
let quadrature = tanh_sinh_cosine_power_integral(lower, upper, f64::from(power));
let floor = if exact.abs() > 1e-12 {
exact.abs()
} else {
1e-12
};
assert!(
(exact - quadrature).abs() < 1e-12 * floor,
"cos^{power} over [{lower}, {upper}]: {exact} exact, {quadrature} by quadrature"
);
}
}
assert_eq!(integer_power(4.0), Some(4));
assert_eq!(integer_power(0.0), Some(0));
assert_eq!(integer_power(2.7), None);
assert_eq!(integer_power(-1.0), None);
assert_eq!(
integer_power(65.0),
None,
"the recursion bound is not open-ended"
);
assert_eq!(integer_power(f64::INFINITY), None);
}
#[test]
fn the_default_series_is_the_solar_winds_own_density_at_one_astronomical_unit() {
let series = CoronaSeries::new(&AKSIM_PAVLOV_2022).unwrap();
let at_one_au: f64 = series.electron_density(ASTRONOMICAL_UNIT);
assert!(
(at_one_au - 1.31 * 5.97e6).abs() < 1e-6 * 1.31 * 5.97e6,
"{at_one_au} m^-3 at 1 AU"
);
let at_two_au: f64 = series.electron_density(2.0 * ASTRONOMICAL_UNIT);
assert!((at_one_au / at_two_au - 4.0).abs() < 1e-9);
}
#[test]
fn the_delay_is_signed_by_the_observable_and_falls_as_one_over_frequency_squared() {
let (receiver, transmitter) = conjunction(6.0 * SOLAR_RADIUS);
let series = CoronaSeries::new(&AKSIM_PAVLOV_2022).unwrap();
let delay = |f, signature| -> f64 {
solar_corona_delay(&series, &transmitter, &receiver, f, signature).unwrap()
};
let group = delay(8.4e9, PlasmaSignature::GroupDelay);
let phase = delay(8.4e9, PlasmaSignature::PhaseAdvance);
assert!(group > 0.0, "a ranging observable is retarded, got {group}");
assert!(
(group + phase).abs() < 1e-12 * group,
"the two are equal and opposite"
);
let s_band = delay(2.3e9, PlasmaSignature::GroupDelay);
let ratio = (8.4e9 / 2.3e9) * (8.4e9 / 2.3e9);
assert!(
(s_band / group - ratio).abs() < 1e-12 * ratio,
"S/X delay ratio {} against {ratio}",
s_band / group
);
assert!(
(10.0..300.0).contains(&group),
"X-band delay at 6 R_sun is {group} m"
);
}
#[test]
fn a_line_of_sight_that_grazes_the_sun_is_refused_rather_than_extrapolated() {
let series = CoronaSeries::new(&AKSIM_PAVLOV_2022).unwrap();
let (receiver, transmitter) = conjunction(0.5 * SOLAR_RADIUS);
let refused = solar_corona_delay::<f64>(
&series,
&transmitter,
&receiver,
8.4e9,
PlasmaSignature::GroupDelay,
);
assert!(matches!(
refused,
Err(RadiometricError::LineOfSightInsideTheSun { .. })
));
let (receiver, transmitter) = conjunction(1.000_001 * SOLAR_RADIUS);
assert!(
solar_corona_delay::<f64>(
&series,
&transmitter,
&receiver,
8.4e9,
PlasmaSignature::GroupDelay
)
.is_ok()
);
let grazing = [0.0, SOLAR_RADIUS, 0.0];
let beyond = [1e11, SOLAR_RADIUS, 0.0];
assert!(
solar_corona_delay::<f64>(
&series,
&beyond,
&grazing,
8.4e9,
PlasmaSignature::GroupDelay
)
.is_ok(),
"the boundary itself is inside the domain"
);
}
#[test]
fn a_series_that_does_not_converge_and_a_frequency_that_does_not_exist_are_refused() {
assert_eq!(
CoronaSeries::new(&[]),
Err(RadiometricError::EmptyCoronaSeries)
);
for exponent in [0.0, -2.0, f64::NAN] {
let terms = [CoronaTerm {
coefficient: 1.0,
exponent,
}];
assert!(matches!(
CoronaSeries::new(&terms),
Err(RadiometricError::NonPositiveExponent { .. })
));
}
let series = CoronaSeries::new(&AKSIM_PAVLOV_2022).unwrap();
let (receiver, transmitter) = conjunction(6.0 * SOLAR_RADIUS);
for frequency in [0.0, -8.4e9, f64::NAN, f64::INFINITY] {
assert!(matches!(
solar_corona_delay::<f64>(
&series,
&transmitter,
&receiver,
frequency,
PlasmaSignature::GroupDelay
),
Err(RadiometricError::NonPositiveFrequency { .. })
));
}
assert_eq!(series.terms().len(), 1);
}
#[test]
fn the_measured_frequency_and_the_doppler_count_add_up_to_the_reference() {
let flat = [RampSegment {
start: 0.0,
end: 10_000.0,
start_frequency: 7.15e9,
rate: 0.0,
}];
let table = RampTable::new(&flat).unwrap();
let link = DopplerLink {
uplink: Band::X,
downlink: Band::X,
reference: DopplerReference {
frequency: 7.15e9,
band: Band::X,
},
signature: DopplerSignature::Subtracted,
count_interval: 60.0,
};
let ratio = Band::X.turnaround_ratio(Band::X);
for rate in [1.0, 1.0 - 1e-5, 1.0 + 3e-6] {
let instantaneous: f64 =
measured_frequency(&table, Band::X, Band::X, 100.0, rate).unwrap();
let counted: f64 = averaged_doppler(&table, link, 100.0, 100.0 + 60.0 * rate).unwrap();
let total = ratio * 7.15e9;
assert!(
(instantaneous + counted - total).abs() < 1e-3,
"rate {rate}: {instantaneous:.6} + {counted:.6} against {total:.6}"
);
}
let ramped = tudat_table();
let got: f64 = measured_frequency(&ramped, Band::S, Band::X, 7.0, 1.0).unwrap();
assert!(
(got - Band::S.turnaround_ratio(Band::X) * 9.0).abs() < 1e-12,
"{got}"
);
let swapped: f64 = measured_frequency(&ramped, Band::X, Band::S, 7.0, 1.0).unwrap();
assert!(swapped < got, "{swapped} against {got}");
assert!(matches!(
measured_frequency::<f64>(&ramped, Band::X, Band::X, 20.0, 1.0),
Err(RadiometricError::EpochOutsideRampTable { .. })
));
let epoch = Dual::<1>::variable(7.0, 0);
let derivative = measured_frequency(&ramped, Band::S, Band::X, epoch, Dual::constant(1.0))
.unwrap()
.grad()[0];
assert!(
(derivative - Band::S.turnaround_ratio(Band::X) * 2.0).abs() < 1e-12,
"d/d(transmit) = {derivative}"
);
}
const GOLDSTONE: [f64; 3] = [-2_353_621.4, -4_641_341.5, 3_677_052.3];
const CANBERRA: [f64; 3] = [-4_460_894.9, 2_682_361.5, -3_674_748.5];
fn baseline() -> TdoaGeometry {
TdoaGeometry::new(
0.0,
Terminal::fixed(GOLDSTONE, 1.0),
Terminal::fixed(CANBERRA, 1.0),
)
.unwrap()
}
#[test]
fn the_quasar_direction_is_the_unit_vector_the_catalogue_angles_name() {
for (ra, dec, expected) in [
(0.0, 0.0, [1.0, 0.0, 0.0]),
(core::f64::consts::FRAC_PI_2, 0.0, [0.0, 1.0, 0.0]),
(0.0, core::f64::consts::FRAC_PI_2, [0.0, 0.0, 1.0]),
] {
let got = Quasar {
right_ascension: ra,
declination: dec,
}
.direction();
for (a, b) in got.iter().zip(&expected) {
assert!((a - b).abs() < 1e-15, "{got:?} against {expected:?}");
}
}
let d = Quasar {
right_ascension: 2.71,
declination: -0.83,
}
.direction();
assert!((d[0] * d[0] + d[1] * d[1] + d[2] * d[2] - 1.0).abs() < 1e-15);
}
#[test]
fn delta_dor_vanishes_on_a_spacecraft_in_the_quasars_own_direction() {
let geometry = baseline();
let quasar = Quasar {
right_ascension: 1.3,
declination: 0.4,
};
let direction = quasar.direction();
let at = |range: f64| -> f64 {
let state = [
range * direction[0],
range * direction[1],
range * direction[2],
0.0,
0.0,
0.0,
];
delta_dor(&state, &geometry, quasar)
};
let near = at(1e11);
let far = at(4e11);
assert!(
((near / far).abs() - 4.0).abs() < 0.01,
"the residual should fall as 1/range: {near:.6e} at 1e11, {far:.6e} at 4e11"
);
let state = [
1e11 * direction[0],
1e11 * direction[1],
1e11 * direction[2],
0.0,
0.0,
0.0,
];
let raw: f64 = tdoa(&state, &geometry);
assert!(
raw.abs() > 1e4 * near.abs(),
"TDOA {raw:.6e} s against the differenced {near:.6e} s"
);
}
#[test]
fn the_far_field_limit_is_the_baseline_projected_on_the_angular_offset() {
let geometry = baseline();
let quasar = Quasar {
right_ascension: 1.3,
declination: 0.4,
};
let source = quasar.direction();
let offset = 1e-3;
let mut spacecraft = [
source[0] - offset * source[1],
source[1] + offset * source[0],
source[2],
];
let norm = libm::sqrt(
spacecraft[0] * spacecraft[0]
+ spacecraft[1] * spacecraft[1]
+ spacecraft[2] * spacecraft[2],
);
for component in &mut spacecraft {
*component /= norm;
}
let range = 1e14;
let state = [
range * spacecraft[0],
range * spacecraft[1],
range * spacecraft[2],
0.0,
0.0,
0.0,
];
let got: f64 = delta_dor(&state, &geometry, quasar);
let b = [
CANBERRA[0] - GOLDSTONE[0],
CANBERRA[1] - GOLDSTONE[1],
CANBERRA[2] - GOLDSTONE[2],
];
let expected = (b[0] * (source[0] - spacecraft[0])
+ b[1] * (source[1] - spacecraft[1])
+ b[2] * (source[2] - spacecraft[2]))
/ SPEED_OF_LIGHT;
assert!(
(got - expected).abs() < 1e-3 * expected.abs(),
"{got:.9e} s against the plane-wave {expected:.9e} s"
);
let raw: f64 = tdoa(&state, &geometry);
assert!(
raw.abs() > 1e2 * got.abs(),
"TDOA {raw:.6e} s should dwarf the differenced {got:.6e} s"
);
}
#[test]
fn the_corona_delay_and_delta_dor_carry_their_partials() {
let series = CoronaSeries::new(&AKSIM_PAVLOV_2022).unwrap();
let (receiver, transmitter) = conjunction(8.0 * SOLAR_RADIUS);
let corona = |r: &[f64; 3]| -> f64 {
let lifted = [
Dual::<1>::constant(r[0]),
Dual::<1>::constant(r[1]),
Dual::<1>::constant(r[2]),
];
let emitter = transmitter.map(Dual::<1>::constant);
solar_corona_delay(
&series,
&emitter,
&lifted,
8.4e9,
PlasmaSignature::GroupDelay,
)
.unwrap()
.value()
};
for axis in 0..3 {
let mut lifted = receiver.map(Dual::<1>::constant);
lifted[axis] = Dual::variable(receiver[axis], 0);
let emitter = transmitter.map(Dual::<1>::constant);
let analytic = solar_corona_delay(
&series,
&emitter,
&lifted,
8.4e9,
PlasmaSignature::GroupDelay,
)
.unwrap()
.grad()[0];
let step = 1e4;
let (mut up, mut down) = (receiver, receiver);
up[axis] += step;
down[axis] -= step;
let numeric = (corona(&up) - corona(&down)) / (2.0 * step);
assert!(
(analytic - numeric).abs() < 1e-5 * numeric.abs(),
"axis {axis}: AD {analytic:.9e} m/m against central difference {numeric:.9e}"
);
}
let geometry = baseline();
let quasar = Quasar {
right_ascension: 1.3,
declination: 0.4,
};
let direction = quasar.direction();
let range = 1e11;
let position = [
range * direction[0],
range * direction[1],
range * direction[2],
];
let b = [
CANBERRA[0] - GOLDSTONE[0],
CANBERRA[1] - GOLDSTONE[1],
CANBERRA[2] - GOLDSTONE[2],
];
let projected = b[0] * direction[0] + b[1] * direction[1] + b[2] * direction[2];
for axis in 0..3 {
let mut state = [Dual::<1>::constant(0.0); 6];
for (slot, x) in state.iter_mut().zip(&position) {
*slot = Dual::constant(*x);
}
state[axis] = Dual::variable(position[axis], 0);
let analytic = delta_dor(&state, &geometry, quasar).grad()[0];
let expected = -(b[axis] - projected * direction[axis]) / (range * SPEED_OF_LIGHT);
assert!(
(analytic - expected).abs() < 1e-3 * expected.abs(),
"axis {axis}: AD {analytic:.9e} s/m against the far-field {expected:.9e}"
);
}
}
#[test]
fn every_refusal_names_the_input_it_refused() {
use core::error::Error;
let cases: [(RadiometricError, &str); 9] = [
(RadiometricError::EmptyRampTable, "no segments"),
(RadiometricError::RampTableNotOrdered { index: 3 }, "3"),
(
RadiometricError::EpochOutsideRampTable {
epoch: 6.0,
first: 0.0,
last: 12.0,
},
"6",
),
(
RadiometricError::NonPositiveInterval { seconds: -2.0 },
"-2",
),
(
RadiometricError::UnrepresentableModulus { component: 1_018 },
"1018",
),
(RadiometricError::EmptyCoronaSeries, "no terms"),
(
RadiometricError::NonPositiveExponent { exponent: -2.5 },
"-2.5",
),
(RadiometricError::NonPositiveFrequency { hertz: 0.0 }, "0"),
(
RadiometricError::LineOfSightInsideTheSun {
impact_parameter: 3.5e8,
},
"350000000",
),
];
for (error, needle) in cases {
let rendered = format!("{error}");
assert!(
rendered.contains(needle),
"{rendered:?} does not name {needle:?}"
);
let dynamic: &dyn Error = &error;
assert!(dynamic.source().is_none());
}
}
}