nsb 0.1.0

Night-sky background evaluation and observation planning for ground-based astronomy.
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
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Vallés Puig, Ramon
//! Scientific site profiles, shared atmospheric assumptions, and calibration metadata.
//!
//! NSB deliberately separates observer location from scientific site profiles.
//! A location answers where the observer is; [`SiteProfile<P>`](SiteProfile)
//! answers which NSB assumptions are selected. The marker type `P` carries
//! compile-time identity, while strings are reporting metadata only.
//! Observatory- or project-named planning markers belong at an application or
//! data layer; the core crate only provides the generic mechanism.

/// Shared atmospheric assumptions used by site-aware NSB components.
pub(crate) mod atmosphere;
/// Versioned evidence contract for dedicated site-calibration assets.
pub(crate) mod calibration;

pub use atmosphere::AtmosphericConditions;

use crate::units::dimensionless::Ratios;
use crate::{NsbError, Result};
use siderust::coordinates::centers::Geodetic;
use siderust::coordinates::frames::ECEF;
use siderust::qtty::Kilometers;
use std::marker::PhantomData;

/// Compile-time identity for a scientific site profile.
///
/// Application crates may implement this trait for their own zero-sized marker
/// types. `NAME` is used only for diagnostics and serialized metadata; it never
/// selects scientific behavior or calibration maturity.
pub trait SiteProfileTag: 'static {
    /// Stable presentation/serialization name for this profile.
    const NAME: &'static str;
}

/// Type-level identity of NSB's observer-derived generic clear-sky fallback.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GenericClearSky;

impl SiteProfileTag for GenericClearSky {
    const NAME: &'static str = "generic-clear-sky";
}

/// Scientific maturity of a named site profile.
///
/// Additional maturity labels may be added; match with a wildcard.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CalibrationStatus {
    /// Generic, location-agnostic fallback; not a named-site calibration.
    GenericFallback,
    /// Named-site planning preset with explicit assumptions and provenance.
    PlanningPreset,
    /// Dedicated site-calibrated profile validated against site reference data.
    Calibrated,
}

/// Airglow-side assumptions used by every currently supported site profile.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct AirglowSiteCalibration {
    pub(crate) scale: Ratios,
    pub(crate) provenance: &'static str,
    pub(crate) assumptions: &'static str,
}

impl AirglowSiteCalibration {
    fn skycalc_neutral() -> Self {
        Self {
            scale: Ratios::new(1.0),
            provenance: concat!(
                "Bundled PALACE v1.0 Paranal-derived unresolved-continuum planning product ",
                "reused as an explicit generic/planning proxy; neutral site scale; ",
                "not site-calibrated."
            ),
            assumptions: concat!(
                "No site-specific airglow continuum scale is bundled by the core ",
                "library; named application-layer profiles should record this ",
                "explicitly instead of silently claiming a calibrated site airglow ",
                "model. Arbitrary-location and Paranal-location results remain ",
                "planning approximations unless an explicit validated scientific ",
                "profile is selected; provenance from Paranal is not calibration ",
                "evidence for the observer location."
            ),
        }
    }
}

/// Opaque scientific profile with compile-time identity `P`.
///
/// External marker types provide identity only. Public planning construction
/// always produces [`CalibrationStatus::PlanningPreset`]; it cannot claim a
/// calibrated profile or choose an unevaluated Airglow asset.
pub struct SiteProfile<P: SiteProfileTag> {
    config: SiteProfileConfig,
    marker: PhantomData<fn() -> P>,
}

impl<P: SiteProfileTag> std::fmt::Debug for SiteProfile<P> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("SiteProfile")
            .field("name", &P::NAME)
            .field("calibration_status", &self.config.calibration_status)
            .finish_non_exhaustive()
    }
}

impl<P: SiteProfileTag> Clone for SiteProfile<P> {
    fn clone(&self) -> Self {
        Self {
            config: self.config.clone(),
            marker: PhantomData,
        }
    }
}

