solunatus 0.6.0

High-precision astronomical calculation library and CLI for sun/moon positions, rise/set times, and lunar phases
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
//! Type-safe astronomical units.
//!
//! This module provides type-safe wrappers for angles and coordinates to prevent
//! common errors like mixing degrees with radians or using invalid coordinate ranges.
//!
//! # Type Safety
//!
//! - [`Degrees`] and [`Radians`] prevent angle unit confusion
//! - [`Latitude`] enforces -90° to 90° range
//! - [`Longitude`] enforces -180° to 180° range
//! - [`Altitude`] represents elevation above horizon
//! - [`Azimuth`] represents compass bearing (0-360°, automatically normalized)

use std::f64::consts::PI;
use std::fmt;

/// Conversion factor from degrees to radians.
pub const DEG_TO_RAD: f64 = PI / 180.0;

/// Conversion factor from radians to degrees.
pub const RAD_TO_DEG: f64 = 180.0 / PI;

/// An angle measured in degrees.
///
/// Provides type safety to prevent mixing degrees with radians in calculations.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Degrees(f64);

impl Degrees {
    /// Create an angle from a value in degrees.
    pub fn new(value: f64) -> Self {
        Self(value)
    }

    /// Return the underlying numeric value as a bare `f64`.
    pub fn value(&self) -> f64 {
        self.0
    }

    /// Normalize to 0-360 range
    pub fn normalized(self) -> Self {
        let mut result = self.0 % 360.0;
        if result < 0.0 {
            result += 360.0;
        }
        Self(result)
    }

    /// Normalize to -180 to 180 range
    pub fn normalized_signed(self) -> Self {
        let mut result = self.0 % 360.0;
        if result > 180.0 {
            result -= 360.0;
        } else if result < -180.0 {
            result += 360.0;
        }
        Self(result)
    }

    /// Convert this angle to [`Radians`].
    pub fn to_radians(self) -> Radians {
        Radians::from(self)
    }

    /// Sine of the angle.
    pub fn sin(self) -> f64 {
        self.0.to_radians().sin()
    }

    /// Cosine of the angle.
    pub fn cos(self) -> f64 {
        self.0.to_radians().cos()
    }

    /// Tangent of the angle.
    pub fn tan(self) -> f64 {
        self.0.to_radians().tan()
    }
}

impl fmt::Display for Degrees {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}°", self.0)
    }
}

impl From<f64> for Degrees {
    fn from(value: f64) -> Self {
        Self(value)
    }
}

impl From<Degrees> for f64 {
    fn from(deg: Degrees) -> f64 {
        deg.0
    }
}

/// An angle measured in radians.
///
/// Provides type safety to prevent mixing radians with degrees in calculations.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Radians(f64);

impl Radians {
    /// Create an angle from a value in radians.
    pub fn new(value: f64) -> Self {
        Self(value)
    }

    /// Return the underlying numeric value as a bare `f64`.
    pub fn value(&self) -> f64 {
        self.0
    }

    /// Convert this angle to [`Degrees`].
    pub fn to_degrees(self) -> Degrees {
        Degrees::from(self)
    }

    /// Sine of the angle.
    pub fn sin(self) -> f64 {
        self.0.sin()
    }

    /// Cosine of the angle.
    pub fn cos(self) -> f64 {
        self.0.cos()
    }

    /// Tangent of the angle.
    pub fn tan(self) -> f64 {
        self.0.tan()
    }

    /// Arcsine of a value, as an angle in radians.
    pub fn asin(value: f64) -> Self {
        Self(value.asin())
    }

    /// Arccosine of a value, as an angle in radians.
    pub fn acos(value: f64) -> Self {
        Self(value.acos())
    }

    /// Four-quadrant arctangent of `y/x`, as an angle in radians.
    pub fn atan2(y: f64, x: f64) -> Self {
        Self(y.atan2(x))
    }
}

impl From<Degrees> for Radians {
    fn from(deg: Degrees) -> Self {
        Self(deg.0 * DEG_TO_RAD)
    }
}

impl From<Radians> for Degrees {
    fn from(rad: Radians) -> Self {
        Self(rad.0 * RAD_TO_DEG)
    }
}

/// Geographic latitude coordinate.
///
/// Valid range: -90° to 90° (negative = South, positive = North).
/// Enforces range validation on creation.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Latitude(f64);

impl Latitude {
    /// Create a latitude from decimal degrees, validating the -90 to 90 range.
    pub fn new(degrees: f64) -> Result<Self, String> {
        if !(-90.0..=90.0).contains(&degrees) {
            Err(format!("Invalid latitude: {} (must be -90 to 90)", degrees))
        } else {
            Ok(Self(degrees))
        }
    }

    /// Create without validation (use only when value is known to be valid)
    pub fn new_unchecked(degrees: f64) -> Self {
        Self(degrees)
    }

    /// Return this value as a type-safe [`Degrees`] angle.
    pub fn degrees(&self) -> Degrees {
        Degrees(self.0)
    }

    /// Return this value as a type-safe [`Radians`] angle.
    pub fn radians(&self) -> Radians {
        Radians(self.0 * DEG_TO_RAD)
    }

    /// Return the underlying numeric value as a bare `f64`.
    pub fn value(&self) -> f64 {
        self.0
    }
}

impl fmt::Display for Latitude {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}° {}",
            self.0.abs(),
            if self.0 >= 0.0 { "N" } else { "S" }
        )
    }
}

/// Geographic longitude coordinate.
///
/// Valid range: -180° to 180° (negative = West, positive = East).
/// Enforces range validation on creation.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Longitude(f64);

