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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Vallés Puig, Ramon

//! # Johnson–Cousins UBVRI passbands from Bessell (1990)
//!
//! ## Scientific scope
//!
//! Johnson–Cousins UBVRI is the most widely used broad-band photometric
//! system in optical astronomy. The reference realisation of its filter
//! transmission curves used by virtually every modern synthetic
//! photometry pipeline is the one published in
//!
//! > Bessell, M. S. 1990, "UBVRI Passbands", *Publications of the
//! > Astronomical Society of the Pacific*, **102**, 1181.
//! > <https://doi.org/10.1086/132749>
//!
//! Bessell & Murphy (2012, *PASP* **124**, 140) recommend these curves
//! as the canonical "Johnson–Cousins" realisation against which
//! synthetic magnitudes should be computed.
//!
//! Validity is bounded by the published wavelength range of each
//! filter; throughput outside that range is treated as zero (the
//! standard convention for a compactly supported passband).
//!
//! ## Technical scope
//!
//! Provides lazily-initialised, statically-cached
//! [`SampledSpectrum<Nanometer, Throughput>`](crate::spectra::SampledSpectrum)
//! constants for each of the five UBVRI bands via accessor functions
//! `bessell1990::u()`, `bessell1990::b()`, `bessell1990::v()`,
//! `bessell1990::r()`, `bessell1990::i()`. Each spectrum carries a
//! [`Provenance`](crate::provenance::Provenance) record citing the
//! Bessell (1990) paper and the bundled ASCII source file.
//!
//! Sample values are exposed at the typed boundary; consumers that need
//! to drive the untyped numerical kernels can use
//! [`SampledSpectrum::xs_raw`](crate::spectra::SampledSpectrum::xs_raw)
//! and
//! [`SampledSpectrum::ys_raw`](crate::spectra::SampledSpectrum::ys_raw)
//! to obtain zero-cost numeric-table views (`Vec<f64>` of each axis'
//! unit-scoped value) suitable for passing to the algo kernels.
//!
//! ### Data source
//!
//! Data retrieved from the SVO Filter Profile Service
//! (<http://svo2.cab.inta-csic.es/theory/fps/>) under filter IDs
//! `Generic/Bessell.{U,B,V,R,I}`, which mirror Bessell 1990 Table 2.
//! Wavelengths were converted from Ångström (SVO default) to nanometres
//! by dividing by 10. The curated ASCII tables are bundled at
//! `siderust/data/passbands/bessell1990/{U,B,V,R,I}.dat` and pinned by
//! SHA-256 via [`crate::assert_data_checksum!`].
//!
//! ### Usage
//!
//! ```
//! # #[cfg(feature = "spectra")]
//! # {
//! use siderust::spectra::passbands::bessell1990;
//!
//! let v = bessell1990::v();
//! assert!(!v.is_empty());
//!
//! // Flat-spectrum centroid: ∫λ·T dλ / ∫T dλ (SVO "WavelengthMean")
//! // Note: Bessell 1990 Table 1 reports Vega-weighted λ_eff ≈ 545 nm;
//! // the flat-spectrum centroid is ~551 nm.
//! let xs = v.xs_raw();
//! let ys = v.ys_raw();
//! let num: f64 = xs.windows(2).zip(ys.windows(2)).map(|(xw, yw)| {
//!     0.5 * (xw[0] * yw[0] + xw[1] * yw[1]) * (xw[1] - xw[0])
//! }).sum();
//! let den: f64 = xs.windows(2).zip(ys.windows(2)).map(|(xw, yw)| {
//!     0.5 * (yw[0] + yw[1]) * (xw[1] - xw[0])
//! }).sum();
//! let lambda_eff = num / den;
//! // SVO WavelengthMean for Generic/Bessell.V = 5512.1 Å = 551.2 nm
//! assert!((lambda_eff - 551.2).abs() < 2.0, "λ_eff = {lambda_eff:.1} nm");
//! # }
//! ```
//!
//! ## References
//!
//! - Bessell, M. S. (1990). "UBVRI Passbands". *Publications of the
//!   Astronomical Society of the Pacific* **102**, 1181.
//!   doi:10.1086/132749.
//! - Bessell, M. S., & Murphy, S. (2012). "Spectrophotometric Libraries,
//!   Revised Photonic Passbands, and Zero Points for UBVRI, Hipparcos,
//!   and Tycho Photometry". *Publications of the Astronomical Society
//!   of the Pacific* **124**, 140. doi:10.1086/664083.
//! - Rodrigo, C., Solano, E. (2020). *The SVO Filter Profile Service*.
//!   Contributions to the XIV.0 Scientific Meeting of the Spanish
//!   Astronomical Society. <http://svo2.cab.inta-csic.es/theory/fps/>.