impl<P: SiteProfileTag> PartialEq for SiteProfile<P> {
    fn eq(&self, other: &Self) -> bool {
        self.config == other.config
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct SiteProfileConfig {
    name: String,
    calibration_status: CalibrationStatus,
    _representative_altitude: Option<Kilometers>,
    atmosphere: Option<AtmosphericConditions>,
    atmosphere_provenance: String,
    airglow: AirglowSiteCalibration,
}

impl SiteProfile<GenericClearSky> {
    /// Observer-derived generic clear-sky fallback.
    ///
    /// Pressure is derived from the query observer altitude when resolved.
    pub fn generic_clear_sky() -> Self {
        Self {
            config: SiteProfileConfig::generic_clear_sky(),
            marker: PhantomData,
        }
    }
}

impl<P: SiteProfileTag> SiteProfile<P> {
    /// Explicit planning preset with fixed atmospheric assumptions.
    ///
    /// `P` supplies compile-time identity. Its [`SiteProfileTag::NAME`] is
    /// retained only as reporting metadata. Nonphysical inputs are rejected.
    pub fn planning(
        representative_altitude: Kilometers,
        atmosphere: AtmosphericConditions,
        atmosphere_provenance: impl Into<String>,
    ) -> Result<Self> {
        let atmosphere_provenance = atmosphere_provenance.into();
        validate_nonempty(&atmosphere_provenance, "site-profile atmosphere provenance")?;
        validate_finite(representative_altitude.value(), "representative altitude")?;
        atmosphere.validate()?;

        Ok(Self {
            config: SiteProfileConfig {
                name: P::NAME.to_owned(),
                calibration_status: CalibrationStatus::PlanningPreset,
                _representative_altitude: Some(representative_altitude),
                atmosphere: Some(atmosphere),
                atmosphere_provenance,
                airglow: AirglowSiteCalibration::skycalc_neutral(),
            },
            marker: PhantomData,
        })
    }

    /// Evidence-backed calibration maturity for this scientific profile.
    pub const fn calibration_status(&self) -> CalibrationStatus {
        self.config.calibration_status
    }

    /// Human-readable profile name.
    pub fn name(&self) -> &str {
        &self.config.name
    }

    /// Provenance and limitations of the atmospheric assumptions.
    pub fn atmosphere_provenance(&self) -> &str {
        &self.config.atmosphere_provenance
    }

    pub(crate) fn erase(self) -> SiteProfileConfig {
        self.config
    }
}

impl SiteProfileConfig {
    fn generic_clear_sky() -> Self {
        Self {
            name: GenericClearSky::NAME.to_owned(),
            calibration_status: CalibrationStatus::GenericFallback,
            _representative_altitude: None,
            atmosphere: None,
            atmosphere_provenance: concat!(
                "Pressure estimated from observer altitude with the NSB ",
                "generic barometric fallback; Rayleigh scale height and Mie ",
                "parameters use the bundled clear-sky defaults."
            )
            .to_owned(),
            airglow: AirglowSiteCalibration::skycalc_neutral(),
        }
    }

    pub(crate) fn name(&self) -> &str {
        &self.name
    }

    pub(crate) const fn calibration_status(&self) -> CalibrationStatus {
        self.calibration_status
    }

    pub(crate) const fn is_site_calibrated(&self) -> bool {
        matches!(self.calibration_status, CalibrationStatus::Calibrated)
    }

    pub(crate) fn resolve(&self, observer: Geodetic<ECEF>) -> ResolvedSiteProfile {
        let atmosphere = self
            .atmosphere
            .unwrap_or_else(|| AtmosphericConditions::generic_clear_sky(observer));
        ResolvedSiteProfile {
            name: self.name.clone(),
            calibration_status: self.calibration_status,
            atmosphere,
            atmosphere_provenance: self.atmosphere_provenance.clone(),
            airglow: self.airglow.clone(),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ResolvedSiteProfile {
    pub(crate) name: String,
    pub(crate) calibration_status: CalibrationStatus,
    pub(crate) atmosphere: AtmosphericConditions,
    pub(crate) atmosphere_provenance: String,
    pub(crate) airglow: AirglowSiteCalibration,
}

fn validate_nonempty(value: &str, field: &str) -> Result<()> {
    if value.trim().is_empty() {
        return Err(NsbError::OutOfRange(format!("{field} must not be empty")));
    }
    Ok(())
}

fn validate_finite(value: f64, field: &str) -> Result<()> {
    if !value.is_finite() {
        return Err(NsbError::OutOfRange(format!("{field} must be finite")));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use siderust::qtty::{Degrees, Hectopascals, Meters};

    struct MagicLaPalma;
    impl SiteProfileTag for MagicLaPalma {
        const NAME: &'static str = "magic-la-palma-planning";
    }

    struct AliasClearSkyName;
    impl SiteProfileTag for AliasClearSkyName {
        const NAME: &'static str = "generic-clear-sky";
    }

    fn observer(height_m: f64) -> Geodetic<ECEF> {
        Geodetic::new_raw(
            Degrees::new(-17.89),
            Degrees::new(28.76),
            Meters::new(height_m),
        )
    }

    #[test]
    fn generic_profile_derives_pressure_from_observer_altitude_without_calibrating() {
        let profile = SiteProfile::<GenericClearSky>::generic_clear_sky();
        let low = profile.erase().resolve(observer(0.0));
        let high = SiteProfile::<GenericClearSky>::generic_clear_sky()
            .erase()
            .resolve(observer(2_500.0));

        assert_eq!(low.calibration_status, CalibrationStatus::GenericFallback);
        assert_eq!(
            SiteProfile::<GenericClearSky>::generic_clear_sky().calibration_status(),
            CalibrationStatus::GenericFallback
        );
        assert!(!SiteProfile::<GenericClearSky>::generic_clear_sky()
            .erase()
            .is_site_calibrated());
        assert!(low.atmosphere.surface_pressure > high.atmosphere.surface_pressure);
        assert_eq!(low.calibration_status, high.calibration_status);
        assert_eq!(
            SiteProfile::<GenericClearSky>::generic_clear_sky().name(),
            "generic-clear-sky"
        );
    }

    #[test]
    fn external_marker_defines_planning_profile_without_core_catalog() {
        let location = observer(2_200.0);
        let profile = SiteProfile::<MagicLaPalma>::planning(
            Kilometers::new(2.2),
            AtmosphericConditions::clear_sky_with_pressure(Hectopascals::new(770.0)).unwrap(),
            "Caller-defined MAGIC/La Palma planning atmosphere; not a core catalog entry.",
        )
        .unwrap();
        let resolved = profile.clone().erase().resolve(location);

        assert_eq!(profile.name(), "magic-la-palma-planning");
        assert_eq!(
            profile.calibration_status(),
            CalibrationStatus::PlanningPreset
        );
        assert_ne!(resolved.calibration_status, CalibrationStatus::Calibrated);
        assert_eq!(resolved.atmosphere.surface_pressure.value(), 770.0);
        assert!(resolved.atmosphere_provenance.contains("Caller-defined"));
        assert_ne!(
            resolved.atmosphere.surface_pressure,
            SiteProfile::<GenericClearSky>::generic_clear_sky()
                .erase()
                .resolve(location)
                .atmosphere
                .surface_pressure
        );
    }

    #[test]
    fn equal_textual_names_do_not_transfer_scientific_behavior() {
        let location = observer(2_200.0);
        let generic = SiteProfile::<GenericClearSky>::generic_clear_sky();
        let alias = SiteProfile::<AliasClearSkyName>::planning(
            Kilometers::new(2.2),
            AtmosphericConditions::clear_sky_with_pressure(Hectopascals::new(770.0)).unwrap(),
            "External marker that reuses the generic-clear-sky presentation name.",
        )
        .unwrap();

        assert_eq!(generic.name(), alias.name());
        assert_eq!(
            generic.calibration_status(),
            CalibrationStatus::GenericFallback
        );
        assert_eq!(
            alias.calibration_status(),
            CalibrationStatus::PlanningPreset
        );
        assert_ne!(
            generic
                .erase()
                .resolve(location)
                .atmosphere
                .surface_pressure,
            alias.erase().resolve(location).atmosphere.surface_pressure
        );
    }

    #[test]
    fn public_construction_cannot_claim_calibrated_maturity() {
        let profile = SiteProfile::<MagicLaPalma>::planning(
            Kilometers::new(2.2),
            AtmosphericConditions::paranal_average(),
            "planning provenance",
        )
        .unwrap();
        assert_eq!(
            profile.calibration_status(),
            CalibrationStatus::PlanningPreset
        );
        assert_ne!(profile.calibration_status(), CalibrationStatus::Calibrated);
    }

    #[test]
    fn planning_profile_rejects_invalid_scientific_inputs() {
        let mut atmosphere = AtmosphericConditions::paranal_average();
        for pressure in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            atmosphere.surface_pressure = Hectopascals::new(pressure);
            assert!(SiteProfile::<MagicLaPalma>::planning(
                Kilometers::new(1.8),
                atmosphere,
                "custom planning atmosphere provenance",
            )
            .is_err());
        }
        assert!(SiteProfile::<MagicLaPalma>::planning(
            Kilometers::new(f64::NAN),
            AtmosphericConditions::paranal_average(),
            "custom planning atmosphere provenance",
        )
        .is_err());
        assert!(SiteProfile::<MagicLaPalma>::planning(
            Kilometers::new(1.8),
            AtmosphericConditions::paranal_average(),
            "   ",
        )
        .is_err());
    }
}