Debian Codegraph @

src/time.rs

raw symbols SCIP
1 //! # Time, Date, and Angle Handling
2 //!
3 //! This module contains functions for the handling and conversion of Times, Dates, and Angles.
4 //!
5 //! This data can be represented in two types:
6 //! - The [`Angle`] type, which represents anything modulo arithmetic should be used to handle
7 //! - The [`Date`] type, which represents an instant in continuous time
8 //!
9 //! ```rust
10 //! # use pracstro::*;
11 //! time::Date::from_calendar(2024, 06, 30, time::Angle::from_clock(16, 30, 0.0)).julian(); // Gets the julian date at 2024-06-30T16:30:00Z
12 //! ```
13
14 use std::f64::consts::{PI, TAU};
15 use std::fmt;
16 use std::ops::{Add, Div, Mul, Sub};
17
18 /**
19 Angles and Time are the most prominent use for this type
20
21 | Property | To Method | From Method |
22 |-------------------|-------------------------|------------------------------|
23 | Degrees (Decimal) | [`Angle::degrees()`] | [`Angle::from_degrees()`] |
24 | Radians | [`Angle::radians()`] | [`Angle::from_radians()`] |
25 | Turns (\[0,1\]) | [`Angle::turns()`] | [`Angle::from_turns()`] |
26 | Hours (Decimal) | [`Angle::decimal()`] | [`Angle::from_decimal()`] |
27 | Clock Time | [`Angle::clock()`] | [`Angle::from_clock()`] |
28 | Degrees (DMS) | [`Angle::degminsec()`] | [`Angle::from_degminsec()`] |
29 | Sine | [`Angle::sin()`] | [`Angle::asin()`] |
30 | Cosine | [`Angle::cos()`] | [`Angle::acos()`] |
31 | Tangent | [`Angle::tan()`] | [`Angle::atan2()`] |
32
33 Additional Methods:
34 * Latitude displaying: [`Angle::to_latitude()`]
35 * Inverse of angle: [`Angle::inverse()`]
36 * GST Correction: [`Angle::gst()`] and [`Angle::ungst()`]
37 * Approx. Atmosphereic Refraction: [`Angle::refract()`] and [`Angle::refractdelta()`]
38 */
39 #[derive(Clone, Copy, Default, PartialOrd)]
40 pub struct Angle(f64);
41 impl Angle {
42 /// Returns the angle as radians.
43 ///
44 /// This is the only function that should directly access the fields of the type.
45 /// ```
46 /// # use pracstro::time::Angle;
47 /// Angle::from_degrees(180.0).radians(); // Pi
48 /// ```
49 pub const fn radians(self) -> f64 {
50 self.0
51 }
52 /// Constructs a angle from radians, reducing it to the range of \[0, 2*PI\].
53 ///
54 /// This is the one of the two only functions that directly access [`Angle`].
55 /// Reduction to the desired range is done with Least Positive Residue instead of the remainder operator.
56 /// ```
57 /// # use pracstro::time::Angle;
58 /// Angle::from_radians(std::f64::consts::PI).degrees(); // 180.0
59 /// ```
60 pub const fn from_radians(x: f64) -> Self {
61 const fn lpr(x: f64, y: f64) -> f64 {
62 let z = x % y;
63 z + if z < 0.0 { y } else { 0.0 }
64 }
65 Angle(lpr(x, TAU))
66 }
67 /// Converts angles internally so that formatting them as latitudes makes sense
68 ///
69 /// This should be used directly in conjunction with a formatting function.
70 /// The main use case for this is in coordinate handling where angles of latitude can be negative.
71 /// This is the only other function that should be able to directly access [`Angle`] than [`Angle::from_radians()`].
72 /// ```
73 /// # use pracstro::time::Angle;
74 /// Angle::from_degrees(-25.0).degrees(); // 335.0
75 /// Angle::from_degrees(-25.0).to_latitude().degrees(); // -25.0
76 /// ```
77 pub const fn to_latitude(self) -> Self {
78 match self.radians() > PI {
79 true => Angle(self.radians() - TAU),
80 false => self,
81 }
82 }
83
84 /// Returns the angle as fractional degrees.
85 ///
86 /// A wrapper around [`f64::to_degrees()`]
87 ///
88 /// ```
89 /// # use pracstro::time::Angle;
90 /// Angle::from_degrees(-25.0).degrees(); // 335.0
91 /// ```
92 pub const fn degrees(self) -> f64 {
93 self.radians().to_degrees()
94 }
95 /// Constructs an angle from fractional degrees.
96 ///
97 /// A wrapper around [`f64::to_radians()`]
98 ///
99 /// ```
100 /// # use pracstro::time::Angle;
101 /// Angle::from_degrees(-25.0).degrees(); // 335.0
102 /// ```
103 pub const fn from_degrees(x: f64) -> Self {
104 Angle::from_radians(x.to_radians())
105 }
106
107 /// Returns the angle in the range between 0 and 1 (i.e. turns)
108 ///
109 /// Used in the calculation for the illuminated fraction of planets
110 pub const fn turns(self) -> f64 {
111 self.radians() / TAU
112 }
113 /// Constructs an angle from a value between 0 and 1
114 ///
115 /// Used in the calculation for the illuminated fraction of planets
116 pub const fn from_turns(x: f64) -> Self {
117 Self::from_radians(x * TAU)
118 }
119
120 /// Returns the angle in fractional number of hours
121 ///
122 /// A wrapper around [`Angle::degrees()`] and one division by 15. Since one hour is 15 degrees of rotation
123 /// ```
124 /// # use pracstro::time::Angle;
125 /// Angle::from_degrees(120.0).decimal(); // 8.0
126 /// ```
127 pub const fn decimal(self) -> f64 {
128 self.degrees() / 15.0 // 1 hour <-> 15 degrees, 360/24 = 15
129 }
130 /// Constructs an angle from a fractional number of hours
131 ///
132 /// A wrapper around [`Angle::from_degrees()`] and one multiplication by 15. Since one hour is 15 degrees of rotation
133 /// ```
134 /// # use pracstro::time::Angle;
135 /// Angle::from_decimal(8.0).degrees(); // 120.00
136 /// ```
137 pub const fn from_decimal(x: f64) -> Self {
138 Angle::from_degrees(x * 15.0)
139 }
140
141 /// Returns (Hour, Minute, Second) of a time/angle
142 ///
143 /// Used in hour-angle displays for some coordinate systems, and in times.
144 /// ```
145 /// # use pracstro::time::Angle;
146 /// Angle::from_decimal(8.0).clock(); // (8, 0, 0.0)
147 /// ```
148 pub fn clock(self) -> (u8, u8, f64) {
149 let y = self.decimal();
150 (
151 y.trunc() as u8,
152 (y.fract() * 60.0).trunc() as u8,
153 (y.fract() * 60.0).fract() * 60.0,
154 )
155 }
156 /// Constructs an angle out of an hour, minute, and second
157 ///
158 /// Used in hour-angle displays for some coordinate systems, and in times.
159 /// ```
160 /// use pracstro::time::Angle;
161 /// Angle::from_clock(8, 0, 0.0).decimal(); // 8.0
162 /// ```
163 pub const fn from_clock(h: u8, m: u8, s: f64) -> Self {
164 Angle::from_decimal((h as f64) + (((m as f64) + (s / 60.0)) / 60.0))
165 }
166
167 /// Converts an angle to a degree with arcminutes and arcseconds
168 pub fn degminsec(self) -> (i16, u8, f64) {
169 let y = self.degrees();
170 (
171 y.trunc() as i16,
172 (y.fract() * 60.0).trunc() as u8,
173 (y.fract() * 60.0).fract() * 60.0,
174 )
175 }
176 /// Identical to from_clock in math
177 pub const fn from_degminsec(d: i16, m: u8, s: f64) -> Self {
178 Angle::from_degrees((d as f64) + (((m as f64) + (s / 60.0)) / 60.0))
179 }
180
181 /// Handles the discontinuity created by the orbit of the earth as compared to its rotation.
182 ///
183 /// Algorithm from Practical Astronomy with Your Calculator, although similar algorithms exist in other sources
184 pub fn gst(self, date: Date) -> Self {
185 let t = date.centuries();
186 Angle::from_decimal(
187 6.697374558
188 + (2400.051336 * t)
189 + (0.000025862 * (t * t))
190 + (self.decimal() * 1.002737909),
191 )
192 }
193 /// Handles the discontinuity created by the orbit of the earth as compared to its rotation.
194 ///
195 /// Algorithm from Practical Astronomy with Your Calculator, although similar algorithms exist in other sources
196 pub fn ungst(self, date: Date) -> Self {
197 let t = date.centuries();
198 let t0 = Angle::from_decimal(6.697374558 + (2400.051336 * t) + (0.000025862 * (t * t)));
199 (self - t0) * 0.9972695663
200 }
201
202 /// Sine of Angle
203 pub fn sin(self) -> f64 {
204 self.radians().sin()
205 }
206 /// Cosine of Angle
207 pub fn cos(self) -> f64 {
208 self.radians().cos()
209 }
210 /// Tangent of Angle
211 pub fn tan(self) -> f64 {
212 self.radians().tan()
213 }
214 /// Angle from Arcsine
215 pub fn asin(x: f64) -> Self {
216 Angle::from_radians(x.asin())
217 }
218 /// Angle from Arccosine
219 pub fn acos(x: f64) -> Self {
220 Angle::from_radians(x.acos())
221 }
222 /// Angle from 2-argument Arctangent
223 pub fn atan2(x: f64, y: f64) -> Self {
224 Angle::from_radians(x.atan2(y))
225 }
226 /// Reverses the angle
227 pub fn inverse(self) -> Self {
228 Angle::from_radians(TAU - self.radians())
229 }
230
231 /// Calculates the approximate atmospheric refraction
232 ///
233 /// In reality, this is an complex calculation dependent on factors such as temperature and pressure. But it can be
234 /// Approximated to a reasonable extent assuming some factors.
235 ///
236 /// From <https://www.celestialprogramming.com/snippets/atmosphericrefraction.html>
237 pub fn refractdelta(self) -> Self {
238 Angle::from_degminsec(
239 0,
240 0,
241 (1.02
242 / (self.degrees() + (10.3 / (self.degrees() + 5.11)))
243 .to_radians()
244 .tan())
245 * 60.0,
246 )
247 }
248 /// Accounts for atmospheric refraction
249 ///
250 /// This does not calculate refraction on altitudes under the horizon
251 ///
252 /// This should only be used on the altitude value of a horizontal coordinate.
253 pub fn refract(self) -> Self {
254 if self.to_latitude().degrees() > 0.0 {
255 self + self.refractdelta()
256 } else {
257 self
258 }
259 }
260 }
261 /// Used in testing
262 impl fmt::Debug for Angle {
263 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
264 let (d, m, s) = self.degminsec();
265 // Hubble has a resolution of 0.1", this is more than sufficent
266 write!(f, "{}°{}'{:.2}\"", d, m, s)
267 }
268 }
269 /// Does not check if arcseconds are equal
270 impl PartialEq for Angle {
271 fn eq(&self, other: &Self) -> bool {
272 let (d, m, _) = self.degminsec();
273 let (d2, m2, _) = other.degminsec();
274 d == d2 && m == m2
275 }
276 }
277 impl Add<Angle> for Angle {
278 type Output = Angle;
279 /// Addition, For timezones and LST
280 fn add(self, x: Self) -> Self {
281 Angle::from_radians(self.radians() + x.radians())
282 }
283 }
284 impl Sub<Angle> for Angle {
285 type Output = Angle;
286 /// Subtraction, For timezones and LST
287 fn sub(self, x: Self) -> Self {
288 Angle::from_radians(self.radians() - x.radians())
289 }
290 }
291 impl Mul<f64> for Angle {
292 type Output = Angle;
293 /// Multiplication
294 fn mul(self, x: f64) -> Self {
295 Angle::from_radians(self.radians() * x)
296 }
297 }
298 impl Div<f64> for Angle {
299 type Output = Angle;
300 /// Multiplication
301 fn div(self, x: f64) -> Self {
302 Angle::from_radians(self.radians() / x)
303 }
304 }
305
306 /**
307 Continuous Instant in Time
308
309 | Property | To Method | From Method |
310 |-------------------|-----------------------|----------------------------|
311 | Julian Day | [`Date::julian()`] | [`Date::from_julian()`] |
312 | Calendar | [`Date::calendar()`] | [`Date::from_calendar()`] |
313 | Unix Time | [`Date::unix()`] | [`Date::from_unix()`] |
314 | Date/Time | [`Date::time()`] | [`Date::from_time()`] |
315
316 Additional Methods
317 * Get the current time: [`Date::now()`]
318 * Julian Centuries since J2000: [`Date::centuries()`]
319 */
320 #[derive(Debug, PartialEq, Clone, Copy)]
321 pub struct Date(f64);
322 impl Date {
323 /// Returns time as Julian Days
324 ///
325 /// Direct interface to type
326 ///
327 /// This is the only function that should directly read the fields of the type
328 pub const fn julian(self) -> f64 {
329 self.0
330 }
331 /// Constructs time from Julian Days
332 ///
333 /// Direct interface to type
334 ///
335 /// This is the only function that should directly write the fields of the type
336 pub const fn from_julian(x: f64) -> Self {
337 Date(x)
338 }
339
340 /// Returns Julian Centuries since 1900.
341 ///
342 /// Used heavily in astronomical estimation of things that change slowly
343 pub const fn centuries(self) -> f64 {
344 (self.julian() - 2451545.0) / 36525.0
345 }
346
347 /// Returns Year, Month, Day (time is Angle::from_decimal(day.fract()))
348 ///
349 /// Algorithm from Practical Astronomy with Your Calculator, Although similar algorithms exist in other sources
350 pub fn calendar(self) -> (i64, u8, u8, Angle) {
351 let j = self.julian() + 0.5;
352 let (i, f) = (j.trunc(), j.fract());
353
354 let b = if i > 2_299_160.0 {
355 let a = ((i - 1867216.25) / 36524.25).trunc();
356 i + 1.0 + a - (a / 4.0).trunc()
357 } else {
358 i
359 } + 1524.0;
360
361 let d = ((b - 122.2) / 365.25).trunc();
362 let e = (365.25 * d).trunc();
363 let g = ((b - e) / 30.6001).trunc();
364
365 let m = if g < 13.5 { g - 1.0 } else { g - 13.0 };
366 let y = if m > 2.5 { d - 4716.0 } else { d - 4715.0 };
367 let d = b - e + f - (30.6001 * g).trunc();
368
369 (y as i64, m as u8, d as u8, Angle::from_turns(d.fract()))
370 }
371 /// Takes Year, Month, and Day
372 ///
373 /// Algorithm from Practical Astronomy with Your Calculator, although similar algorithms exist in other sources
374 pub fn from_calendar(y: i64, m: u8, day: u8, t: Angle) -> Self {
375 let (year, month) = if m < 3 { (y - 1, m + 12) } else { (y, m) };
376
377 Date::from_julian(
378 if year >= 1582 {
379 2 - (year / 100) + (year / 400)
380 } else {
381 0
382 } as f64
383 + (365.25 * year as f64 - if year < 0 { 0.75 } else { 0.0 }).trunc()
384 + (30.6001 * (month + 1) as f64).trunc()
385 + day as f64
386 + t.turns()
387 + 1_720_994.5,
388 )
389 }
390 /// Gets the time of day in a current calendar date
391 pub fn time(self) -> Angle {
392 self.calendar().3
393 }
394 /// Constructs a date out of a date and a time.
395 pub fn from_time(d: Self, t: Angle) -> Self {
396 let (y, m, d, _) = d.calendar();
397 Self::from_calendar(y, m, d, t)
398 }
399
400 /// Interface for unix time, Does not correct for the 1582 Julain/Gregorian split
401 pub const fn unix(self) -> f64 {
402 (self.julian() - 2440587.5) * 86400.0
403 }
404 /// Interface for unix time, Does not correct for the 1582 Julain/Gregorian split
405 pub const fn from_unix(t: f64) -> Self {
406 Date::from_julian((t / 86400.0) + 2440587.5)
407 }
408
409 /// Gets the current date
410 ///
411 /// Since this function relies on SystemTime and duration_since, it does not work for dates before 1970.
412 pub fn now() -> Self {
413 use std::time::{SystemTime, UNIX_EPOCH};
414 let now = SystemTime::now()
415 .duration_since(UNIX_EPOCH)
416 .expect("Expected pre-1970-01-01 date")
417 .as_secs() as f64;
418 Date::from_unix(now)
419 }
420 }
421
422 /// Calculate the date of Easter
423 pub fn easter(year: i32) -> (i32, i32) {
424 let a = year % 19;
425 let (b, c) = (year / 100, year % 100);
426 let d = b / 4;
427 let g = (b - (b + 8) / 25 + 1) / 3;
428 let h = ((19 * a) + b - d - g + 15) % 30;
429 let l = (32 + (2 * b % 4) + (2 * c / 4) - h - c % 4) % 7;
430 let m = (a + (11 * h) + (22 * l)) / 451;
431 let n = (h + l - (7 * m) + 114) / 31;
432 let p = (h + l - (7 * m) + 114) % 31;
433 (n, p + 1)
434 }
435
436 /// Time at epoch J2000
437 pub const J2000: Date = Date::from_julian(2451545.0);
438
439 #[cfg(test)]
440 mod tests {
441 use super::*;
442
443 #[test]
444 fn test_julian() {
445 assert_eq!(
446 Date::from_julian(2_446_113.75),
447 Date::from_calendar(1985, 2, 17, Angle::from_decimal(6.0))
448 );
449 assert_eq!(
450 Date::from_julian(2_446_113.75).calendar(),
451 (1985, 2, 17, Angle::from_decimal(6.0))
452 );
453 assert_eq!(
454 Date::from_calendar(1967, 04, 12, Angle::from_turns(0.6))
455 .time()
456 .decimal(),
457 14.400000002235174
458 );
459 }
460
461 #[test]
462 fn test_calendar() {
463 assert_eq!(
464 Date::from_calendar(1000, 10, 20, Angle::default()).calendar(),
465 (1000, 10, 20, Angle::default())
466 );
467 assert_eq!(
468 Date::from_calendar(1000, 14, 20, Angle::default()).calendar(),
469 (1001, 2, 20, Angle::default())
470 );
471 }
472
473 #[test]
474 fn test_decimalhrs() {
475 assert_eq!(
476 Angle::from_clock(18, 31, 27.0),
477 Angle::from_decimal(18.52417)
478 );
479 assert_eq!(Angle::from_decimal(11.75), Angle::from_clock(11, 45, 0.0));
480 }
481
482 #[test]
483 fn test_gst() {
484 assert_eq!(
485 Angle::from_clock(14, 36, 51.6).gst(Date::from_julian(2_444_351.5)),
486 Angle::from_clock(4, 40, 5.23)
487 );
488 assert_eq!(
489 Angle::from_clock(4, 40, 5.23).ungst(Date::from_julian(2_444_351.5)),
490 Angle::from_clock(14, 36, 51.6)
491 );
492 }
493
494 #[test]
495 fn test_lati() {
496 assert_eq!(
497 Angle::from_degrees(-25.0).to_latitude().degrees(),
498 -25.00000000000002 // God I hate floating point
499 );
500 }
501
502 #[test]
503 fn test_turn() {
504 assert_eq!(Angle::from_turns(0.5), Angle::from_degrees(180.0));
505 assert_eq!(Angle::from_degrees(180.0), Angle::from_turns(0.5));
506 }
507
508 #[test]
509 fn test_easter() {
510 assert_eq!(easter(2000), (4, 23));
511 assert_eq!(easter(2024), (3, 31));
512 }
513
514 #[test]
515 fn test_refract() {
516 assert_eq!(
517 Angle::from_degrees(25.0).refractdelta(),
518 Angle::from_degminsec(0, 2, 9.2)
519 );
520 assert_eq!(
521 Angle::from_degrees(-25.0).refract(),
522 Angle::from_degminsec(-25, 0, 0.0)
523 );
524 }
525 }