use std::sync::OnceLock;

use crate::ext_qtty::length::Nanometer;
use crate::provenance::Provenance;
use crate::spectra::interp::{Interpolation, OutOfRange};
use crate::spectra::loaders::ascii;
use crate::spectra::sampled::SampledSpectrum;

use super::Throughput;

// ── bundled data ─────────────────────────────────────────────────────────────

const RAW_U: &str = include_str!("../../archive/data/passbands/bessell1990/U.dat");
const RAW_B: &str = include_str!("../../archive/data/passbands/bessell1990/B.dat");
const RAW_V: &str = include_str!("../../archive/data/passbands/bessell1990/V.dat");
const RAW_R: &str = include_str!("../../archive/data/passbands/bessell1990/R.dat");
const RAW_I: &str = include_str!("../../archive/data/passbands/bessell1990/I.dat");

// Pinned SHA-256 of each Bessell 1990 passband file. Update only when the
// curated SVO export is intentionally refreshed (see
// `siderust::provenance::checksum`).
crate::assert_data_checksum!(
    "siderust/data/passbands/bessell1990/U.dat",
    RAW_U.as_bytes(),
    "e00771381f3ecd293bcf8c20fdbe57ce5cb9c24404b6ad7f499f28912525ea58"
);
crate::assert_data_checksum!(
    "siderust/data/passbands/bessell1990/B.dat",
    RAW_B.as_bytes(),
    "ba2b36196cc285482659df521fc5ffde60e8c6849963912cfcbe61f912f704b0"
);
crate::assert_data_checksum!(
    "siderust/data/passbands/bessell1990/V.dat",
    RAW_V.as_bytes(),
    "fd5cc0ac9bba2e8121efe8b66d1aeb63b0744b0997d672053bdccf585248e24c"
);
crate::assert_data_checksum!(
    "siderust/data/passbands/bessell1990/R.dat",
    RAW_R.as_bytes(),
    "25393e6cd0c2b3c2c7a2a0688ce675e6475d550150b44f580751e13731ac1bc0"
);
crate::assert_data_checksum!(
    "siderust/data/passbands/bessell1990/I.dat",
    RAW_I.as_bytes(),
    "f3eba62d9898b1b69b6c56cbb7806875f528410145594e56d61cff4f8c5c44e0"
);

// ── static caches ─────────────────────────────────────────────────────────────

static U_TABLE: OnceLock<SampledSpectrum<Nanometer, Throughput>> = OnceLock::new();
static B_TABLE: OnceLock<SampledSpectrum<Nanometer, Throughput>> = OnceLock::new();
static V_TABLE: OnceLock<SampledSpectrum<Nanometer, Throughput>> = OnceLock::new();
static R_TABLE: OnceLock<SampledSpectrum<Nanometer, Throughput>> = OnceLock::new();
static I_TABLE: OnceLock<SampledSpectrum<Nanometer, Throughput>> = OnceLock::new();

// ── helpers ───────────────────────────────────────────────────────────────────

fn provenance(filter_id: &str, dat_path: &str) -> Provenance {
    Provenance::bundled_file(dat_path).with_notes(format!(
        "Bessell 1990, PASP 102, 1181 — filter {filter_id}. \
         Retrieved from SVO Filter Profile Service \
         <http://svo2.cab.inta-csic.es/theory/fps/>. \
         Wavelengths converted Å→nm (÷10)."
    ))
}

