-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathephemeris.service.ts
More file actions
1445 lines (1250 loc) Β· 42.8 KB
/
ephemeris.service.ts
File metadata and controls
1445 lines (1250 loc) Β· 42.8 KB
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
/**
* Core ephemeris calculation service using NASA JPL Horizons data.
*
* This module provides functions to query NASA's JPL Horizons system for precise
* celestial body positions and properties. It handles data retrieval, parsing,
* caching, and type-safe access to ephemeris values.
*
* @remarks
* Data sources:
* - NASA JPL Horizons API (https://ssd.jpl.nasa.gov/horizons/)
* - DE431 ephemeris for planetary positions
* - 1-minute sampling interval for high temporal resolution
* - SQLite caching to minimize API calls and improve performance
*
* Ephemeris types:
* - Coordinate: Ecliptic longitude/latitude for aspect calculations
* - Orbit: Orbital elements for lunar nodes and apsides
* - Azimuth/Elevation: Horizon coordinates for rise/set/culmination
* - Illumination: Illuminated fraction for phase detection
* - Diameter: Angular diameter for eclipse calculations
* - Distance: Distance from Earth for phase and apsis events
*
* @see {@link https://ssd.jpl.nasa.gov/horizons/manual.html} for Horizons documentation
* @see {@link ./ephemeris.constants#} for API configuration
* @see {@link ./ephemeris.types#} for data structures
*/
import _ from "lodash";
import moment from "moment-timezone";
import { nodes } from "../constants";
import {
type EphemerisRecord,
getEphemerisRecords,
upsertEphemerisValues,
} from "../database.utilities";
import { fetchWithRetry } from "../fetch.utilities";
import { arcsecondsPerDegree, normalizeDegrees } from "../math.utilities";
import { symbolByBody } from "../symbols";
import {
commandIdByBody,
dateRegex,
decimalRegex,
horizonsUrl,
QUANTITY_ANGULAR_DIAMETER,
QUANTITY_APPARENT_AZIMUTH_ELEVATION,
QUANTITY_ECLIPTIC_LONGITUDE_LATITUDE,
QUANTITY_ILLUMINATED_FRACTION,
QUANTITY_RANGE_RATE,
} from "./ephemeris.constants";
import type { Asteroid, Body, Comet, Node, Planet } from "../types";
import type {
AzimuthElevationEphemeris,
AzimuthElevationEphemerisBody,
CoordinateEphemeris,
Coordinates,
DiameterEphemeris,
DiameterEphemerisBody,
DistanceEphemeris,
DistanceEphemerisBody,
IlluminationEphemeris,
IlluminationEphemerisBody,
Latitude,
Longitude,
OrbitEphemeris,
OrbitEphemerisBody,
} from "./ephemeris.types";
// #region Utilities
/**
* Calculates the expected number of ephemeris records for a date range.
*
* Ephemeris data is sampled at 1-minute intervals, so this returns the number
* of minutes between start and end (inclusive).
*
* @param start - Range start date
* @param end - Range end date
* @returns Expected number of 1-minute interval records
*
* @remarks
* Used for cache validation to detect incomplete data requiring API refetch.
* Adds 1 to include both boundary timestamps (inclusive range).
*
* @example
* ```typescript
* const start = new Date('2026-01-21T00:00:00');
* const end = new Date('2026-01-21T01:00:00');
* const count = getExpectedRecordCount(start, end);
* // count === 61 (0:00, 0:01, 0:02, ..., 1:00)
* ```
*/
function getExpectedRecordCount(start: Date, end: Date): number {
// Ephemeris data is fetched at 1-minute intervals
const diffInMs = end.getTime() - start.getTime();
const diffInMinutes = Math.floor(diffInMs / (1000 * 60));
// Add 1 to include both start and end timestamps
return diffInMinutes + 1;
}
/**
* Safely extracts coordinate data (longitude or latitude) from ephemeris at a timestamp.
*
* Provides type-safe access to ephemeris values with null-checking to prevent
* runtime errors from missing data.
*
* @param ephemeris - Coordinate ephemeris object indexed by ISO timestamp
* @param timestamp - ISO 8601 timestamp string (e.g., "2026-01-21T12:00:00.000Z")
* @param fieldName - Field to extract ("longitude" or "latitude")
* @returns Coordinate value in degrees
* @throws When timestamp is missing from ephemeris
* @throws When specified field is undefined at timestamp
*
* @remarks
* - Longitude: 0-360Β° along ecliptic (0Β° = vernal equinox)
* - Latitude: -90Β° to +90Β° perpendicular to ecliptic
*
* @see {@link getCoordinatesEphemeris} for ephemeris retrieval
* @see {@link CoordinateEphemeris} for data structure
*
* @example
* ```typescript
* const ephemeris = await getCoordinatesEphemeris({...});
* const longitude = getCoordinateFromEphemeris(
* ephemeris,
* '2026-01-21T12:00:00.000Z',
* 'longitude'
* );
* // Returns: 125.4 (degrees along ecliptic)
* ```
*/
export function getCoordinateFromEphemeris(
ephemeris: CoordinateEphemeris,
timestamp: string,
fieldName: "longitude" | "latitude",
): number {
const data = ephemeris[timestamp];
if (data?.[fieldName] === undefined) {
throw new Error(`Missing ${fieldName} at ${timestamp}`);
}
return data[fieldName];
}
/**
* Safely extracts azimuth or elevation data from horizon coordinate ephemeris.
*
* Provides type-safe access to horizon coordinate values for rise/set/culmination calculations.
*
* @param ephemeris - Azimuth/elevation ephemeris indexed by ISO timestamp
* @param timestamp - ISO 8601 timestamp string
* @param fieldName - Field to extract ("azimuth" or "elevation")
* @returns Coordinate value in degrees
* @throws When timestamp is missing from ephemeris
* @throws When specified field is undefined at timestamp
*
* @remarks
* - Azimuth: 0-360Β° measured clockwise from north (0Β°=N, 90Β°=E, 180Β°=S, 270Β°=W)
* - Elevation: -90Β° to +90Β° above horizon (0Β°=horizon, 90Β°=zenith, -90Β°=nadir)
* - Negative elevation indicates body is below horizon (not visible)
*
* @see {@link getAzimuthElevationEphemeris} for ephemeris retrieval
* @see {@link getDailySolarCycleEvents} for sunrise/sunset detection using elevation
*
* @example
* ```typescript
* const sunEphemeris = await getAzimuthElevationEphemeris({body: 'sun', ...});
* const elevation = getAzimuthElevationFromEphemeris(
* sunEphemeris,
* '2026-01-21T06:30:00.000Z',
* 'elevation'
* );
* // Returns: -6.2 (degrees below horizon, civil twilight)
* ```
*/
export function getAzimuthElevationFromEphemeris(
ephemeris: AzimuthElevationEphemeris,
timestamp: string,
fieldName: "azimuth" | "elevation",
): number {
const data = ephemeris[timestamp];
if (data?.[fieldName] === undefined) {
throw new Error(`Missing ${fieldName} at ${timestamp}`);
}
return data[fieldName];
}
/**
* Safely extracts illumination fraction from ephemeris for phase calculations.
*
* Provides type-safe access to illuminated fraction values used for detecting
* lunar phases and planetary phase events.
*
* @param ephemeris - Illumination ephemeris indexed by ISO timestamp
* @param timestamp - ISO 8601 timestamp string
* @param fieldName - Field description (unused but kept for API consistency)
* @returns Illuminated fraction as a decimal (0.0 to 1.0)
* @throws When timestamp is missing from ephemeris
* @throws When illumination value is undefined at timestamp
*
* @remarks
* Illumination values:
* - 0.0: New moon (not illuminated)
* - 0.5: First/last quarter (half illuminated)
* - 1.0: Full moon (fully illuminated)
*
* For inner planets (Venus, Mercury, Mars), illumination varies based on
* their position relative to Earth and Sun.
*
* @see {@link getIlluminationEphemeris} for ephemeris retrieval
* @see {@link getMonthlyLunarCycleEvents} for lunar phase detection
* @see {@link getPlanetaryPhaseEvents} for planetary phase detection
*
* @example
* ```typescript
* const moonEphemeris = await getIlluminationEphemeris({body: 'moon', ...});
* const illumination = getIlluminationFromEphemeris(
* moonEphemeris,
* '2026-01-21T12:00:00.000Z',
* 'illumination'
* );
* // Returns: 0.87 (87% illuminated, waxing gibbous)
* ```
*/
export function getIlluminationFromEphemeris(
ephemeris: IlluminationEphemeris,
timestamp: string,
fieldName: string,
): number {
const data = ephemeris[timestamp];
if (data?.illumination === undefined) {
throw new Error(`Missing ${fieldName} at ${timestamp}`);
}
return data.illumination;
}
/**
* Safely extracts distance from Earth from ephemeris for apsis and phase calculations.
*
* Provides type-safe access to distance values used for detecting perihelion/aphelion
* and determining planetary phase transitions.
*
* @param ephemeris - Distance ephemeris indexed by ISO timestamp
* @param timestamp - ISO 8601 timestamp string
* @param fieldName - Field description (unused but kept for API consistency)
* @returns Distance from Earth in astronomical units (AU)
* @throws When timestamp is missing from ephemeris
* @throws When distance value is undefined at timestamp
*
* @remarks
* Distance values are heliocentric for planets and geocentric for the Moon.
* 1 AU β 149,597,871 km (average Earth-Sun distance).
*
* Typical distances:
* - Sun: 0.983-1.017 AU (perihelion-aphelion)
* - Venus: 0.27-1.72 AU (varies greatly with orbital position)
* - Mars: 0.37-2.68 AU (large variation due to orbital eccentricity)
*
* @see {@link getDistanceEphemeris} for ephemeris retrieval
* @see {@link getSolarApsisEvents} for perihelion/aphelion detection
*
* @example
* ```typescript
* const sunEphemeris = await getDistanceEphemeris({body: 'sun', ...});
* const distance = getDistanceFromEphemeris(
* sunEphemeris,
* '2026-01-21T12:00:00.000Z',
* 'distance'
* );
* // Returns: 0.984 (AU, near perihelion)
* ```
*/
export function getDistanceFromEphemeris(
ephemeris: DistanceEphemeris,
timestamp: string,
fieldName: string,
): number {
const data = ephemeris[timestamp];
if (data?.distance === undefined) {
throw new Error(`Missing ${fieldName} at ${timestamp}`);
}
return data.distance;
}
/**
* Safely extracts angular diameter from ephemeris for eclipse calculations.
*
* Provides type-safe access to apparent angular diameter values used for
* determining eclipse types (total vs. annular vs. partial).
*
* @param ephemeris - Diameter ephemeris indexed by ISO timestamp
* @param timestamp - ISO 8601 timestamp string
* @param fieldName - Field description (unused but kept for API consistency)
* @returns Angular diameter in degrees
* @throws When timestamp is missing from ephemeris
* @throws When diameter value is undefined at timestamp
*
* @remarks
* Angular diameter represents the apparent size of a body as seen from Earth.
* Values are converted from arcseconds to degrees internally.
*
* Typical values:
* - Sun: ~0.53Β° (31.6-32.7 arcminutes, varies with Earth's distance)
* - Moon: ~0.52Β° (29.3-34.1 arcminutes, varies with lunar distance)
*
* Eclipse classification:
* - Total solar eclipse: Moon's diameter \> Sun's diameter
* - Annular solar eclipse: Moon's diameter \< Sun's diameter
* - Total lunar eclipse: Moon fully within Earth's umbral shadow
*
* @see {@link getDiameterEphemeris} for ephemeris retrieval
* @see {@link getEclipseEvents} for eclipse detection and classification
*
* @example
* ```typescript
* const moonEphemeris = await getDiameterEphemeris({body: 'moon', ...});
* const diameter = getDiameterFromEphemeris(
* moonEphemeris,
* '2026-01-21T12:00:00.000Z',
* 'diameter'
* );
* // Returns: 0.518 (degrees, ~31 arcminutes)
* ```
*/
export function getDiameterFromEphemeris(
ephemeris: DiameterEphemeris,
timestamp: string,
fieldName: string,
): number {
const data = ephemeris[timestamp];
if (data?.diameter === undefined) {
throw new Error(`Missing ${fieldName} at ${timestamp}`);
}
return data.diameter;
}
function getHorizonsBaseUrl(args: {
start: Date;
end: Date;
coordinates?: Coordinates;
}): URL {
const { start, end, coordinates } = args;
const url = new URL(horizonsUrl);
url.searchParams.append("format", "text");
url.searchParams.append("MAKE_EPHEM", "YES");
url.searchParams.append("OBJ_DATA", "NO");
url.searchParams.append("START_TIME", start.toISOString());
url.searchParams.append("STOP_TIME", end.toISOString());
url.searchParams.append("STEP_SIZE", `1m`);
if (coordinates) {
const [longitude, latitude] = coordinates;
const siteCoords = `'${longitude},${latitude},0'`;
url.searchParams.append("SITE_COORD", siteCoords);
}
return url;
}
// #region π« Orbit
function parseOrbitEphemeris(text: string): OrbitEphemeris {
const ephemerisTable = text.split("$$SOE")[1]?.split("$$EOE")[0]?.trim();
const datePattern = /\d{4}-[A-Za-z]{3}-\d{2} \d{2}:\d{2}:\d{2}(\.\d{4})?/g;
const pattern = new RegExp(
`(${datePattern.source})${String.raw`[\s\S]*?`}(?=${datePattern.source}|$)`,
"g",
);
const getPattern = (key: string): RegExp => {
return new RegExp(String.raw`${key}.*?=.+?(\d+\.\d+(E[+-]\d{2})?)`, "g");
};
const orbitEphemeris: OrbitEphemeris = [
...(ephemerisTable?.matchAll(pattern) ?? []),
].reduce<OrbitEphemeris>((orbitEphemeris, match) => {
const [fullMatch, dateString] = match;
const date = moment
.utc(dateString, ["YYYY-MMM-DD HH:mm:ss.SSSS", "YYYY-MMM-DD HH:mm:ss"])
.toISOString();
const ecMatch = [...fullMatch.matchAll(getPattern("EC"))][0]?.[1] ?? "";
const qrMatch = [...fullMatch.matchAll(getPattern("QR"))][0]?.[1] ?? "";
const inMatch = [...fullMatch.matchAll(getPattern("IN"))][0]?.[1] ?? "";
const omMatch = [...fullMatch.matchAll(getPattern("OM"))][0]?.[1] ?? "";
const wMatch = [...fullMatch.matchAll(getPattern("W"))][0]?.[1] ?? "";
const tpMatch = [...fullMatch.matchAll(getPattern("Tp"))][0]?.[1] ?? "";
const nMatch = [...fullMatch.matchAll(getPattern("N"))][0]?.[1] ?? "";
const maMatch = [...fullMatch.matchAll(getPattern("MA"))][0]?.[1] ?? "";
const taMatch = [...fullMatch.matchAll(getPattern("TA"))][0]?.[1] ?? "";
const aMatch = [...fullMatch.matchAll(getPattern("A"))][0]?.[1] ?? "";
const adMatch = [...fullMatch.matchAll(getPattern("AD"))][0]?.[1] ?? "";
const prMatch = [...fullMatch.matchAll(getPattern("PR"))][0]?.[1] ?? "";
return {
...orbitEphemeris,
[date]: {
argumentOfPerifocus: Number.parseFloat(wMatch),
eccentricity: Number.parseFloat(ecMatch),
inclination: Number.parseFloat(inMatch),
timeOfPeriapsis: Number.parseFloat(tpMatch),
longitudeOfAscendingNode: Number.parseFloat(omMatch),
meanAnomaly: Number.parseFloat(maMatch),
periapsisDistance: Number.parseFloat(qrMatch),
meanMotion: Number.parseFloat(nMatch),
trueAnomaly: Number.parseFloat(taMatch),
semiMajorAxis: Number.parseFloat(aMatch),
apoapsisDistance: Number.parseFloat(adMatch),
siderealOrbitPeriod: Number.parseFloat(prMatch),
},
};
}, {});
return orbitEphemeris;
}
function getOrbitEphemerisUrl(args: {
body: OrbitEphemerisBody;
end: Date;
start: Date;
}): URL {
const { body, end, start } = args;
const url = getHorizonsBaseUrl({ end, start });
url.searchParams.append("EPHEM_TYPE", "ELEMENTS");
url.searchParams.append("CENTER", "500@399");
url.searchParams.append("COMMAND", commandIdByBody[body]);
return url;
}
/**
*
*/
export async function getOrbitEphemeris(args: {
body: OrbitEphemerisBody;
end: Date;
start: Date;
timezone: string;
}): Promise<OrbitEphemeris> {
const { body, end, start, timezone } = args;
const timespan = `${moment.tz(start, timezone).toISOString(true)} to ${moment
.tz(end, timezone)
.toISOString(true)}`;
const message = `orbit ephemeris π« for ${symbolByBody[body]} from ${timespan}`;
console.log(`π Fetching ${message}`);
const url = getOrbitEphemerisUrl({ body, end, start });
const text = await fetchWithRetry(url.toString());
const orbitEphemeris = parseOrbitEphemeris(text);
console.log(`π Fetched ${message}`);
return orbitEphemeris;
}
/**
*
*/
export async function getNodeCoordinatesEphemeris(args: {
end: Date;
node: Node;
start: Date;
timezone: string;
}): Promise<CoordinateEphemeris> {
const { end, node, start, timezone } = args;
const timespan = `${moment.tz(start, timezone).toISOString(true)} to ${moment
.tz(end, timezone)
.toISOString(true)}`;
const message = `coordinate ephemeris π― for ${symbolByBody[node]} from ${timespan}`;
// Check if data exists in database
console.log(`π Querying database for ${message}`);
const existingRecords = await getEphemerisRecords({
body: node,
start,
end,
type: "coordinate",
});
const expectedCount = getExpectedRecordCount(start, end);
const hasAllValues = existingRecords.every(
(record) => record.latitude && record.longitude,
);
if (existingRecords.length === expectedCount && hasAllValues) {
console.log(`π’οΈ Found complete database data for ${message}`);
return convertRecordsToCoordinateEphemeris(existingRecords);
} else if (existingRecords.length > 0) {
console.log(
`π’οΈ Found incomplete database data (${existingRecords.length}/${expectedCount} records) for ${message}, fetching from API`,
);
}
console.log(`π Fetching ${message}`);
const nodeOrbitEphemeris = await getOrbitEphemeris({
body: "moon",
start,
end,
timezone,
});
const nodeEphemeris: CoordinateEphemeris = _.mapValues(
nodeOrbitEphemeris,
(nodeOrbitEphemerisValue: OrbitEphemeris[string]) => {
const { longitudeOfAscendingNode, argumentOfPerifocus } =
nodeOrbitEphemerisValue;
switch (node) {
case "north lunar node": {
return { longitude: longitudeOfAscendingNode, latitude: 0 };
}
case "south lunar node": {
return {
longitude: normalizeDegrees(longitudeOfAscendingNode + 180),
latitude: 0,
};
}
case "lunar perigee": {
return {
longitude: normalizeDegrees(
longitudeOfAscendingNode + argumentOfPerifocus,
),
latitude: 0,
};
}
case "lunar apogee": {
return {
longitude: normalizeDegrees(
longitudeOfAscendingNode + argumentOfPerifocus + 180,
),
latitude: 0,
};
}
default: {
throw new Error(`Unknown node: ${node}`);
}
}
},
);
console.log(`π Fetched ${message}`);
console.log(`π’οΈ Upserting ${message}`);
await upsertEphemerisValues(
convertCoordinateEphemerisToRecords(node, nodeEphemeris),
);
console.log(`π’οΈ Upserted ${message}`);
return nodeEphemeris;
}
// #region π Coordinates
function parseCoordinatesEphemeris(text: string): CoordinateEphemeris {
const ephemerisTable = text.split("$$SOE")[1]?.split("$$EOE")[0]?.trim();
if (!ephemerisTable) {
throw new Error("No coordinate ephemeris data found");
}
const ephemeris: CoordinateEphemeris = ephemerisTable
.split("\n")
.filter((line) => line.trim().length > 0)
.reduce<CoordinateEphemeris>((ephemeris, ephemerisLine) => {
const parts = ephemerisLine.trim().split(/\s+/);
// Format: "YYYY-MMM-DD HH:mm longitude latitude"
const dateString = `${parts[0]} ${parts[1]}`;
const longitudeString = parts[2];
const latitudeString = parts[3];
const date = moment.utc(dateString, "YYYY-MMM-DD HH:mm").toDate();
const latitude: Latitude = Number(latitudeString);
const longitude: Longitude = Number(longitudeString);
return { ...ephemeris, [date.toISOString()]: { latitude, longitude } };
}, {});
return ephemeris;
}
function convertCoordinateEphemerisToRecords(
body: Body,
coordinateEphemeris: CoordinateEphemeris,
): EphemerisRecord[] {
return _.map(
_.toPairs(coordinateEphemeris),
([timestampIso, { latitude, longitude }]) => ({
body,
timestamp: new Date(timestampIso),
latitude,
longitude,
}),
);
}
function convertRecordsToCoordinateEphemeris(
records: EphemerisRecord[],
): CoordinateEphemeris {
return records.reduce<CoordinateEphemeris>((acc, record) => {
if (record.latitude === undefined || record.longitude === undefined) {
throw new Error(
`Record at ${record.timestamp.toISOString()} is missing latitude or longitude value`,
);
}
return {
...acc,
[record.timestamp.toISOString()]: {
latitude: record.latitude,
longitude: record.longitude,
},
};
}, {});
}
function getCoordinatesEphemerisUrl(args: {
body: Planet | Asteroid | Comet;
start: Date;
end: Date;
}): URL {
const { body, start, end } = args;
const url = getHorizonsBaseUrl({ start, end });
url.searchParams.append("EPHEM_TYPE", "OBSERVER");
url.searchParams.append("QUANTITIES", QUANTITY_ECLIPTIC_LONGITUDE_LATITUDE);
url.searchParams.append("CENTER", "500@399"); // earth
url.searchParams.append("COMMAND", commandIdByBody[body]);
return url;
}
/**
*
*/
export async function getCoordinatesEphemeris(args: {
body: Planet | Asteroid | Comet;
start: Date;
end: Date;
timezone: string;
}): Promise<CoordinateEphemeris> {
const { body, start, end, timezone } = args;
const timespan = `${moment.tz(start, timezone).toISOString(true)} to ${moment
.tz(end, timezone)
.toISOString(true)}`;
const message = `coordinate ephemeris π― for ${symbolByBody[body]} from ${timespan}`;
// Check if data exists in database
console.log(`π Querying database for ${message}`);
const existingRecords = await getEphemerisRecords({
body,
start,
end,
type: "coordinate",
});
const expectedCount = getExpectedRecordCount(start, end);
const hasAllValues = existingRecords.every(
(record) => record.latitude !== undefined && record.longitude !== undefined,
);
if (existingRecords.length === expectedCount && hasAllValues) {
console.log(`π’οΈ Found complete database data for ${message}`);
return convertRecordsToCoordinateEphemeris(existingRecords);
} else {
console.log(
`π’οΈ Found incomplete database data (${existingRecords.length}/${expectedCount} records) for ${message}, fetching from API`,
);
}
console.log(`π Fetching ${message}`);
const url = getCoordinatesEphemerisUrl({ body, start, end });
const text = await fetchWithRetry(url.toString());
const ephemeris = parseCoordinatesEphemeris(text);
console.log(`π Fetched ${message}`);
console.log(`π’οΈ Upserting ${message}`);
await upsertEphemerisValues(
convertCoordinateEphemerisToRecords(body, ephemeris),
);
console.log(`π’οΈ Upserted ${message}`);
return ephemeris;
}
function isNode(body: string): body is Node {
return nodes.includes(body as Node);
}
/**
*
*/
export async function getCoordinateEphemerisByBody(args: {
bodies: Body[];
start: Date;
end: Date;
timezone: string;
}): Promise<Record<Body, CoordinateEphemeris>> {
const { bodies, start, end, timezone } = args;
const bodiesString = bodies.map((body: Body) => symbolByBody[body]).join(" ");
const timespan = `${moment.tz(start, timezone).toISOString(true)} to ${moment
.tz(end, timezone)
.toISOString(true)}`;
const message = `coordinate ephemerides π― for ${bodiesString} from ${timespan}`;
console.log(`π Getting ${message}`);
const coordinateEphemerisByBody = {} as Record<Body, CoordinateEphemeris>;
for (const body of bodies) {
coordinateEphemerisByBody[body] = await (isNode(body)
? getNodeCoordinatesEphemeris({
end,
node: body,
start,
timezone,
})
: getCoordinatesEphemeris({
body,
end,
start,
timezone,
}));
}
console.log(`π Got ${message}`);
return coordinateEphemerisByBody;
}
// #region β« Azimuth Elevation
function parseAzimuthElevationEphemeris(
text: string,
): AzimuthElevationEphemeris {
const ephemerisTable = text.split("$$SOE")[1]?.split("$$EOE")[0]?.trim();
if (!ephemerisTable) {
throw new Error("No azimuth elevation ephemeris data found");
}
const ephemeris: AzimuthElevationEphemeris = ephemerisTable
.split("\n ")
.reduce<AzimuthElevationEphemeris>((ephemeris, ephemerisLine) => {
const regexString = String.raw`${dateRegex.source}.+?${decimalRegex.source}\s+?${decimalRegex.source}`;
const azimuthElevationRegex = new RegExp(regexString);
const match = ephemerisLine.match(azimuthElevationRegex);
if (!match) {
return ephemeris;
}
const [, dateString, azimuthString, elevationString] = match;
const date = moment.utc(dateString, "YYYY-MMM-DD HH:mm").toDate();
const elevation = Number(elevationString);
const azimuth = Number(azimuthString);
return { ...ephemeris, [date.toISOString()]: { elevation, azimuth } };
}, {});
return ephemeris;
}
function convertAzimuthElevationEphemerisToRecords(
body: Body,
azimuthElevationEphemeris: AzimuthElevationEphemeris,
): EphemerisRecord[] {
return _.map(
_.toPairs(azimuthElevationEphemeris),
([timestampIso, { azimuth, elevation }]) => ({
body,
timestamp: new Date(timestampIso),
azimuth,
elevation,
}),
);
}
function convertRecordsToAzimuthElevationEphemeris(
records: EphemerisRecord[],
): AzimuthElevationEphemeris {
return records.reduce<AzimuthElevationEphemeris>((acc, record) => {
if (record.azimuth === undefined || record.elevation === undefined) {
throw new Error(
`Record at ${record.timestamp.toISOString()} is missing azimuth or elevation value`,
);
}
return {
...acc,
[record.timestamp.toISOString()]: {
azimuth: record.azimuth,
elevation: record.elevation,
},
};
}, {});
}
function getAzimuthElevationEphemerisUrl(args: {
body: AzimuthElevationEphemerisBody;
coordinates: Coordinates;
end: Date;
start: Date;
}): URL {
const { body, coordinates, end, start } = args;
const url = getHorizonsBaseUrl({ start, end, coordinates });
url.searchParams.append("EPHEM_TYPE", "OBSERVER");
url.searchParams.append("QUANTITIES", QUANTITY_APPARENT_AZIMUTH_ELEVATION);
url.searchParams.append("CENTER", "coord@399"); // earth, specific location
url.searchParams.append("COMMAND", commandIdByBody[body]);
return url;
}
/**
*
*/
export async function getAzimuthElevationEphemeris(args: {
body: AzimuthElevationEphemerisBody;
coordinates: Coordinates;
end: Date;
start: Date;
timezone: string;
}): Promise<AzimuthElevationEphemeris> {
const { body, coordinates, end, start, timezone } = args;
const timespan = `${moment.tz(start, timezone).toISOString(true)} to ${moment
.tz(end, timezone)
.toISOString(true)}`;
const message = `azimuth elevation ephemeris β« for ${symbolByBody[body]} from ${timespan}`;
// Check if data exists in database
console.log(`π Querying database for ${message}`);
const existingRecords = await getEphemerisRecords({
body,
start,
end,
type: "azimuthElevation",
});
const expectedCount = getExpectedRecordCount(start, end);
const hasAllValues = existingRecords.every(
(record) => record.azimuth !== undefined && record.elevation !== undefined,
);
if (existingRecords.length === expectedCount && hasAllValues) {
console.log(`π’οΈ Found complete database data for ${message}`);
return convertRecordsToAzimuthElevationEphemeris(existingRecords);
} else {
console.log(
`π’οΈ Found incomplete database data (${existingRecords.length}/${expectedCount} records) for ${message}, fetching from API`,
);
}
console.log(`π Fetching ${message}`);
const url = getAzimuthElevationEphemerisUrl({
start,
end,
coordinates,
body,
});
const text = await fetchWithRetry(url.toString());
const ephemeris = parseAzimuthElevationEphemeris(text);
console.log(`π Fetched ${message}`);
console.log(`π’οΈ Upserting ${message}`);
await upsertEphemerisValues(
convertAzimuthElevationEphemerisToRecords(body, ephemeris),
);
console.log(`π’οΈ Upserted ${message}`);
return ephemeris;
}
/**
*
*/
export async function getAzimuthElevationEphemerisByBody(args: {
bodies: AzimuthElevationEphemerisBody[];
start: Date;
end: Date;
coordinates: Coordinates;
timezone: string;
}): Promise<Record<Body, AzimuthElevationEphemeris>> {
const { bodies, start, end, coordinates, timezone } = args;
const bodiesString = bodies.map((body: Body) => symbolByBody[body]).join(" ");
const timespan = `${moment.tz(start, timezone).toISOString(true)} to ${moment
.tz(end, timezone)
.toISOString(true)}`;
const message = `azimuth elevation ephemerides β« for ${bodiesString} from ${timespan}`;
console.log(`π Getting ${message}`);
const azimuthElevationEphemerisByBody = {} as Record<
Body,
AzimuthElevationEphemeris
>;
for (const body of bodies) {
azimuthElevationEphemerisByBody[body] = await getAzimuthElevationEphemeris({
body,
end,
start,
coordinates,
timezone,
});
}
console.log(`π Got ${message}`);
return azimuthElevationEphemerisByBody;
}
// #region π Illumination
function parseIlluminationEphemeris(text: string): IlluminationEphemeris {
const ephemerisTable = text.split("$$SOE")[1]?.split("$$EOE")[0]?.trim();
if (!ephemerisTable) {
throw new Error("No illumination ephemeris data found");
}
const ephemeris: IlluminationEphemeris = ephemerisTable
.split("\n ")
.reduce<IlluminationEphemeris>((ephemeris, ephemerisLine) => {
const regexString = `${dateRegex.source}.+?${decimalRegex.source}`;
const illuminatedFractionRegex = new RegExp(regexString);
const match = ephemerisLine.match(illuminatedFractionRegex);
if (!match) {
return ephemeris;
}
const [, dateString, illuminationString] = match;
const date = moment.utc(dateString, "YYYY-MMM-DD HH:mm").toDate();
const illumination = Number(illuminationString);
return { ...ephemeris, [date.toISOString()]: { illumination } };
}, {});
return ephemeris;
}
function convertIlluminationEphemerisToRecords(
body: Body,
illuminationEphemeris: IlluminationEphemeris,
): EphemerisRecord[] {
return _.map(
_.toPairs(illuminationEphemeris),
([timestampIso, { illumination }]) => ({
body,
timestamp: new Date(timestampIso),
illumination,
}),
);
}
function convertRecordsToIlluminationEphemeris(
records: EphemerisRecord[],
): IlluminationEphemeris {
return records.reduce<IlluminationEphemeris>((acc, record) => {
if (record.illumination === undefined) {
throw new Error(
`Record at ${record.timestamp.toISOString()} is missing illumination value`,
);
}
return {
...acc,
[record.timestamp.toISOString()]: {
illumination: record.illumination,
},
};
}, {});
}
function getIlluminationEphemerisUrl(args: {
body: IlluminationEphemerisBody;
start: Date;
end: Date;
coordinates: Coordinates;
}): URL {
const { body, start, end, coordinates } = args;