siderust 0.7.0

High-precision astronomy and satellite mechanics in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Vallés Puig, Ramon

//! # Azimuth Event-Finding Functions
//!
//! ## Scientific scope
//!
//! Computes time‑domain azimuth events for a topocentric observer:
//! bearing crossings (instants when *A(t)* matches a fixed compass
//! bearing), local extrema (turning points where *A(t)* reaches its most
//! northerly/southerly excursion), and the time intervals during which
//! *A(t)* stays inside a (possibly North‑wrapping) bearing band. The
//! azimuth function itself is delegated to [`AzimuthProvider`], so
//! accuracy and validity inherit from the underlying ephemeris/star
//! engine. Refraction is not modelled.
//!
//! ## Technical scope
//!
//! Public API: [`azimuth_crossings`], [`azimuth_extrema`],
//! [`azimuth_ranges`], [`in_azimuth_range`], [`outside_azimuth_range`].
//! All `Period<ModifiedJulianDate>` inputs/outputs are interpreted on the
//! TT axis. Convert UTC timestamps with `ModifiedJulianDate::from_chrono(…)`
//! first.
//!
//! ### Handling the 0°/360° discontinuity
//!
//! Azimuth is a circular quantity that wraps at North (0° = 360°).  Naive
//! root-finding on the raw `az(t)` function would produce false crossings at
//! every wrap-around.  This module uses two complementary strategies:
//!
//! * **Trigonometric reformulation** for crossings and range queries:
//!   `sin(az(t) − b)` and `cos(az(t) − midpoint)` are continuous even
//!   through the 0°/360° boundary, because cosine/sine are 2π-periodic.
//!   These are passed directly to `math_core` without any unwrapping.
//!
//! * **Stateful unwrapping closure** for extrema: a `Cell`-based closure
//!   tracks the previous raw sample and accumulates ±2π offsets, producing
//!   a continuous monotone-ish function safe for `find_extrema_tol`.
//!
//! ## References
//! None.

use std::cell::Cell;

use super::provider::AzimuthProvider;
use super::search::{SearchOpts, DEFAULT_SCAN_STEP, EXTREMA_SCAN_STEP};
use super::types::{AzimuthCrossingEvent, AzimuthExtremum, AzimuthExtremumKind, AzimuthQuery};
use crate::calculus::altitude::CrossingDirection;
use crate::calculus::math_core::{extrema, intervals};
use crate::coordinates::centers::Geodetic;
use crate::coordinates::frames::ECEF;
use crate::qtty::*;
use crate::time::{complement_within, ModifiedJulianDate, Period};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Choose the best scan step for the target.
fn scan_step_for<T: AzimuthProvider>(target: &T, opts: &SearchOpts) -> Days {
    opts.scan_step_days
        .or_else(|| target.scan_step_hint())
        .unwrap_or(DEFAULT_SCAN_STEP)
}

/// Build a **continuous** function `sin(az(t) − bearing)`.
///
/// This sidesteps the 0°/360° discontinuity of the raw azimuth: because sine
/// has period 2π, `sin(az + 2π − b) = sin(az − b)`, the function is smooth
/// and sign-changes exactly where `az(t) = bearing  (mod 360°)`.
///
/// The zero-crossings of this function correspond exactly to crossing events
/// for the given bearing.
fn make_az_bearing_sin_fn<'a, T: AzimuthProvider>(
    target: &'a T,
    site: &'a Geodetic<ECEF>,
    bearing: Radians,
) -> impl Fn(ModifiedJulianDate) -> Radians + 'a {
    let site = *site;
    move |t: ModifiedJulianDate| {
        let az = target.azimuth_at(&site, t);
        Radians::new((az - bearing).value().sin())
    }
}

