-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathastronomy.cs
12177 lines (10875 loc) · 564 KB
/
astronomy.cs
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Astronomy Engine for C# / .NET.
https://github.com/cosinekitty/astronomy
MIT License
Copyright (c) 2019-2025 Don Cross <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace CosineKitty
{
/// <summary>
/// This exception is thrown by certain Astronomy Engine functions
/// when an invalid attempt is made to use the Earth as the observed
/// celestial body. Usually this happens for cases where the Earth itself
/// is the location of the observer.
/// </summary>
public class EarthNotAllowedException: ArgumentException
{
internal EarthNotAllowedException():
base("The Earth is not allowed as the body parameter.")
{}
}
/// <summary>
/// This exception is thrown by certain Astronomy Engine functions
/// when a body is specified that is not appropriate for the given operation.
/// </summary>
public class InvalidBodyException: ArgumentException
{
internal InvalidBodyException(Body body):
base("Invalid body: " + body)
{}
}
/// <summary>
/// This exception indicates an unexpected error occurred inside Astronomy Engine.
/// Please report any such errors by creating an issue at:
/// https://github.com/cosinekitty/astronomy/issues
/// </summary>
public class InternalError: Exception
{
internal InternalError(string message):
base("Internal error. Please report an issue at: https://github.com/cosinekitty/astronomy/issues. Diagnostic: " + message)
{}
}
/// <summary>Defines a function type for calculating Delta T.</summary>
/// <remarks>
/// Delta T is the discrepancy between times measured using an atomic clock
/// and times based on observations of the Earth's rotation, which is gradually
/// slowing down over time. Delta T = TT - UT, where
/// TT = Terrestrial Time, based on atomic time, and
/// UT = Universal Time, civil time based on the Earth's rotation.
/// Astronomy Engine defaults to using a Delta T function defined by
/// Espenak and Meeus in their "Five Millennium Canon of Solar Eclipses".
/// See: https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html
/// </remarks>
public delegate double DeltaTimeFunc(double ut);
/// <summary>
/// The enumeration of celestial bodies supported by Astronomy Engine.
/// </summary>
public enum Body
{
/// <summary>
/// A placeholder value representing an invalid or unknown celestial body.
/// </summary>
Invalid = -1,
/// <summary>
/// The planet Mercury.
/// </summary>
Mercury,
/// <summary>
/// The planet Venus.
/// </summary>
Venus,
/// <summary>
/// The planet Earth.
/// Some functions that accept a `Body` parameter will fail if passed this value
/// because they assume that an observation is being made from the Earth,
/// and therefore the Earth is not a target of observation.
/// </summary>
Earth,
/// <summary>
/// The planet Mars.
/// </summary>
Mars,
/// <summary>
/// The planet Jupiter.
/// </summary>
Jupiter,
/// <summary>
/// The planet Saturn.
/// </summary>
Saturn,
/// <summary>
/// The planet Uranus.
/// </summary>
Uranus,
/// <summary>
/// The planet Neptune.
/// </summary>
Neptune,
/// <summary>
/// The planet Pluto.
/// </summary>
Pluto,
/// <summary>
/// The Sun.
/// </summary>
Sun,
/// <summary>
/// The Earth's natural satellite, the Moon.
/// </summary>
Moon,
/// <summary>
/// The Earth/Moon Barycenter.
/// </summary>
EMB,
/// <summary>
/// The Solar System Barycenter.
/// </summary>
SSB,
/// <summary>
/// User-defined star #1.
/// </summary>
Star1 = 101,
/// <summary>
/// User-defined star #2.
/// </summary>
Star2,
/// <summary>
/// User-defined star #3.
/// </summary>
Star3,
/// <summary>
/// User-defined star #4.
/// </summary>
Star4,
/// <summary>
/// User-defined star #5.
/// </summary>
Star5,
/// <summary>
/// User-defined star #6.
/// </summary>
Star6,
/// <summary>
/// User-defined star #7.
/// </summary>
Star7,
/// <summary>
/// User-defined star #8.
/// </summary>
Star8,
}
/// <summary>
/// A date and time used for astronomical calculations.
/// </summary>
public class AstroTime
{
private static readonly DateTime Origin = new DateTime(2000, 1, 1, 12, 0, 0, DateTimeKind.Utc);
/// <summary>
/// UT1/UTC number of days since noon on January 1, 2000.
/// </summary>
/// <remarks>
/// The floating point number of days of Universal Time since noon UTC January 1, 2000.
/// Astronomy Engine approximates UTC and UT1 as being the same thing, although they are
/// not exactly equivalent; UTC and UT1 can disagree by up to plus or minus 0.9 seconds.
/// This approximation is sufficient for the accuracy requirements of Astronomy Engine.
///
/// Universal Time Coordinate (UTC) is the international standard for legal and civil
/// timekeeping and replaces the older Greenwich Mean Time (GMT) standard.
/// UTC is kept in sync with unpredictable observed changes in the Earth's rotation
/// by occasionally adding leap seconds as needed.
///
/// UT1 is an idealized time scale based on observed rotation of the Earth, which
/// gradually slows down in an unpredictable way over time, due to tidal drag by the Moon and Sun,
/// large scale weather events like hurricanes, and internal seismic and convection effects.
/// Conceptually, UT1 drifts from atomic time continuously and erratically, whereas UTC
/// is adjusted by a scheduled whole number of leap seconds as needed.
///
/// The value in `ut` is appropriate for any calculation involving the Earth's rotation,
/// such as calculating rise/set times, culumination, and anything involving apparent
/// sidereal time.
///
/// Before the era of atomic timekeeping, days based on the Earth's rotation
/// were often known as *mean solar days*.
/// </remarks>
public readonly double ut;
/// <summary>
/// Terrestrial Time days since noon on January 1, 2000.
/// </summary>
/// <remarks>
/// Terrestrial Time is an atomic time scale defined as a number of days since noon on January 1, 2000.
/// In this system, days are not based on Earth rotations, but instead by
/// the number of elapsed [SI seconds](https://physics.nist.gov/cuu/Units/second.html)
/// divided by 86400. Unlike `ut`, `tt` increases uniformly without adjustments
/// for changes in the Earth's rotation.
///
/// The value in `tt` is used for calculations of movements not involving the Earth's rotation,
/// such as the orbits of planets around the Sun, or the Moon around the Earth.
///
/// Historically, Terrestrial Time has also been known by the term *Ephemeris Time* (ET).
/// </remarks>
public readonly double tt;
internal double psi = double.NaN; // For internal use only. Used to optimize Earth tilt calculations.
internal double eps = double.NaN; // For internal use only. Used to optimize Earth tilt calculations.
internal double st = double.NaN; // For internal use only. Lazy-caches sidereal time (Earth rotation).
private AstroTime(double ut, double tt)
{
this.ut = ut;
this.tt = tt;
}
/// <summary>
/// Creates an `AstroTime` object from a Universal Time day value.
/// </summary>
/// <param name="ut">The number of days after the J2000 epoch.</param>
public AstroTime(double ut)
: this(ut, Astronomy.TerrestrialTime(ut))
{
}
/// <summary>
/// Creates an `AstroTime` object from a .NET `DateTime` object.
/// </summary>
/// <param name="d">The date and time to be converted to AstroTime format.</param>
public AstroTime(DateTime d)
: this((d.ToUniversalTime() - Origin).TotalDays)
{
}
/// <summary>
/// Creates an `AstroTime` object from a UTC year, month, day, hour, minute and second.
/// </summary>
/// <param name="year">The UTC year value.</param>
/// <param name="month">The UTC month value 1..12.</param>
/// <param name="day">The UTC day of the month 1..31.</param>
/// <param name="hour">The UTC hour value 0..23.</param>
/// <param name="minute">The UTC minute value 0..59.</param>
/// <param name="second">The UTC second value [0, 60).</param>
public AstroTime(int year, int month, int day, int hour, int minute, double second)
: this(UniversalTimeFromCalendar(year, month, day, hour, minute, second))
{
}
/// <summary>
/// Creates an `AstroTime` object from a Terrestrial Time day value.
/// </summary>
/// <remarks>
/// This function can be used in rare cases where a time must be based
/// on Terrestrial Time (TT) rather than Universal Time (UT).
/// Most developers will want to invoke `new AstroTime(ut)` with a universal time
/// instead of this function, because usually time is based on civil time adjusted
/// by leap seconds to match the Earth's rotation, rather than the uniformly
/// flowing TT used to calculate solar system dynamics. In rare cases
/// where the caller already knows TT, this function is provided to create
/// an `AstroTime` value that can be passed to Astronomy Engine functions.
/// </remarks>
/// <param name="tt">The number of days after the J2000 epoch.</param>
public static AstroTime FromTerrestrialTime(double tt)
{
return new AstroTime(Astronomy.UniversalTime(tt), tt);
}
/// <summary>
/// Converts this object to .NET `DateTime` format.
/// </summary>
/// <returns>a UTC `DateTime` object for this `AstroTime` value.</returns>
public DateTime ToUtcDateTime()
{
return Origin.AddDays(ut).ToUniversalTime();
}
/// <summary>
/// Converts this object to our custom type #CalendarDateTime.
/// </summary>
/// <remarks>
/// The .NET type `DateTime` can only represent years in the range 0000..9999.
/// However, the Astronomy Engine type #CalendarDateTime can represent
/// years in the range -999999..+999999. This is a time span of nearly 2 million years.
/// This function converts this `AstroTime` object to an equivalent Gregorian calendar representation.
/// </remarks>
public CalendarDateTime ToCalendarDateTime() => new CalendarDateTime(ut);
/// <summary>
/// Converts this `AstroTime` to ISO 8601 format, expressed in UTC with millisecond resolution.
/// </summary>
/// <returns>Example: "2019-08-30T17:45:22.763Z".</returns>
public override string ToString() => ToCalendarDateTime().ToString();
private static Regex re = new Regex(
@"^
([\+\-]?[0-9]{4,6}) # 1 : year : should be 4-digit, or 6-digit with +/- prefix, but be flexible
-(0[0-9]|1[012]) # 2 : month
-([012][0-9]|3[01]) # 3 : day
T([01][0-9]|2[0-3]) # 4 : hour
:([0-5][0-9]) # 5 : minute
( # 6
:
( # 7
[0-5][0-9] # optional seconds
(\.[0-9]+)? # optional fraction of a second
)
)?
Z$ # terminator",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace
);
/// <summary>
/// Converts a string of the format returned by #AstroTime.ToString back into an `AstroTime`.
/// </summary>
/// <remarks>
/// This function attempts to parse an ISO 8601 formatted date and time string
/// into an `AstroTime` object.
/// If the string is valid, sets `time` to a new object and returns `true`.
/// If the string is not valid, sets `time` to `null` and returns `false`.
/// </remarks>
/// <param name="text">The string from which to parse a date and time.</param>
/// <param name="time">On success, receives the date and time value. On failure, receives `null`.</param>
public static bool TryParse(string text, out AstroTime time)
{
time = null;
if (text == null)
return false;
Match m = re.Match(text);
if (!m.Success)
return false;
if (!int.TryParse(m.Groups[1].Value, out int year))
return false;
if (!int.TryParse(m.Groups[2].Value, out int month))
return false;
if (!int.TryParse(m.Groups[3].Value, out int day))
return false;
if (!int.TryParse(m.Groups[4].Value, out int hour))
return false;
if (!int.TryParse(m.Groups[5].Value, out int minute))
return false;
double second = 0.0;
string stext = m.Groups[7].Value;
if (!string.IsNullOrEmpty(stext))
{
var styles = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent;
if (!double.TryParse(stext, styles, CultureInfo.InvariantCulture, out second))
return false;
}
time = new AstroTime(year, month, day, hour, minute, second);
return true;
}
/// <summary>
/// Calculates the sum or difference of an #AstroTime with a specified floating point number of days.
/// </summary>
/// <remarks>
/// Sometimes we need to adjust a given #AstroTime value by a certain amount of time.
/// This function adds the given real number of days in `days` to the date and time in this object.
///
/// More precisely, the result's Universal Time field `ut` is exactly adjusted by `days` and
/// the Terrestrial Time field `tt` is adjusted for the resulting UTC date and time,
/// using a best-fit piecewise polynomial model devised by
/// [Espenak and Meeus](https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html).
/// </remarks>
/// <param name="days">A floating point number of days by which to adjust `time`. May be negative, 0, or positive.</param>
/// <returns>A date and time that is conceptually equal to `time + days`.</returns>
public AstroTime AddDays(double days)
{
return new AstroTime(this.ut + days);
}
/// <summary>
/// Nutation angle `psi`. Intended for unit testing only.
/// </summary>
public double Psi => psi;
/// <summary>
/// Nutation angle `eps`. Intended for unit testing only.
/// </summary>
public double Eps => eps;
private static double UniversalTimeFromCalendar(int year, int month, int day, int hour, int minute, double second)
{
// This formula is adapted from NOVAS C 3.1 function julian_date(),
// which in turn comes from Henry F. Fliegel & Thomas C. Van Flendern:
// Communications of the ACM, Vol 11, No 10, October 1968, p. 657.
// See: https://dl.acm.org/doi/pdf/10.1145/364096.364097
//
// [Don Cross - 2023-02-25] I modified the formula so that it will
// work correctly with years as far back as -999999.
long y = (long)year;
long m = (long)month;
long d = (long)day;
long f = (14 - m) / 12;
long y2000 = (
(d - 365972956)
+ (1461*(y + 1000000 - f))/4
+ (367*(m - 2 + 12*f))/12
- (3*((y + 1000100 - f) / 100))/4
);
double ut = (y2000 - 0.5) + (hour / 24.0) + (minute / 1440.0) + (second / 86400.0);
return ut;
}
}
/// <summary>
/// Represents a Gregorian calendar date and time within plus or minus 1 million years from the year 0.
/// </summary>
/// <remarks>
/// The C# standard type `System.DateTime` only allows years from 0001 to 9999.
/// However, the #AstroTime class can represent years in the range -999999 to +999999.
/// In order to support formatting dates with extreme year values in an extrapolated
/// Gregorian calendar, the `CalendarDateTime` class breaks out the components of
/// a date into separate fields.
/// </remarks>
public struct CalendarDateTime
{
/// <summary>The year value in the range -999999 to +999999.</summary>
public int year;
/// <summary>The calendar month in the range 1..12.</summary>
public int month;
/// <summary>The day of the month in the reange 1..31.</summary>
public int day;
/// <summary>The hour in the range 0..23.</summary>
public int hour;
/// <summary>The minute in the range 0..59.</summary>
public int minute;
/// <summary>The real-valued second in the half-open range [0, 60).</summary>
public double second;
/// <summary>Convert a J2000 day value to a Gregorian calendar date.</summary>
/// <param name="ut">The real-valued number of days since the J2000 epoch.</param>
public CalendarDateTime(double ut)
{
// Adapted from the NOVAS C 3.1 function cal_date().
// Convert fractional days since J2000 into Gregorian calendar date/time.
double djd = ut + 2451545.5;
long jd = (long)Math.Floor(djd);
double x = 24.0 * (djd % 1.0);
if (x < 0.0)
x += 24.0;
hour = (int)x;
x = 60.0 * (x % 1.0);
minute = (int)x;
second = 60.0 * (x % 1.0);
// This is my own adjustment to the NOVAS cal_date logic
// so that it can handle dates much farther back in the past.
// I add c*400 years worth of days at the front,
// then subtract c*400 years at the back,
// which avoids negative values in the formulas that mess up
// the calendar date calculations.
// Any multiple of 400 years has the same number of days,
// because it eliminates all the special cases for leap years.
const long c = 2500;
long k = jd + (68569 + c*146097);
long n = (4 * k) / 146097;
k = k - (146097*n + 3) / 4;
long m = (4000 * (k+1)) / 1461001;
k = k - (1461 * m)/4 + 31;
month = (int) ((80 * k) / 2447);
day = (int) (k - (2447 * month)/80);
k = month / 11;
month = (int) (month + 2 - 12*k);
year = (int) (100 * (n - 49) + m + k - 400*c);
if (year < -999999 || year > +999999)
throw new ArgumentOutOfRangeException("The supplied time is too far from the year 2000 to be represented.");
if (month < 1 || month > 12 || day < 1 || day > 31)
throw new InternalError($"Invalid calendar date calculated: month={month}, day={day}.");
}
/// <summary>
/// Converts this `CalendarDateTime` to ISO 8601 format, expressed in UTC with millisecond resolution.
/// </summary>
/// <returns>Example: "2019-08-30T17:45:22.763Z".</returns>
public override string ToString()
{
int millis = Math.Max(0, Math.Min(59999, (int)Math.Round(second * 1000.0)));
string y;
if (year < 0)
y = "-" + (-year).ToString("000000");
else if (year <= 9999)
y = year.ToString("0000");
else
y = "+" + year.ToString("000000");
return $"{y}-{month:00}-{day:00}T{hour:00}:{minute:00}:{millis/1000:00}.{millis%1000:000}Z";
}
}
internal struct TerseVector
{
public double x;
public double y;
public double z;
public TerseVector(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
public static readonly TerseVector Zero = new TerseVector(0.0, 0.0, 0.0);
public AstroVector ToAstroVector(AstroTime time)
{
return new AstroVector(x, y, z, time);
}
public static TerseVector operator +(TerseVector a, TerseVector b)
{
return new TerseVector(a.x + b.x, a.y + b.y, a.z + b.z);
}
public static TerseVector operator -(TerseVector a, TerseVector b)
{
return new TerseVector(a.x - b.x, a.y - b.y, a.z - b.z);
}
public static TerseVector operator -(TerseVector a)
{
return new TerseVector(-a.x, -a.y, -a.z);
}
public static TerseVector operator *(double s, TerseVector v)
{
return new TerseVector(s*v.x, s*v.y, s*v.z);
}
public static TerseVector operator /(TerseVector v, double s)
{
return new TerseVector(v.x/s, v.y/s, v.z/s);
}
public double Quadrature()
{
return x*x + y*y + z*z;
}
public double Magnitude()
{
return Math.Sqrt(Quadrature());
}
}
/// <summary>
/// A 3D Cartesian vector whose components are expressed in Astronomical Units (AU).
/// </summary>
public struct AstroVector
{
/// <summary>
/// The Cartesian x-coordinate of the vector in AU.
/// </summary>
public double x;
/// <summary>
/// The Cartesian y-coordinate of the vector in AU.
/// </summary>
public double y;
/// <summary>
/// The Cartesian z-coordinate of the vector in AU.
/// </summary>
public double z;
/// <summary>
/// The date and time at which this vector is valid.
/// </summary>
public AstroTime t;
/// <summary>
/// Creates an AstroVector.
/// </summary>
/// <param name="x">A Cartesian x-coordinate expressed in AU.</param>
/// <param name="y">A Cartesian y-coordinate expressed in AU.</param>
/// <param name="z">A Cartesian z-coordinate expressed in AU.</param>
/// <param name="t">The date and time at which this vector is valid.</param>
public AstroVector(double x, double y, double z, AstroTime t)
{
if (t == null)
throw new NullReferenceException("AstroTime parameter is not allowed to be null.");
this.x = x;
this.y = y;
this.z = z;
this.t = t;
}
/// <summary>
/// Converts the vector to a string of the format (x, y, z, t).
/// </summary>
public override string ToString()
{
return $"({x:G16}, {y:G16}, {z:G16}, {t})";
}
// (0.1428571428571428, 1.333333333333333, 3.846153846153846E-07, 2023-02-14T09:45:30.000Z)
private static Regex re = new Regex(
@"^\s*\(\s* # (
([^\s,]+) \s* , \s* # x ,
([^\s,]+) \s* , \s* # y ,
([^\s,]+) \s* , \s* # z ,
([^\s\)]+) \s* \) \s* $ # t )",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace
);
/// <summary>
/// Parses a vector from a string as formatted by #AstroVector.ToString.
/// On success, `vector` receives the vector and the function returns `true`.
/// Otherwise, `vector` receives the value (0, 0, 0, null) and the function returns `false`.
/// </summary>
/// <param name="text">A string of the form "(x, y, z, t)".</param>
/// <param name="vector">Receives the output vector.</param>
public static bool TryParse(string text, out AstroVector vector)
{
vector = new AstroVector();
if (text != null)
{
Match m = re.Match(text);
if (m.Success)
{
var styles = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent;
return (
double.TryParse(m.Groups[1].Value, styles, CultureInfo.InvariantCulture, out vector.x) &&
double.TryParse(m.Groups[2].Value, styles, CultureInfo.InvariantCulture, out vector.y) &&
double.TryParse(m.Groups[3].Value, styles, CultureInfo.InvariantCulture, out vector.z) &&
AstroTime.TryParse(m.Groups[4].Value, out vector.t)
);
}
}
return false;
}
/// <summary>
/// Calculates the total distance in AU represented by this vector.
/// </summary>
/// <returns>The nonnegative length of the Cartisian vector in AU.</returns>
public double Length()
{
return Astronomy.hypot(x, y, z);
}
#pragma warning disable 1591 // we don't need XML documentation for these operator overloads
public static AstroVector operator - (AstroVector a)
{
return new AstroVector(-a.x, -a.y, -a.z, a.t);
}
public static AstroVector operator - (AstroVector a, AstroVector b)
{
return new AstroVector (
a.x - b.x,
a.y - b.y,
a.z - b.z,
VerifyIdenticalTimes(a.t, b.t)
);
}
public static AstroVector operator + (AstroVector a, AstroVector b)
{
return new AstroVector (
a.x + b.x,
a.y + b.y,
a.z + b.z,
VerifyIdenticalTimes(a.t, b.t)
);
}
public static double operator * (AstroVector a, AstroVector b)
{
// the scalar dot product of two vectors
VerifyIdenticalTimes(a.t, b.t);
return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
}
public static AstroVector operator * (double factor, AstroVector a)
{
return new AstroVector(
factor * a.x,
factor * a.y,
factor * a.z,
a.t
);
}
public static AstroVector operator / (AstroVector a, double denom)
{
if (denom == 0.0)
throw new ArgumentException("Attempt to divide a vector by zero.");
return new AstroVector(
a.x / denom,
a.y / denom,
a.z / denom,
a.t
);
}
#pragma warning restore 1591
private static AstroTime VerifyIdenticalTimes(AstroTime a, AstroTime b)
{
if (a.tt != b.tt)
throw new ArgumentException("Attempt to operate on two vectors from different times.");
// If either time has already had its nutation calculated, retain that work.
return !double.IsNaN(a.psi) ? a : b;
}
}
/// <summary>
/// A combination of a position vector and a velocity vector at a given moment in time.
/// </summary>
/// <remarks>
/// A state vector represents the dynamic state of a point at a given moment.
/// It includes the position vector of the point, expressed in Astronomical Units (AU)
/// along with the velocity vector of the point, expressed in AU/day.
/// </remarks>
public struct StateVector
{
/// <summary>
/// The position x-coordinate in AU.
/// </summary>
public double x;
/// <summary>
/// The position y-coordinate in AU.
/// </summary>
public double y;
/// <summary>
/// The position z-coordinate in AU.
/// </summary>
public double z;
/// <summary>
/// The velocity x-component in AU/day.
/// </summary>
public double vx;
/// <summary>
/// The velocity y-component in AU/day.
/// </summary>
public double vy;
/// <summary>
/// The velocity z-component in AU/day.
/// </summary>
public double vz;
/// <summary>
/// The date and time at which this vector is valid.
/// </summary>
public AstroTime t;
/// <summary>
/// Creates an AstroVector.
/// </summary>
/// <param name="x">A position x-coordinate expressed in AU.</param>
/// <param name="y">A position y-coordinate expressed in AU.</param>
/// <param name="z">A position z-coordinate expressed in AU.</param>
/// <param name="vx">A velocity x-component expressed in AU/day.</param>
/// <param name="vy">A velocity y-component expressed in AU/day.</param>
/// <param name="vz">A velocity z-component expressed in AU/day.</param>
/// <param name="t">The date and time at which this state vector is valid.</param>
public StateVector(double x, double y, double z, double vx, double vy, double vz, AstroTime t)
{
if (t == null)
throw new NullReferenceException("AstroTime parameter is not allowed to be null.");
this.x = x;
this.y = y;
this.z = z;
this.vx = vx;
this.vy = vy;
this.vz = vz;
this.t = t;
}
/// <summary>
/// Combines a position vector and a velocity vector into a single state vector.
/// </summary>
/// <param name="pos">A position vector.</param>
/// <param name="vel">A velocity vector.</param>
/// <param name="time">The common time that represents the given position and velocity.</param>
public StateVector(AstroVector pos, AstroVector vel, AstroTime time)
{
if (time == null)
throw new NullReferenceException("AstroTime parameter is not allowed to be null.");
this.x = pos.x;
this.y = pos.y;
this.z = pos.z;
this.vx = vel.x;
this.vy = vel.y;
this.vz = vel.z;
this.t = time;
}
/// <summary>
/// Converts the state vector to a string of the format (x, y, z, vx, vy, vz, t).
/// </summary>
public override string ToString()
{
return $"({x:G16}, {y:G16}, {z:G16}, {vx:G16}, {vy:G16}, {vz:G16}, {t})";
}
/// <summary>
/// Returns the position vector associated with this state vector.
/// </summary>
public AstroVector Position()
{
return new AstroVector(x, y, z, t);
}
/// <summary>
/// Returns the velocity vector associated with this state vector.
/// </summary>
public AstroVector Velocity()
{
return new AstroVector(vx, vy, vz, t);
}
}
/// <summary>
/// Holds the positions and velocities of Jupiter's major 4 moons.
/// </summary>
/// <remarks>
/// The #Astronomy.JupiterMoons function returns an object of this type
/// to report position and velocity vectors for Jupiter's largest 4 moons
/// Io, Europa, Ganymede, and Callisto. Each position vector is relative
/// to the center of Jupiter. Both position and velocity are oriented in
/// the EQJ system (that is, using Earth's equator at the J2000 epoch).
/// The positions are expressed in astronomical units (AU),
/// and the velocities in AU/day.
/// </remarks>
public struct JupiterMoonsInfo
{
/// <summary>The position and velocity of Jupiter's moon Io.</summary>
public StateVector io;
/// <summary>The position and velocity of Jupiter's moon Europa.</summary>
public StateVector europa;
/// <summary>The position and velocity of Jupiter's moon Ganymede.</summary>
public StateVector ganymede;
/// <summary>The position and velocity of Jupiter's moon Callisto.</summary>
public StateVector callisto;
}
/// <summary>
/// A rotation matrix that can be used to transform one coordinate system to another.
/// </summary>
public struct RotationMatrix
{
/// <summary>A normalized 3x3 rotation matrix.</summary>
public readonly double[,] rot;
/// <summary>Creates a rotation matrix.</summary>
/// <param name="rot">A 3x3 array of floating point numbers defining the rotation matrix.</param>
public RotationMatrix(double[,] rot)
{
if (rot == null || rot.GetLength(0) != 3 || rot.GetLength(1) != 3)
throw new ArgumentException("Rotation matrix must be given a 3x3 array.");
this.rot = rot;
}
}
/// <summary>
/// Spherical coordinates: latitude, longitude, distance.
/// </summary>
public struct Spherical
{
/// <summary>The latitude angle: -90..+90 degrees.</summary>
public readonly double lat;
/// <summary>The longitude angle: 0..360 degrees.</summary>
public readonly double lon;
/// <summary>Distance in AU.</summary>
public readonly double dist;
/// <summary>
/// Creates a set of spherical coordinates.
/// </summary>
/// <param name="lat">The latitude angle: -90..+90 degrees.</param>
/// <param name="lon">The longitude angle: 0..360 degrees.</param>
/// <param name="dist">Distance in AU.</param>
public Spherical(double lat, double lon, double dist)
{
this.lat = lat;
this.lon = lon;
this.dist = dist;
}
}
/// <summary>
/// The location of an observer on (or near) the surface of the Earth.
/// </summary>
/// <remarks>
/// This structure is passed to functions that calculate phenomena as observed
/// from a particular place on the Earth.
/// </remarks>
public struct Observer
{
/// <summary>
/// Geographic latitude in degrees north (positive) or south (negative) of the equator.
/// </summary>
public readonly double latitude;
/// <summary>
/// Geographic longitude in degrees east (positive) or west (negative) of the prime meridian at Greenwich, England.
/// </summary>
public readonly double longitude;
/// <summary>
/// The height above (positive) or below (negative) sea level, expressed in meters.
/// </summary>
public readonly double height;
/// <summary>
/// Creates an Observer object.
/// </summary>
/// <param name="latitude">Geographic latitude in degrees north (positive) or south (negative) of the equator.</param>
/// <param name="longitude">Geographic longitude in degrees east (positive) or west (negative) of the prime meridian at Greenwich, England.</param>