Skip to main content

spacelab_constellation/
shell.rs

1//! Two-tier constellations for continuous surveillance of a spherical *shell* of near-Earth space —
2//! space situational awareness, where the targets are other orbiting objects, not the ground.
3//!
4//! Unlike ground coverage, the target is a sphere in space and a sensor's viewing zone is set by three
5//! limits: the half-cone `β` of the onboard sensor (measured from its boresight), the slant range `D`,
6//! and the minimum elevation `γ` of the satellite above the *target's* local horizon. A single Walker
7//! delta-tier covers one sphere; a **two-tier** system splits a thick shell between an inner and an
8//! outer tier, and is chosen to minimise the total launch characteristic velocity (СХС),
9//!
10//! ```text
11//! V(N, H, i) = N · [ √(μ/Rₑ · (Rₑ + 2H)/(Rₑ + H)) − ω Rₑ cos i ],
12//! ```
13//!
14//! the sum over the tiers of the per-satellite launch ΔV (Earth-rotation assist `ω Rₑ cos i`
15//! subtracted). This module provides the space-visibility test and the cost; the tier sizing is the
16//! optimisation the caller drives with them.
17
18use spacelab_core::{Angle, Vec3};
19
20use crate::walker::Walker;
21
22fn scale(v: Vec3, s: f64) -> Vec3 {
23    Vec3::new(v.x * s, v.y * s, v.z * s)
24}
25
26/// Whether a sensor satellite at `sat` observes a target point at `target` (both Earth-centred
27/// inertial, metres), under the three limits: the target lies within `half_cone` of the sensor
28/// `boresight`, the slant range is at most `range`, and the satellite sits at least `min_elevation`
29/// above the target's local horizon.
30#[must_use]
31pub fn observes(
32    sat: Vec3,
33    target: Vec3,
34    boresight: Vec3,
35    half_cone: Angle,
36    range: f64,
37    min_elevation: Angle,
38) -> bool {
39    let d = target - sat; // sat → target
40    let dist = d.norm();
41    if dist > range {
42        return false;
43    }
44    // Sensor half-cone: angle between the boresight and the target direction ≤ β.
45    if d.dot(boresight) < libm::cos(half_cone.radians()) * dist * boresight.norm() {
46        return false;
47    }
48    // Elevation of the satellite above the target's horizon: sin(el) = (sat − target)·t̂ / |sat − target|.
49    let t_hat = scale(target, 1.0 / target.norm());
50    let sin_el = -d.dot(t_hat) / dist;
51    sin_el >= libm::sin(min_elevation.radians())
52}
53
54/// The launch characteristic velocity (СХС) of a one-tier delta-system of `n` satellites at circular
55/// height `height` (m) and inclination — Nguyen's formula (10). `re` is the Earth radius, `earth_rate`
56/// its spin rate (rad/s).
57#[must_use]
58pub fn characteristic_velocity(
59    n: u32,
60    height: f64,
61    inclination: Angle,
62    mu: f64,
63    re: f64,
64    earth_rate: f64,
65) -> f64 {
66    let dv_star = libm::sqrt(mu / re * (re + 2.0 * height) / (re + height));
67    let v_omega = earth_rate * re * libm::cos(inclination.radians());
68    f64::from(n) * (dv_star - v_omega)
69}
70
71/// One tier of a shell-surveillance system: a Walker delta-system plus its sensor limits. The
72/// boresight is the satellite nadir (`−r̂`), so the tier watches the shell below it.
73#[derive(Clone, Copy, Debug)]
74pub struct ShellTier {
75    /// The tier's delta-system (circular, common altitude and inclination).
76    pub walker: Walker,
77    /// Sensor half-cone `β` from nadir.
78    pub half_cone: Angle,
79    /// Maximum slant range `D`, metres.
80    pub range: f64,
81    /// Minimum elevation `γ` of the satellite above a target's horizon.
82    pub min_elevation: Angle,
83}
84
85impl ShellTier {
86    /// Emit the tier's satellite elements (the underlying Walker).
87    pub fn generate<E: FnMut(spacelab_elements::KeplerianElements)>(&self, emit: E) {
88        self.walker.generate(emit);
89    }
90
91    /// This tier's launch characteristic velocity (СХС), taking the circular height as
92    /// `semi_major_axis − re`.
93    #[must_use]
94    pub fn characteristic_velocity(&self, mu: f64, re: f64, earth_rate: f64) -> f64 {
95        characteristic_velocity(
96            self.walker.total(),
97            self.walker.semi_major_axis - re,
98            self.walker.inclination,
99            mu,
100            re,
101            earth_rate,
102        )
103    }
104}
105
106/// A two-tier shell-surveillance system: an inner and an outer delta-tier whose union continuously
107/// watches a spherical shell of space.
108#[derive(Clone, Copy, Debug)]
109pub struct TwoTierShell {
110    /// The inner (lower-altitude) tier.
111    pub inner: ShellTier,
112    /// The outer (higher-altitude) tier.
113    pub outer: ShellTier,
114}
115
116impl TwoTierShell {
117    /// Total number of satellites across both tiers.
118    #[must_use]
119    pub const fn total(&self) -> u32 {
120        self.inner.walker.total() + self.outer.walker.total()
121    }
122
123    /// The combined launch characteristic velocity (СХС) — the optimisation objective.
124    #[must_use]
125    pub fn total_characteristic_velocity(&self, mu: f64, re: f64, earth_rate: f64) -> f64 {
126        self.inner.characteristic_velocity(mu, re, earth_rate)
127            + self.outer.characteristic_velocity(mu, re, earth_rate)
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    #![allow(clippy::float_cmp)]
134    use super::*;
135    use crate::walker::WalkerPattern;
136    use spacelab_elements::KeplerianElements;
137
138    const MU: f64 = 3.986_004_415e14;
139    const RE: f64 = 6_371e3; // Nguyen's mean Earth radius
140    const OMEGA_E: f64 = 7.292_115_9e-5;
141    const TAU: f64 = core::f64::consts::TAU;
142
143    /// A unit vector with no zero component, and one perpendicular to it.
144    fn frame() -> (Vec3, Vec3) {
145        let raw_up = Vec3::new(0.3, 0.5, 0.8);
146        let inv_up = 1.0 / raw_up.norm();
147        let up = Vec3::new(raw_up.x * inv_up, raw_up.y * inv_up, raw_up.z * inv_up);
148        let raw_east = Vec3::new(0.5, -0.3, 0.0); // up · east = 0.15 − 0.15 = 0
149        let inv_east = 1.0 / raw_east.norm();
150        let east = Vec3::new(
151            raw_east.x * inv_east,
152            raw_east.y * inv_east,
153            raw_east.z * inv_east,
154        );
155        (up, east)
156    }
157
158    #[test]
159    fn the_elevation_gate_is_an_angle_and_not_merely_a_sign() {
160        // The existing coverage test uses `min_elevation = 0`, which reduces the gate to a sign
161        // test — and every surviving mutant here rescales `sin_el` by a large *positive* factor, so
162        // the sign is exactly what they preserve. Build a geometry whose elevation is known by
163        // construction and place the mask strictly between two of them.
164        let (up, east) = frame();
165        let radius = RE + 500e3;
166        let target = Vec3::new(up.x * radius, up.y * radius, up.z * radius);
167        let range = 2_000e3;
168        let slant = 800e3;
169        let mask = Angle::from_radians(10.0_f64.to_radians());
170
171        for (el_deg, want) in [(5.0_f64, false), (15.0_f64, true)] {
172            let (sin_el, cos_el) = libm::sincos(el_deg.to_radians());
173            // `look` leaves the target at elevation `el_deg`: sin_el = look·û = sin(el), exactly.
174            let look = Vec3::new(
175                sin_el * up.x + cos_el * east.x,
176                sin_el * up.y + cos_el * east.y,
177                sin_el * up.z + cos_el * east.z,
178            );
179            let sat = Vec3::new(
180                target.x + slant * look.x,
181                target.y + slant * look.y,
182                target.z + slant * look.z,
183            );
184            let boresight = Vec3::new(-look.x, -look.y, -look.z);
185            let got = observes(
186                sat,
187                target,
188                boresight,
189                Angle::from_radians(60.0_f64.to_radians()),
190                range,
191                mask,
192            );
193            assert_eq!(got, want, "elevation {el_deg} deg against a {mask:?} mask");
194        }
195    }
196
197    #[test]
198    fn the_cone_gate_measures_an_angle_against_a_boresight_of_any_length() {
199        // The cone assertion in the existing test is vacuous — its "outside" case is refused by the
200        // range gate before the cone is ever evaluated — and both call sites pass a unit boresight,
201        // which is the one length at which `* boresight.norm()` and `/ boresight.norm()` agree. Use
202        // a boresight of length two and straddle the half-cone.
203        let (up, east) = frame();
204        let radius = RE + 1_200e3;
205        let sat = Vec3::new(up.x * radius, up.y * radius, up.z * radius);
206        let nadir = Vec3::new(-2.0 * up.x, -2.0 * up.y, -2.0 * up.z); // length two, on purpose
207        let half_cone = Angle::from_radians(20.0_f64.to_radians());
208        let slant = 900e3;
209
210        for (off_deg, want) in [(12.0_f64, true), (28.0_f64, false)] {
211            let (sin_off, cos_off) = libm::sincos(off_deg.to_radians());
212            // A direction `off_deg` from nadir, so the cone test is decided at a known angle.
213            let los = Vec3::new(
214                slant * (-cos_off * up.x + sin_off * east.x),
215                slant * (-cos_off * up.y + sin_off * east.y),
216                slant * (-cos_off * up.z + sin_off * east.z),
217            );
218            let target = Vec3::new(sat.x + los.x, sat.y + los.y, sat.z + los.z);
219            let got = observes(
220                sat,
221                target,
222                nadir,
223                half_cone,
224                2_000e3,
225                Angle::from_radians(-90.0_f64.to_radians()),
226            );
227            assert_eq!(got, want, "{off_deg} deg off a 20 deg half-cone");
228        }
229    }
230
231    #[test]
232    fn both_boundaries_are_inclusive_at_the_limit_they_name() {
233        // On the +z axis every quantity is exact: the slant range is the coordinate difference, the
234        // boresight dot product is `2·L`, and `cos(0)·L·‖b‖` is the same `2·L` bit for bit. So this
235        // fixture sits precisely on both thresholds at once and says which way each falls.
236        let l = 400e3;
237        let sat = Vec3::new(0.0, 0.0, RE + l);
238        let target = Vec3::new(0.0, 0.0, RE);
239        let nadir = Vec3::new(0.0, 0.0, -2.0);
240        let zero_cone = Angle::from_radians(0.0);
241        let horizon = Angle::from_radians(0.0);
242        assert!(
243            observes(sat, target, nadir, zero_cone, l, horizon),
244            "a target exactly at the range limit and exactly on the boresight is not observed"
245        );
246        assert!(
247            !observes(sat, target, nadir, zero_cone, l - 1.0, horizon),
248            "a target beyond the range limit is observed"
249        );
250    }
251
252    #[test]
253    fn a_tier_reports_the_launch_cost_of_the_walker_it_wraps() {
254        // Only ever checked by `chv.is_finite() && chv > 0.0`, which `1.0` also satisfies. Compare
255        // against the free function — itself pinned by the energy balance above — at a *literal*
256        // altitude, so that reading the height as `a + re` rather than `a − re` is observable.
257        let height = 3_000e3;
258        let inc = Angle::from_radians(65.0_f64.to_radians());
259        let tier = |planes, per_plane, h: f64| ShellTier {
260            walker: Walker {
261                pattern: WalkerPattern::Delta,
262                inclination: inc,
263                planes,
264                per_plane,
265                phasing: 0,
266                semi_major_axis: RE + h,
267                mu: MU,
268            },
269            half_cone: Angle::from_radians(30.0_f64.to_radians()),
270            range: 5_000e3,
271            min_elevation: Angle::from_radians(0.0),
272        };
273
274        let inner = tier(4, 3, height);
275        let want_inner = characteristic_velocity(12, height, inc, MU, RE, OMEGA_E);
276        let got_inner = inner.characteristic_velocity(MU, RE, OMEGA_E);
277        assert!(
278            (got_inner - want_inner).abs() < 1e-9,
279            "tier cost {got_inner} against {want_inner}"
280        );
281
282        let outer = tier(6, 2, 8_000e3);
283        let want_outer = characteristic_velocity(12, 8_000e3, inc, MU, RE, OMEGA_E);
284        let shell = TwoTierShell { inner, outer };
285        let total = shell.total_characteristic_velocity(MU, RE, OMEGA_E);
286        assert!(
287            (total - (want_inner + want_outer)).abs() < 1e-9,
288            "shell cost {total} against {want_inner} + {want_outer}"
289        );
290        assert!(
291            total > want_inner && total > want_outer,
292            "the total is not above either tier"
293        );
294    }
295
296    #[test]
297    fn characteristic_velocity_matches_the_energy_balance() {
298        // ΔV* is defined by equating launch-pad and orbit energy:
299        // (ΔV*)²/2 − μ/Rₑ = V_H²/2 − μ/(Rₑ+H), with V_H² = μ/(Rₑ+H).
300        let h = 1_000e3;
301        let inc = Angle::from_radians(60.0_f64.to_radians());
302        let v_h2 = MU / (RE + h);
303        let dv_star = (2.0 * (v_h2 / 2.0 - MU / (RE + h) + MU / RE)).sqrt();
304        let expect = 12.0 * (dv_star - OMEGA_E * RE * (60.0_f64.to_radians()).cos());
305        let got = characteristic_velocity(12, h, inc, MU, RE, OMEGA_E);
306        assert!((got - expect).abs() < 1e-6, "{got} vs {expect}");
307        // Higher orbits and lower (rotation-assisted) inclinations cost more / less as expected.
308        assert!(
309            characteristic_velocity(1, 2_000e3, inc, MU, RE, OMEGA_E)
310                > characteristic_velocity(1, 500e3, inc, MU, RE, OMEGA_E)
311        );
312    }
313
314    #[test]
315    fn observes_honours_cone_range_and_elevation() {
316        // Sensor satellite 1500 km up on the +x axis, looking down (nadir = −x̂).
317        let sat = Vec3::new(RE + 1_500e3, 0.0, 0.0);
318        let nadir = Vec3::new(-1.0, 0.0, 0.0);
319        let cone = Angle::from_radians(40.0_f64.to_radians());
320        let range = 3_000e3;
321        let gamma = Angle::from_radians(5.0_f64.to_radians());
322
323        // Target straight below on a 700 km sphere: in cone, in range, high elevation → visible.
324        let below = Vec3::new(RE + 700e3, 0.0, 0.0);
325        assert!(observes(sat, below, nadir, cone, range, gamma));
326        // Same sphere but pushed sideways out of the cone → not visible.
327        let a = 30.0_f64.to_radians();
328        let side = Vec3::new((RE + 700e3) * a.cos(), (RE + 700e3) * a.sin(), 0.0);
329        assert!(!observes(sat, side, nadir, cone, range, gamma));
330        // Straight below but beyond the range gate → not visible.
331        assert!(!observes(sat, below, nadir, cone, 500e3, gamma));
332    }
333
334    fn fibonacci_sphere(n: u32, radius: f64) -> Vec<Vec3> {
335        let ga = core::f64::consts::PI * (3.0 - 5.0_f64.sqrt());
336        (0..n)
337            .map(|k| {
338                let z = 1.0 - 2.0 * (f64::from(k) + 0.5) / f64::from(n);
339                let r = (1.0 - z * z).max(0.0).sqrt();
340                let phi = ga * f64::from(k);
341                Vec3::new(radius * r * phi.cos(), radius * r * phi.sin(), radius * z)
342            })
343            .collect()
344    }
345
346    fn tier(planes: u32, per_plane: u32, alt: f64, cone_deg: f64) -> ShellTier {
347        ShellTier {
348            walker: Walker {
349                pattern: WalkerPattern::Delta,
350                inclination: Angle::from_radians(70.0_f64.to_radians()),
351                planes,
352                per_plane,
353                phasing: 1,
354                semi_major_axis: RE + alt,
355                mu: MU,
356            },
357            half_cone: Angle::from_radians(cone_deg.to_radians()),
358            range: 12_000e3,
359            min_elevation: Angle::from_radians(0.0),
360        }
361    }
362
363    fn tier_positions(t: &ShellTier, time: f64) -> Vec<Vec3> {
364        let mut v = Vec::new();
365        t.generate(|e: KeplerianElements| v.push(e.propagate(time).to_state().0));
366        v
367    }
368
369    #[test]
370    fn two_tiers_continuously_watch_a_space_shell() {
371        // Two dense delta-tiers above a shell, both looking down, together keep every point of the
372        // shell in view of at least one satellite at all sampled times. This exercises the space
373        // visibility geometry end-to-end (targets are spheres in space, not the ground).
374        let system = TwoTierShell {
375            inner: tier(9, 9, 3_000e3, 55.0),
376            outer: tier(8, 8, 6_000e3, 55.0),
377        };
378        // A shell from 600 to 1200 km altitude — below both tiers, so the nadir boresight and the
379        // elevation constraint are satisfiable.
380        let shell_radii = [RE + 600e3, RE + 900e3, RE + 1_200e3];
381        let period = TAU * ((RE + 3_000e3).powi(3) / MU).sqrt(); // inner-tier period
382        let tiers = [system.inner, system.outer];
383
384        let mut worst_covered = true;
385        for it in 0..40 {
386            let time = period * f64::from(it) / 40.0;
387            let sats: Vec<(Vec3, &ShellTier)> = tiers
388                .iter()
389                .flat_map(|t| tier_positions(t, time).into_iter().map(move |p| (p, t)))
390                .collect();
391            for &radius in &shell_radii {
392                for target in fibonacci_sphere(300, radius) {
393                    let seen = sats.iter().any(|(p, t)| {
394                        let nadir = scale(*p, -1.0 / p.norm());
395                        observes(*p, target, nadir, t.half_cone, t.range, t.min_elevation)
396                    });
397                    if !seen {
398                        worst_covered = false;
399                    }
400                }
401            }
402        }
403        assert!(worst_covered, "a shell point went unseen by both tiers");
404        // The cost objective is a positive, finite number and the tiers add up.
405        let chv = system.total_characteristic_velocity(MU, RE, OMEGA_E);
406        assert!(chv.is_finite() && chv > 0.0);
407        assert_eq!(system.total(), 9 * 9 + 8 * 8);
408    }
409}