/// Build a continuous function `cos(az(t) − mid)` for range queries.
///
/// The body is inside the arc `[min_az, max_az]` when
/// `cos(az − mid) ≥ cos(halfwidth)`, i.e. when this function is ≥ 0 after
/// subtracting `cos(halfwidth)`.  This avoids the 0°/360° wrap entirely.
fn make_az_cosine_fn<'a, T: AzimuthProvider>(
    target: &'a T,
    site: &'a Geodetic<ECEF>,
    mid: Radians,
    cos_hw: f64,
) -> impl Fn(ModifiedJulianDate) -> Radians + 'a {
    let site = *site;
    move |t: ModifiedJulianDate| {
        let az = target.azimuth_at(&site, t);
        Radians::new((az - mid).value().cos() - cos_hw)
    }
}

/// Build an **unwrapped** (continuous) azimuth closure using a `Cell`-based
/// accumulator.
///
/// Each call adjusts a running ±2π offset whenever the raw azimuth value
/// jumps by more than π since the last sample.  This produces a smooth,
/// monotone function safe for `find_extrema_tol`.
///
/// **Important:** this closure is stateful and must be evaluated with
/// monotonically increasing `t`, as guaranteed by all `math_core` scan loops.
fn make_az_unwrapped_fn<'a, T: AzimuthProvider>(
    target: &'a T,
    site: Geodetic<ECEF>,
) -> impl Fn(ModifiedJulianDate) -> Radians + 'a {
    let prev_raw: Cell<f64> = Cell::new(f64::NAN);
    let offset: Cell<f64> = Cell::new(0.0f64);
    move |t: ModifiedJulianDate| {
        let raw = target.azimuth_at(&site, t).value(); // [0, 2π)
        let p = prev_raw.get();
        if !p.is_nan() {
            let diff = raw - p;
            if diff > std::f64::consts::PI {
                // Apparent upward jump > π → real motion was downward (0°→360° crossing)
                offset.set(offset.get() - std::f64::consts::TAU);
            } else if diff < -std::f64::consts::PI {
                // Apparent downward jump > π → real motion was upward (360°→0° crossing)
                offset.set(offset.get() + std::f64::consts::TAU);
            }
        }
        prev_raw.set(raw);
        Radians::new(raw + offset.get())
    }
}

// ---------------------------------------------------------------------------
// Bearing Crossings
// ---------------------------------------------------------------------------