impl Longitude {
    /// Create a longitude from decimal degrees, validating the -180 to 180 range.
    pub fn new(degrees: f64) -> Result<Self, String> {
        if !(-180.0..=180.0).contains(&degrees) {
            Err(format!(
                "Invalid longitude: {} (must be -180 to 180)",
                degrees
            ))
        } else {
            Ok(Self(degrees))
        }
    }

    /// Create without validation (use only when value is known to be valid)
    pub fn new_unchecked(degrees: f64) -> Self {
        Self(degrees)
    }

    /// Return this value as a type-safe [`Degrees`] angle.
    pub fn degrees(&self) -> Degrees {
        Degrees(self.0)
    }

    /// Return this value as a type-safe [`Radians`] angle.
    pub fn radians(&self) -> Radians {
        Radians(self.0 * DEG_TO_RAD)
    }

    /// Return the underlying numeric value as a bare `f64`.
    pub fn value(&self) -> f64 {
        self.0
    }
}

impl fmt::Display for Longitude {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}° {}",
            self.0.abs(),
            if self.0 >= 0.0 { "E" } else { "W" }
        )
    }
}

/// Altitude angle (elevation above horizon).
///
/// Range: -90° to 90° (negative = below horizon, positive = above horizon).
/// - 0° = on the horizon
/// - 90° = at zenith (directly overhead)
/// - -90° = at nadir (directly below)
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Altitude(f64);

impl Altitude {
    /// Create an altitude from decimal degrees above (positive) or below (negative) the horizon.
    pub fn from_degrees(degrees: f64) -> Self {
        Self(degrees)
    }

    /// Create an altitude from a value in radians.
    pub fn from_radians(radians: f64) -> Self {
        Self(radians * RAD_TO_DEG)
    }

    /// Return this value as a type-safe [`Degrees`] angle.
    pub fn degrees(&self) -> Degrees {
        Degrees(self.0)
    }

    /// Return this value as a type-safe [`Radians`] angle.
    pub fn radians(&self) -> Radians {
        Radians(self.0 * DEG_TO_RAD)
    }

    /// Return the underlying numeric value as a bare `f64`.
    pub fn value(&self) -> f64 {
        self.0
    }
}

impl fmt::Display for Altitude {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:.2}°", self.0)
    }
}

/// Azimuth angle (compass bearing from North).
///
/// Range: 0° to 360° (automatically normalized).
/// - 0° = North
/// - 90° = East
/// - 180° = South
/// - 270° = West
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Azimuth(f64);

impl Azimuth {
    /// Create an azimuth from decimal degrees, normalizing into the 0-360 range.
    pub fn from_degrees(degrees: f64) -> Self {
        // Normalize to 0-360
        let mut normalized = degrees % 360.0;
        if normalized < 0.0 {
            normalized += 360.0;
        }
        Self(normalized)
    }

    /// Create an azimuth from a value in radians, normalizing into the 0-360 degree range.
    pub fn from_radians(radians: f64) -> Self {
        Self::from_degrees(radians * RAD_TO_DEG)
    }

    /// Return this value as a type-safe [`Degrees`] angle.
    pub fn degrees(&self) -> Degrees {
        Degrees(self.0)
    }

    /// Return this value as a type-safe [`Radians`] angle.
    pub fn radians(&self) -> Radians {
        Radians(self.0 * DEG_TO_RAD)
    }

    /// Return the underlying numeric value as a bare `f64`.
    pub fn value(&self) -> f64 {
        self.0
    }

    /// Return the nearest 8-point compass direction (N, NE, E, SE, S, SW, W, NW).
    pub fn to_compass(&self) -> &'static str {
        let index = ((self.0 + 22.5) / 45.0).floor() as usize % 8;
        ["N", "NE", "E", "SE", "S", "SW", "W", "NW"][index]
    }
}

impl fmt::Display for Azimuth {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:.2}° {}", self.0, self.to_compass())
    }
}

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

    #[test]
    fn test_degrees_to_radians() {
        let deg = Degrees::new(180.0);
        let rad = deg.to_radians();
        assert!((rad.value() - PI).abs() < 0.0001);
    }

    #[test]
    fn test_radians_to_degrees() {
        let rad = Radians::new(PI);
        let deg = rad.to_degrees();
        assert!((deg.value() - 180.0).abs() < 0.0001);
    }

    #[test]
    fn test_degrees_normalize() {
        assert_eq!(Degrees::new(370.0).normalized().value(), 10.0);
        assert_eq!(Degrees::new(-10.0).normalized().value(), 350.0);
    }

    #[test]
    fn test_latitude_validation() {
        assert!(Latitude::new(45.0).is_ok());
        assert!(Latitude::new(-90.0).is_ok());
        assert!(Latitude::new(90.0).is_ok());
        assert!(Latitude::new(91.0).is_err());
        assert!(Latitude::new(-91.0).is_err());
    }

    #[test]
    fn test_longitude_validation() {
        assert!(Longitude::new(0.0).is_ok());
        assert!(Longitude::new(180.0).is_ok());
        assert!(Longitude::new(-180.0).is_ok());
        assert!(Longitude::new(181.0).is_err());
        assert!(Longitude::new(-181.0).is_err());
    }

    #[test]
    fn test_azimuth_normalize() {
        assert_eq!(Azimuth::from_degrees(370.0).value(), 10.0);
        assert_eq!(Azimuth::from_degrees(-10.0).value(), 350.0);
    }

    #[test]
    fn test_azimuth_compass() {
        assert_eq!(Azimuth::from_degrees(0.0).to_compass(), "N");
        assert_eq!(Azimuth::from_degrees(45.0).to_compass(), "NE");
        assert_eq!(Azimuth::from_degrees(90.0).to_compass(), "E");
        assert_eq!(Azimuth::from_degrees(270.0).to_compass(), "W");
    }
}