fn load(raw: &str, filter_id: &str, dat_path: &str) -> SampledSpectrum<Nanometer, Throughput> {
    ascii::two_column::<Nanometer, Throughput>(
        raw,
        1.0, // wavelengths already in nm (converted from Å during data curation)
        1.0,
        Interpolation::Linear,
        OutOfRange::ClampToEndpoints,
        Some(provenance(filter_id, dat_path)),
    )
    .unwrap_or_else(|e| panic!("Bessell 1990 {filter_id} passband failed to parse: {e}"))
}

// ── public API ────────────────────────────────────────────────────────────────

/// Johnson U passband — Bessell 1990, PASP 102, 1181.
///
/// λ_eff ≈ 366 nm, FWHM ≈ 66 nm (Bessell 1990 Table 1).
pub fn u() -> &'static SampledSpectrum<Nanometer, Throughput> {
    U_TABLE.get_or_init(|| {
        load(
            RAW_U,
            "Generic/Bessell.U",
            "siderust/data/passbands/bessell1990/U.dat",
        )
    })
}

/// Johnson B passband — Bessell 1990, PASP 102, 1181.
///
/// λ_eff ≈ 438 nm, FWHM ≈ 98 nm (Bessell 1990 Table 1).
pub fn b() -> &'static SampledSpectrum<Nanometer, Throughput> {
    B_TABLE.get_or_init(|| {
        load(
            RAW_B,
            "Generic/Bessell.B",
            "siderust/data/passbands/bessell1990/B.dat",
        )
    })
}

/// Johnson V passband — Bessell 1990, PASP 102, 1181.
///
/// λ_eff ≈ 545 nm, FWHM ≈ 88 nm (Bessell 1990 Table 1).
pub fn v() -> &'static SampledSpectrum<Nanometer, Throughput> {
    V_TABLE.get_or_init(|| {
        load(
            RAW_V,
            "Generic/Bessell.V",
            "siderust/data/passbands/bessell1990/V.dat",
        )
    })
}

/// Cousins R passband — Bessell 1990, PASP 102, 1181.
///
/// λ_eff ≈ 641 nm, FWHM ≈ 158 nm (Bessell 1990 Table 1).
pub fn r() -> &'static SampledSpectrum<Nanometer, Throughput> {
    R_TABLE.get_or_init(|| {
        load(
            RAW_R,
            "Generic/Bessell.R",
            "siderust/data/passbands/bessell1990/R.dat",
        )
    })
}

/// Cousins I passband — Bessell 1990, PASP 102, 1181.
///
/// λ_eff ≈ 798 nm, FWHM ≈ 154 nm (Bessell 1990 Table 1).
pub fn i() -> &'static SampledSpectrum<Nanometer, Throughput> {
    I_TABLE.get_or_init(|| {
        load(
            RAW_I,
            "Generic/Bessell.I",
            "siderust/data/passbands/bessell1990/I.dat",
        )
    })
}

// ── helpers for tests ─────────────────────────────────────────────────────────

/// Compute effective wavelength ∫λ·T dλ / ∫T dλ using trapezoidal integration.
#[cfg(test)]
fn effective_wavelength(s: &SampledSpectrum<Nanometer, Throughput>) -> f64 {
    let xs = s.xs_raw();
    let ys = s.ys_raw();
    let num: f64 = xs
        .windows(2)
        .zip(ys.windows(2))
        .map(|(xw, yw)| 0.5 * (xw[0] * yw[0] + xw[1] * yw[1]) * (xw[1] - xw[0]))
        .sum();
    let den: f64 = xs
        .windows(2)
        .zip(ys.windows(2))
        .map(|(xw, yw)| 0.5 * (yw[0] + yw[1]) * (xw[1] - xw[0]))
        .sum();
    num / den
}