/// Find all moments when `target`'s azimuth crosses a given `bearing`,
/// within the specified `window`.
///
/// Returns a chronologically sorted list of [`AzimuthCrossingEvent`]s.
///
/// `direction` is [`CrossingDirection::Rising`] when the azimuth is
/// increasing (moving clockwise / eastward across the bearing), and
/// [`CrossingDirection::Setting`] when decreasing.
///
/// # Arguments
/// * `target`  , any body implementing [`AzimuthProvider`]
/// * `observer`, site on Earth
/// * `window`  , search interval (MJD on TT axis)
/// * `bearing` , compass bearing to detect crossings of (North-clockwise)
/// * `opts`    , search options (tolerances, scan step)
///
/// # Example
/// ```rust
/// use siderust::calculus::azimuth::{azimuth_crossings, SearchOpts};
/// use siderust::bodies::Sun;
/// use siderust::coordinates::centers::Geodetic;
/// use siderust::coordinates::frames::ECEF;
/// use siderust::time::{ModifiedJulianDate, MJD, Period};
/// use siderust::qtty::*;
///
/// let site = Geodetic::<ECEF>::new(Degrees::new(0.0), Degrees::new(51.48), Meters::new(0.0));
/// let window = Period::new(ModifiedJulianDate::new(60000.0), ModifiedJulianDate::new(60001.0));
///
/// // Find when the Sun crosses due-South (180°)
/// let events = azimuth_crossings(&Sun, &site, window, Degrees::new(180.0), SearchOpts::default());
/// ```
///
/// # Returns
///
/// Chronologically sorted `Vec<AzimuthCrossingEvent>` of every bearing
/// transit found inside `window`.
pub fn azimuth_crossings<T: AzimuthProvider>(
    target: &T,
    observer: &Geodetic<ECEF>,
    window: Period<ModifiedJulianDate>,
    bearing: Degrees,
    opts: SearchOpts,
) -> Vec<AzimuthCrossingEvent> {
    let bearing_rad = bearing.to::<Radian>();
    let f = make_az_bearing_sin_fn(target, observer, bearing_rad);
    let step = scan_step_for(target, &opts);

    let mut raw = intervals::find_crossings(window, step, &f, Radians::new(0.0));
    let labeled = intervals::label_crossings(&mut raw, &f, Radians::new(0.0));

    labeled
        .iter()
        .map(|lc| AzimuthCrossingEvent {
            mjd: lc.t,
            direction: if lc.direction > 0 {
                CrossingDirection::Rising
            } else {
                CrossingDirection::Setting
            },
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Azimuth Extrema
// ---------------------------------------------------------------------------

/// Find all local azimuth extrema (northernmost and southernmost bearings)
/// of `target` in `window`.
///
/// Returns a chronologically sorted list of [`AzimuthExtremum`]s.
///
/// Uses a stateful unwrapped closure so that true extrema near the
/// 0°/360° boundary are detected correctly.
///
/// # Arguments
///
/// * `target`, body implementing [`AzimuthProvider`]
/// * `observer`, geodetic site
/// * `window`, MJD/TT search interval
/// * `opts`, search precision options
///
/// # Returns
///
/// Sorted `Vec<AzimuthExtremum>` mixing local maxima and minima of the
/// (unwrapped) azimuth.
pub fn azimuth_extrema<T: AzimuthProvider>(
    target: &T,
    observer: &Geodetic<ECEF>,
    window: Period<ModifiedJulianDate>,
    opts: SearchOpts,
) -> Vec<AzimuthExtremum> {
    let step = opts
        .scan_step_days
        .or_else(|| target.scan_step_hint())
        .unwrap_or(EXTREMA_SCAN_STEP);
    let tol = opts.time_tolerance;

    let f = make_az_unwrapped_fn(target, *observer);
    let raw: Vec<extrema::Extremum<Radian>> = extrema::find_extrema_tol(window, step, &f, tol);

    raw.iter()
        .map(|ext| {
            // Wrap the unwrapped value back into [0°, 360°)
            let az_deg = ext.value.wrap_pos().to::<Degree>();
            AzimuthExtremum {
                mjd: ext.t,
                azimuth: az_deg,
                kind: match ext.kind {
                    extrema::ExtremumKind::Maximum => AzimuthExtremumKind::Max,
                    extrema::ExtremumKind::Minimum => AzimuthExtremumKind::Min,
                },
            }
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Azimuth Range Periods (internal helper called from provider.rs)
// ---------------------------------------------------------------------------

/// Compute periods when `target`'s azimuth is within the band described by
/// `query`.
///
/// This function is `pub(crate)` and is the single implementation backing
/// all [`AzimuthProvider::azimuth_periods`] impls.
///
/// ## Non-wrap range (`min ≤ max`)
///
/// Uses the midpoint-cosine approach:
/// `f(t) = cos(az(t) − mid) − cos(halfwidth) ≥ 0` precisely when
/// `az ∈ [min, max]`.  This function is continuous even through the
/// 0°/360° boundary.
///
/// ## Wrap-around range (`min > max`)
///
/// The arc `[min, 360°) ∪ [0°, max]` equals the complement of the arc
/// `[max, min]` (non-wrapping).  We compute the non-wrapping complement and
/// take its complement within the window.
pub(crate) fn azimuth_range_periods<T: AzimuthProvider>(
    target: &T,
    query: &AzimuthQuery,
) -> Vec<Period<ModifiedJulianDate>> {
    let step = target.scan_step_hint().unwrap_or(DEFAULT_SCAN_STEP);

    if query.min_azimuth <= query.max_azimuth {
        // ── Non-wrap arc [min, max] ────────────────────────────────────────
        let mid = ((query.min_azimuth + query.max_azimuth) * 0.5).to::<Radian>();
        let half_width = ((query.max_azimuth - query.min_azimuth) * 0.5).to::<Radian>();
        let cos_hw = half_width.cos();

        let f = make_az_cosine_fn(target, &query.observer, mid, cos_hw);
        intervals::above_threshold_periods(query.window, step, &f, Radians::new(0.0))
    } else {
        // ── Wrap-around arc [min, 360°) ∪ [0°, max] ──────────────────────
        // Complement arc is [max, min] (non-wrapping).
        let mid = ((query.max_azimuth + query.min_azimuth) * 0.5).to::<Radian>();
        let half_width = ((query.min_azimuth - query.max_azimuth) * 0.5).to::<Radian>();
        let cos_hw = half_width.cos();

        let f = make_az_cosine_fn(target, &query.observer, mid, cos_hw);
        let outside = intervals::above_threshold_periods(query.window, step, &f, Radians::new(0.0));
        complement_within(query.window, &outside)
    }
}

// ---------------------------------------------------------------------------
// Public free functions (generic, exposed from mod.rs)
// ---------------------------------------------------------------------------

/// Find all time intervals where `target`'s azimuth is within
/// `[min_az, max_az]`.
///
/// Supports wrap-around ranges when `min_az > max_az` (e.g. 350° → 10°).
///
/// Returns a sorted list of `Period<ModifiedJulianDate>`.
///
/// # Arguments
///
/// * `target`, body implementing [`AzimuthProvider`]
/// * `observer`, geodetic site
/// * `window`, MJD/TT search interval
/// * `min_az`, lower bearing bound (or start of wrap arc)
/// * `max_az`, upper bearing bound (or end of wrap arc)
/// * `_opts`, search precision options (currently routed via the provider hint)
///
/// # Returns
///
/// Sorted, non‑overlapping `Vec<Period<ModifiedJulianDate>>` covering the
/// times when the azimuth lies in the requested arc.
pub fn azimuth_ranges<T: AzimuthProvider>(
    target: &T,
    observer: &Geodetic<ECEF>,
    window: Period<ModifiedJulianDate>,
    min_az: Degrees,
    max_az: Degrees,
    _opts: SearchOpts,
) -> Vec<Period<ModifiedJulianDate>> {
    target.azimuth_periods(&AzimuthQuery {
        observer: *observer,
        window,
        min_azimuth: min_az,
        max_azimuth: max_az,
    })
}

/// Convenience: find periods where azimuth is within `[min_az, max_az]`.
///
/// Identical to [`azimuth_ranges`]; provided as a named convenience wrapper.
///
/// # Arguments
///
/// * `target`, body implementing [`AzimuthProvider`]
/// * `observer`, geodetic site
/// * `window`, MJD/TT search interval
/// * `min_az`, lower bearing bound (or start of wrap arc)
/// * `max_az`, upper bearing bound (or end of wrap arc)
/// * `opts`, search precision options
///
/// # Returns
///
/// Same as [`azimuth_ranges`]: sorted `Vec<Period<ModifiedJulianDate>>`.
pub fn in_azimuth_range<T: AzimuthProvider>(
    target: &T,
    observer: &Geodetic<ECEF>,
    window: Period<ModifiedJulianDate>,
    min_az: Degrees,
    max_az: Degrees,
    opts: SearchOpts,
) -> Vec<Period<ModifiedJulianDate>> {
    azimuth_ranges(target, observer, window, min_az, max_az, opts)
}

/// Convenience: find periods where azimuth is **outside** `[min_az, max_az]`.
///
/// # Arguments
///
/// * `target`, body implementing [`AzimuthProvider`]
/// * `observer`, geodetic site
/// * `window`, MJD/TT search interval
/// * `min_az`, lower bearing bound (or start of wrap arc)
/// * `max_az`, upper bearing bound (or end of wrap arc)
/// * `opts`, search precision options
///
/// # Returns
///
/// Sorted, non‑overlapping `Vec<Period<ModifiedJulianDate>>` covering the
/// complement of [`in_azimuth_range`] inside `window`.
pub fn outside_azimuth_range<T: AzimuthProvider>(
    target: &T,
    observer: &Geodetic<ECEF>,
    window: Period<ModifiedJulianDate>,
    min_az: Degrees,
    max_az: Degrees,
    opts: SearchOpts,
) -> Vec<Period<ModifiedJulianDate>> {
    let inside = azimuth_ranges(target, observer, window, min_az, max_az, opts);
    complement_within(window, &inside)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bodies::solar_system::Sun;

    fn greenwich() -> Geodetic<ECEF> {
        Geodetic::<ECEF>::new(Degrees::new(0.0), Degrees::new(51.4769), Meters::new(0.0))
    }

    fn one_day() -> Period<ModifiedJulianDate> {
        Period::new(
            ModifiedJulianDate::new(60000.0),
            ModifiedJulianDate::new(60001.0),
        )
    }

    #[test]
    fn crossings_finds_south_transit() {
        let events = azimuth_crossings(
            &Sun,
            &greenwich(),
            one_day(),
            Degrees::new(180.0), // due-South
            SearchOpts::default(),
        );
        // Sun transits the meridian (az≈180°) once per day at 51°N
        assert!(
            !events.is_empty(),
            "should find the Sun's southward transit"
        );
    }

    #[test]
    fn extrema_are_valid_if_present() {
        // The Sun's azimuth is monotonically increasing over 24h (Earth rotation
        // dominates), so no local extrema are expected.  This test only validates
        // that the function runs cleanly and any returned extrema are in range.
        let exts = azimuth_extrema(&Sun, &greenwich(), one_day(), SearchOpts::default());
        for e in &exts {
            assert!(
                e.azimuth.value() >= 0.0 && e.azimuth.value() < 360.0,
                "extremum azimuth out of [0°, 360°): {}",
                e.azimuth.value()
            );
        }
    }

    #[test]
    fn range_periods_non_wrap() {
        let periods = in_azimuth_range(
            &Sun,
            &greenwich(),
            one_day(),
            Degrees::new(90.0),  // East
            Degrees::new(270.0), // West
            SearchOpts::default(),
        );
        assert!(!periods.is_empty(), "Sun should be east-to-west in 24h");
    }

    #[test]
    fn range_periods_wrap_around() {
        // North-crossing arc: 340° → 20°
        let periods = in_azimuth_range(
            &Sun,
            &greenwich(),
            // Use a 7-day window, the Sun is near North briefly near the solstice,
            // but let's just check the function runs without panicking and that
            // non-wrap + wrap complement each other.
            Period::new(
                ModifiedJulianDate::new(60000.0),
                ModifiedJulianDate::new(60007.0),
            ),
            Degrees::new(340.0),
            Degrees::new(20.0),
            SearchOpts::default(),
        );
        // Result may be empty (Sun rarely near North at 51°N); just check no panic.
        let _ = periods;
    }

    #[test]
    fn outside_is_complement_of_in_range() {
        let window = one_day();
        let observer = greenwich();
        let inside = in_azimuth_range(
            &Sun,
            &observer,
            window,
            Degrees::new(90.0),
            Degrees::new(270.0),
            SearchOpts::default(),
        );
        let outside = outside_azimuth_range(
            &Sun,
            &observer,
            window,
            Degrees::new(90.0),
            Degrees::new(270.0),
            SearchOpts::default(),
        );
        let total: f64 = inside
            .iter()
            .chain(outside.iter())
            .map(|p| ((p).end - (p).start).value())
            .sum();
        let window_duration = ((window).end - (window).start).value();
        assert!(
            (total - window_duration).abs() < 1e-6,
            "inside + outside durations must equal the window"
        );
    }
}