/// Compute FWHM of a passband (in the same units as xs).
#[cfg(test)]
fn fwhm(s: &SampledSpectrum<Nanometer, Throughput>) -> f64 {
    let xs = s.xs_raw();
    let ys = s.ys_raw();
    let half_max = ys.iter().cloned().fold(f64::NEG_INFINITY, f64::max) / 2.0;

    // find rising edge (first crossing of half_max going up)
    let lo = xs
        .windows(2)
        .zip(ys.windows(2))
        .find(|(_, yw)| yw[0] < half_max && yw[1] >= half_max)
        .map(|(xw, yw)| {
            let t = (half_max - yw[0]) / (yw[1] - yw[0]);
            xw[0] + t * (xw[1] - xw[0])
        })
        .unwrap_or(xs[0]);

    // find falling edge (last crossing of half_max going down)
    let hi = xs
        .windows(2)
        .zip(ys.windows(2))
        .rev()
        .find(|(_, yw)| yw[0] >= half_max && yw[1] < half_max)
        .map(|(xw, yw)| {
            let t = (yw[0] - half_max) / (yw[0] - yw[1]);
            xw[0] + t * (xw[1] - xw[0])
        })
        .unwrap_or(*xs.last().unwrap());

    hi - lo
}

// ── tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    /// Defense-in-depth: confirm the runtime SHA-256 of every bundled
    /// passband file matches the value pinned via
    /// [`assert_data_checksum!`].
    #[test]
    fn pinned_sha256_matches_runtime_hash() {
        use crate::provenance::checksum::{sha256, to_hex};
        let cases: &[(&str, &str)] = &[
            (
                RAW_U,
                "e00771381f3ecd293bcf8c20fdbe57ce5cb9c24404b6ad7f499f28912525ea58",
            ),
            (
                RAW_B,
                "ba2b36196cc285482659df521fc5ffde60e8c6849963912cfcbe61f912f704b0",
            ),
            (
                RAW_V,
                "fd5cc0ac9bba2e8121efe8b66d1aeb63b0744b0997d672053bdccf585248e24c",
            ),
            (
                RAW_R,
                "25393e6cd0c2b3c2c7a2a0688ce675e6475d550150b44f580751e13731ac1bc0",
            ),
            (
                RAW_I,
                "f3eba62d9898b1b69b6c56cbb7806875f528410145594e56d61cff4f8c5c44e0",
            ),
        ];
        for (raw, want) in cases {
            assert_eq!(to_hex(&sha256(raw.as_bytes())), *want);
        }
    }

    // ── per-band fixtures ──────────────────────────────────────────────────────

    struct BandSpec {
        name: &'static str,
        band: fn() -> &'static SampledSpectrum<Nanometer, Throughput>,
        /// Expected effective wavelength from Bessell 1990 Table 1 (nm).
        lambda_eff_expected: f64,
        /// Tolerance on effective wavelength (nm).
        lambda_eff_tol: f64,
        /// Expected FWHM from Bessell 1990 Table 1 (nm). `None` = skip.
        fwhm_expected: Option<f64>,
        /// Tolerance on FWHM (nm).
        fwhm_tol: f64,
    }

    fn bands() -> Vec<BandSpec> {
        // Expected λ_eff values are the flat-spectrum centroids ∫λT dλ / ∫T dλ
        // (SVO "WavelengthMean") computed from the bundled data.  These differ
        // from the Bessell 1990 Table 1 "effective wavelengths" (≈ U:366, B:438,
        // V:545, R:641, I:798 nm) which are Vega-weighted: ∫λT·Vega dλ / ∫T·Vega dλ.
        vec![
            BandSpec {
                name: "U",
                band: u,
                lambda_eff_expected: 360.5,
                lambda_eff_tol: 2.0,
                fwhm_expected: None,
                fwhm_tol: 10.0,
            },
            BandSpec {
                name: "B",
                band: b,
                lambda_eff_expected: 441.3,
                lambda_eff_tol: 2.0,
                fwhm_expected: Some(98.0),
                fwhm_tol: 15.0,
            },
            BandSpec {
                name: "V",
                band: v,
                lambda_eff_expected: 551.2,
                lambda_eff_tol: 2.0,
                fwhm_expected: Some(88.0),
                fwhm_tol: 15.0,
            },
            BandSpec {
                name: "R",
                band: r,
                lambda_eff_expected: 658.6,
                lambda_eff_tol: 2.0,
                fwhm_expected: None, // R has a very broad, irregular tail
                fwhm_tol: 10.0,
            },
            BandSpec {
                name: "I",
                band: i,
                lambda_eff_expected: 806.0,
                lambda_eff_tol: 2.0,
                fwhm_expected: None,
                fwhm_tol: 10.0,
            },
        ]
    }

    // ── basic structural tests ─────────────────────────────────────────────────

    #[test]
    fn all_bands_nonempty() {
        for spec in bands() {
            let s = (spec.band)();
            assert!(!s.is_empty(), "{}: spectrum must not be empty", spec.name);
            assert!(s.len() >= 2, "{}: must have at least 2 samples", spec.name);
        }
    }

    #[test]
    fn all_bands_monotonic_wavelengths() {
        for spec in bands() {
            let s = (spec.band)();
            let xs = s.xs_raw();
            for w in xs.windows(2) {
                assert!(
                    w[1] > w[0],
                    "{}: wavelengths not strictly increasing: {} <= {}",
                    spec.name,
                    w[1],
                    w[0]
                );
            }
        }
    }

    #[test]
    fn all_bands_transmittances_in_unit_interval() {
        for spec in bands() {
            let s = (spec.band)();
            for (i, y) in s.ys_raw().iter().enumerate() {
                assert!(
                    *y >= 0.0 && *y <= 1.0,
                    "{}: transmittance[{i}] = {y} is outside [0, 1]",
                    spec.name
                );
            }
        }
    }

    // ── photometric accuracy tests ─────────────────────────────────────────────

    /// Tests flat-spectrum centroid ∫λT dλ / ∫T dλ (SVO "WavelengthMean").
    /// Note: Bessell 1990 Table 1 publishes Vega-weighted λ_eff; see band
    /// fixture comments for the distinction.
    #[test]
    fn flat_spectrum_centroid_matches_svo_wavelength_mean() {
        for spec in bands() {
            let s = (spec.band)();
            let lam = effective_wavelength(s);
            assert!(
                (lam - spec.lambda_eff_expected).abs() <= spec.lambda_eff_tol,
                "{}: λ_eff = {lam:.2} nm, expected {:.1} ± {:.1} nm",
                spec.name,
                spec.lambda_eff_expected,
                spec.lambda_eff_tol
            );
        }
    }

    #[test]
    fn fwhm_sanity_check_b_and_v() {
        for spec in bands() {
            if let Some(expected_fwhm) = spec.fwhm_expected {
                let s = (spec.band)();
                let w = fwhm(s);
                assert!(
                    (w - expected_fwhm).abs() <= spec.fwhm_tol,
                    "{}: FWHM = {w:.2} nm, expected {expected_fwhm:.1} ± {:.1} nm",
                    spec.name,
                    spec.fwhm_tol
                );
            }
        }
    }

    // ── OnceLock identity test ─────────────────────────────────────────────────

    #[test]
    fn repeated_calls_return_same_pointer() {
        let a = v() as *const _;
        let b = v() as *const _;
        assert_eq!(
            a, b,
            "OnceLock must return the same instance on repeated calls"
        );
    }

    // ── integration smoke test ─────────────────────────────────────────────────

    /// Load V band and integrate a flat spectrum (F_λ = 1) through it.
    /// ∫ T(λ) dλ over the V band should be positive and finite.
    #[test]
    fn v_band_flat_spectrum_integral_is_positive() {
        let vb = v();
        let xs = vb.xs_raw();
        let ys = vb.ys_raw();
        // Trapezoidal ∫ T dλ
        let integral: f64 = xs
            .windows(2)
            .zip(ys.windows(2))
            .map(|(xw, yw)| 0.5 * (yw[0] + yw[1]) * (xw[1] - xw[0]))
            .sum();
        assert!(
            integral > 0.0,
            "∫ T_V dλ should be positive, got {integral}"
        );
        // The V band spans ~470–700 nm with peak ≈ 1.0; ∫T dλ ≈ several tens of nm
        assert!(integral > 10.0, "∫ T_V dλ = {integral} nm seems too small");
    }
}