@johnmorrisdotca/chikyu-earth 0.57.0 → 0.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,441 @@
1
+ // A satellite's history: a series of element sets, the launch and decay dates, and where it was at any moment from the set nearest that moment. SGP4 is satellite.js (MIT, an optional peer);
2
+ // nothing here fetches anything (the page brings the sets) and nothing touches the screen, so it imports on a server. The space view takes `createHistoryGroup(history)` like any other group.
3
+ import { json2satrec, sgp4 } from "satellite.js";
4
+ import { createSatellites } from "./track.js";
5
+ const EARTH_RADIUS_KM = 6371;
6
+ const DAY_MS = 86_400_000;
7
+ /**
8
+ * The package's stated uncertainty for a low orbit: 1 km, 3 km a day and 1.5 km a day squared from the nearest element set. It was set from what was measured against NASA/JPL Horizons
9
+ * (the ISS from one element set: 25, 59, 108 and 168 km at 5.6, 7.6, 9.6 and 11.6 days) with a margin; a higher orbit, with less drag, is better than this, so it is a ceiling, not a forecast.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { DEFAULT_UNCERTAINTY } from "@johnmorrisdotca/chikyu-earth/satellites";
14
+ *
15
+ * console.log(DEFAULT_UNCERTAINTY.kmPerDay);
16
+ * ```
17
+ */
18
+ export const DEFAULT_UNCERTAINTY = { baseKm: 1, kmPerDay: 3, kmPerDaySquared: 1.5 };
19
+ /**
20
+ * The stated uncertainty, in kilometres, of a satellite's place `days` from its nearest element set (either side).
21
+ *
22
+ * @param days - The distance in days from the nearest set's epoch (the sign is ignored).
23
+ * @param model - The growth to state (`DEFAULT_UNCERTAINTY` when left out).
24
+ * @returns Kilometres, never less than `model.baseKm`.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * import { predictionUncertaintyKm } from "@johnmorrisdotca/chikyu-earth/satellites";
29
+ *
30
+ * console.log(predictionUncertaintyKm(0).toFixed(0), predictionUncertaintyKm(10).toFixed(0)); // 1 181
31
+ * ```
32
+ */
33
+ export function predictionUncertaintyKm(days, model = DEFAULT_UNCERTAINTY) {
34
+ const d = Math.abs(Number.isFinite(days) ? days : 0);
35
+ return model.baseKm + model.kmPerDay * d + model.kmPerDaySquared * d * d;
36
+ }
37
+ /** A date or a number as milliseconds, and whether it was a bare date (then a decay is the end of that day). */
38
+ const moment = (value, end) => {
39
+ if (value === undefined)
40
+ return Number.NaN;
41
+ if (typeof value === "number")
42
+ return value;
43
+ const t = value.trim();
44
+ if (t === "")
45
+ return Number.NaN;
46
+ if (t.length <= 10)
47
+ return Date.parse(`${t}T00:00:00Z`) + (end ? DAY_MS - 1 : 0);
48
+ const iso = t.replace(" ", "T");
49
+ return Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(iso) ? iso : `${iso}Z`);
50
+ };
51
+ const epochOf = (text) => Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(text) ? text : `${text}Z`);
52
+ const placedStatus = (s) => s === "backcast" || s === "tracked" || s === "predicted";
53
+ /**
54
+ * Make the history of one satellite from its element sets (any number, any order, all of one satellite). A set that SGP4 cannot start from is listed in `refused` and left out.
55
+ * It needs satellite.js and imports in a browser or on a server. The sets are the page's: nothing is fetched.
56
+ *
57
+ * @param sets - Element sets in CelesTrak's JSON format, one satellite, as many epochs as the page has.
58
+ * @param options - `launch`, `decay` (else the sets' own `LAUNCH_DATE`, `DECAY_DATE`) and `uncertainty`.
59
+ * @returns The history: `describe(ms)`, `exact(ms, out)`, `trail`, and `group` for the space view.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * import { createSatelliteHistory, type ElementSet } from "@johnmorrisdotca/chikyu-earth/satellites";
64
+ *
65
+ * const set = (epoch: string, meanAnomaly: number): ElementSet => ({
66
+ * OBJECT_NAME: "ISS (ZARYA)",
67
+ * OBJECT_ID: "1998-067A",
68
+ * EPOCH: epoch,
69
+ * MEAN_MOTION: 15.49150046,
70
+ * ECCENTRICITY: 0.0007139,
71
+ * INCLINATION: 51.6332,
72
+ * RA_OF_ASC_NODE: 335.9757,
73
+ * ARG_OF_PERICENTER: 339.3739,
74
+ * MEAN_ANOMALY: meanAnomaly,
75
+ * NORAD_CAT_ID: 25544,
76
+ * BSTAR: 0.00012,
77
+ * MEAN_MOTION_DOT: 0.0001,
78
+ * MEAN_MOTION_DDOT: 0,
79
+ * LAUNCH_DATE: "1998-11-20",
80
+ * });
81
+ * const history = createSatelliteHistory([set("2026-11-02T10:25:21.580320", 20.6961)]);
82
+ * console.log(history.describe(Date.UTC(1990, 0, 1)).status, history.describe(Date.UTC(2026, 10, 3)).status, history.describe(Date.UTC(2026, 10, 20)).status);
83
+ * ```
84
+ */
85
+ export function createSatelliteHistory(sets, options = {}) {
86
+ const model = options.uncertainty ?? DEFAULT_UNCERTAINTY;
87
+ const refused = [];
88
+ const good = [];
89
+ for (const set of sets) {
90
+ const epoch = epochOf(set.EPOCH);
91
+ if (!Number.isFinite(epoch)) {
92
+ refused.push({ noradId: set.NORAD_CAT_ID, epoch: set.EPOCH, reason: "the epoch is not a date" });
93
+ continue;
94
+ }
95
+ try {
96
+ const rec = json2satrec(set);
97
+ const start = sgp4(rec, 0);
98
+ if (!start || !start.position || rec.error !== 0) {
99
+ refused.push({ noradId: set.NORAD_CAT_ID, epoch: set.EPOCH, reason: "SGP4 could not start from these elements" });
100
+ continue;
101
+ }
102
+ good.push({ set, epoch });
103
+ }
104
+ catch (error) {
105
+ refused.push({ noradId: set.NORAD_CAT_ID, epoch: set.EPOCH, reason: error instanceof Error ? error.message : "SGP4 could not start from these elements" });
106
+ }
107
+ }
108
+ good.sort((a, b) => a.epoch - b.epoch);
109
+ const list = good.map((one) => one.set);
110
+ const epochs = good.map((one) => one.epoch);
111
+ const count = list.length;
112
+ const last = list[count - 1];
113
+ // the launch and the decay: the options, else any set that carries them, else (the launch only) the start of the launch year
114
+ const fromSets = (field, end) => {
115
+ for (let i = count - 1; i >= 0; i -= 1) {
116
+ const m = moment(list[i][field], end);
117
+ if (Number.isFinite(m))
118
+ return m;
119
+ }
120
+ return Number.NaN;
121
+ };
122
+ let launch = moment(options.launch, false);
123
+ let launchExact = Number.isFinite(launch);
124
+ if (!launchExact) {
125
+ launch = fromSets("LAUNCH_DATE", false);
126
+ launchExact = Number.isFinite(launch);
127
+ }
128
+ if (!launchExact) {
129
+ const year = /^(\d{4})-\d{3}/.exec(list.find((set) => set.OBJECT_ID)?.OBJECT_ID ?? "");
130
+ launch = year ? Date.UTC(Number(year[1]), 0, 1) : Number.NaN;
131
+ }
132
+ let decay = moment(options.decay, true);
133
+ if (!Number.isFinite(decay))
134
+ decay = fromSets("DECAY_DATE", true);
135
+ const launchedMs = Number.isFinite(launch) ? launch : null;
136
+ const decayedMs = Number.isFinite(decay) ? decay : null;
137
+ const launchAt = launchedMs ?? Number.NEGATIVE_INFINITY;
138
+ const decayAt = decayedMs ?? Number.POSITIVE_INFINITY;
139
+ /** The index of the set whose epoch is nearest `ms` (-1 when there are none): a binary search, no allocation. */
140
+ const nearest = (ms) => {
141
+ if (count === 0)
142
+ return -1;
143
+ let lo = 0;
144
+ let hi = count - 1;
145
+ while (lo < hi) {
146
+ const mid = (lo + hi) >> 1;
147
+ if (epochs[mid] < ms)
148
+ lo = mid + 1;
149
+ else
150
+ hi = mid;
151
+ }
152
+ if (lo > 0 && Math.abs(epochs[lo - 1] - ms) <= Math.abs(epochs[lo] - ms))
153
+ return lo - 1;
154
+ return lo;
155
+ };
156
+ // one SGP4 group for each set, made when it is first needed (a series of years is a long list and most of it is never asked for); the launch and decay are held here, so the group is given none of its own
157
+ const groups = new Array(count);
158
+ const groupFor = (i) => {
159
+ let g = groups[i];
160
+ if (g === undefined) {
161
+ const { LAUNCH_DATE: _launch, DECAY_DATE: _decay, ...rest } = list[i];
162
+ void _launch;
163
+ void _decay;
164
+ const made = createSatellites([rest], { estimateFar: true });
165
+ g = made.count === 1 ? made : null;
166
+ groups[i] = g;
167
+ }
168
+ return g;
169
+ };
170
+ const out6 = new Float64Array(6);
171
+ const describe = (ms) => {
172
+ const i = nearest(ms);
173
+ const epochMs = i < 0 ? 0 : epochs[i];
174
+ const distanceDays = i < 0 ? 0 : Math.abs(ms - epochMs) / DAY_MS;
175
+ let status;
176
+ if (i < 0)
177
+ status = "unplaceable";
178
+ else if (ms < launchAt)
179
+ status = "before-launch";
180
+ else if (ms > decayAt)
181
+ status = "decayed";
182
+ else if (ms > epochs[count - 1])
183
+ status = "predicted";
184
+ else if (ms < epochs[0])
185
+ status = "backcast";
186
+ else
187
+ status = "tracked";
188
+ return { status, setIndex: i, epochMs, distanceDays, uncertaintyKm: placedStatus(status) ? predictionUncertaintyKm(distanceDays, model) : 0, launchedMs, launchExact, decayedMs };
189
+ };
190
+ const place = (ms, out) => {
191
+ const m = describe(ms);
192
+ if (!placedStatus(m.status))
193
+ return m.status;
194
+ const g = groupFor(m.setIndex);
195
+ if (!g || !g.exact(0, ms, out))
196
+ return "unplaceable";
197
+ return m.status;
198
+ };
199
+ const period = (ms) => {
200
+ const i = nearest(ms);
201
+ return (1440 / (list[i]?.MEAN_MOTION || 15)) * 60_000;
202
+ };
203
+ const trailInto = (ms, orbits, out) => {
204
+ const points = Math.floor(out.length / 3);
205
+ if (points < 2 || !placedStatus(place(ms, out6)))
206
+ return 0;
207
+ const span = Math.max(0, orbits) * period(ms);
208
+ let first = -1;
209
+ let lastAt = -1;
210
+ for (let k = 0; k < points; k += 1) {
211
+ const at = ms - span * (1 - k / (points - 1));
212
+ if (!placedStatus(place(at, out6)))
213
+ continue;
214
+ if (first < 0)
215
+ first = k;
216
+ lastAt = k;
217
+ out[k * 3] = out6[0];
218
+ out[k * 3 + 1] = out6[1];
219
+ out[k * 3 + 2] = out6[2];
220
+ }
221
+ if (first < 0)
222
+ return 0;
223
+ // the points before the launch (or after the decay) are not there: the valid ones are moved to the front
224
+ if (first > 0)
225
+ out.copyWithin(0, first * 3, (lastAt + 1) * 3);
226
+ return lastAt - first + 1;
227
+ };
228
+ const history = {
229
+ noradId: last?.NORAD_CAT_ID ?? 0,
230
+ name: last?.OBJECT_NAME ?? "",
231
+ sets: list,
232
+ epochs,
233
+ refused,
234
+ newestEpochMs: count > 0 ? epochs[count - 1] : 0,
235
+ describe,
236
+ exact: place,
237
+ trailInto,
238
+ trail(ms, orbits, points = 120) {
239
+ const path = new Float32Array(Math.max(2, Math.floor(points)) * 3);
240
+ const valid = trailInto(ms, orbits, path);
241
+ return valid === path.length / 3 ? path : path.slice(0, valid * 3);
242
+ },
243
+ get group() {
244
+ return (group ??= createHistoryGroup(history, { count, list, nearest, groupFor, describe }));
245
+ },
246
+ };
247
+ let group;
248
+ return history;
249
+ }
250
+ /** The `Satellites` of a history: one satellite, with every method that takes a moment delegated to the group of the set nearest that moment. */
251
+ function createHistoryGroup(history, inner) {
252
+ const dimmed = new Float32Array(1);
253
+ const shown = new Uint8Array(1);
254
+ const timing = { lastBatchMs: 0, maxBatchMs: 0 };
255
+ const colour = new Float32Array(3);
256
+ let dimVersion = 0;
257
+ let placed = 0;
258
+ let current = Math.max(0, inner.count - 1);
259
+ let pinnedWith = null;
260
+ let estimate = true;
261
+ let step = 1000;
262
+ const refs = () => inner.groupFor(current);
263
+ const choose = (ms) => {
264
+ const m = inner.describe(ms);
265
+ if (m.setIndex >= 0)
266
+ current = m.setIndex;
267
+ const dim = m.status === "predicted" ? 2 : m.distanceDays > 14 ? 1 : 0;
268
+ if (dim !== dimmed[0]) {
269
+ dimmed[0] = dim;
270
+ dimVersion += 1;
271
+ }
272
+ return m;
273
+ };
274
+ const sets = inner.list.length > 0 ? [inner.list[inner.list.length - 1]] : [];
275
+ const group = {
276
+ count: inner.count > 0 ? 1 : 0,
277
+ get sets() {
278
+ const set = inner.list[current];
279
+ sets[0] = set ?? sets[0];
280
+ return sets;
281
+ },
282
+ refused: [],
283
+ maxAgeDays: Number.POSITIVE_INFINITY,
284
+ dimAfterDays: 14,
285
+ dimmed,
286
+ get dimVersion() {
287
+ return dimVersion;
288
+ },
289
+ get propagations() {
290
+ return refs()?.propagations ?? 0;
291
+ },
292
+ timing,
293
+ newestEpochMs: history.newestEpochMs,
294
+ classColour: colour,
295
+ get placed() {
296
+ return placed;
297
+ },
298
+ get fastest() {
299
+ return refs()?.fastest ?? 0;
300
+ },
301
+ get estimateFar() {
302
+ return estimate;
303
+ },
304
+ set estimateFar(value) {
305
+ estimate = value;
306
+ },
307
+ get estimatedCount() {
308
+ return dimmed[0] === 2 && shown[0] === 1 ? 1 : 0;
309
+ },
310
+ estimated: () => dimmed[0] === 2 && shown[0] === 1,
311
+ setStep(ms) {
312
+ step = ms;
313
+ for (let i = 0; i < inner.count; i += 1)
314
+ inner.groupFor(i)?.setStep(ms);
315
+ },
316
+ at(ms, out) {
317
+ const m = choose(ms);
318
+ const g = placedStatus(m.status) ? inner.groupFor(m.setIndex) : null;
319
+ if (!g) {
320
+ out[0] = out[1] = out[2] = 0;
321
+ shown[0] = 0;
322
+ placed = 0;
323
+ return;
324
+ }
325
+ g.setStep(step);
326
+ g.at(ms, out);
327
+ shown[0] = g.visible(0) ? 1 : 0;
328
+ placed = shown[0];
329
+ colour.set(g.classColour);
330
+ },
331
+ visible: () => shown[0] === 1,
332
+ pin(ms) {
333
+ const m = choose(ms);
334
+ const g = placedStatus(m.status) ? inner.groupFor(m.setIndex) : null;
335
+ pinnedWith = g;
336
+ g?.pin(ms);
337
+ },
338
+ arc(ms, spanMs, positions, segments, maxLength = 0) {
339
+ const m = choose(ms);
340
+ const g = placedStatus(m.status) ? inner.groupFor(m.setIndex) : null;
341
+ if (!g) {
342
+ positions.fill(0, 0, 3);
343
+ segments.fill(0, 0, 6);
344
+ shown[0] = 0;
345
+ placed = 0;
346
+ return 0;
347
+ }
348
+ // a satellite that changed set (or came back from before its launch) is pinned again from the set it is now placed by
349
+ if (pinnedWith !== g) {
350
+ g.pin(ms);
351
+ pinnedWith = g;
352
+ }
353
+ const count = g.arc(ms, spanMs, positions, segments, maxLength);
354
+ shown[0] = count;
355
+ placed = count;
356
+ colour.set(g.classColour);
357
+ return count;
358
+ },
359
+ exact(_index, ms, out) {
360
+ return placedStatus(history.exact(ms, out));
361
+ },
362
+ orbit(_index, ms, points) {
363
+ const m = choose(ms);
364
+ const g = placedStatus(m.status) ? inner.groupFor(m.setIndex) : null;
365
+ return g ? g.orbit(0, ms, points) : new Float32Array((points + 1) * 3);
366
+ },
367
+ info(_index, ms) {
368
+ const m = choose(ms);
369
+ if (!placedStatus(m.status))
370
+ return undefined;
371
+ const g = inner.groupFor(m.setIndex);
372
+ const base = g?.info(0, ms);
373
+ if (!base)
374
+ return undefined;
375
+ const info = { ...base, estimated: m.status === "predicted", estimatedDays: m.distanceDays };
376
+ return info;
377
+ },
378
+ };
379
+ return group;
380
+ }
381
+ /**
382
+ * The mean height of a satellite at the epoch of each of its element sets, for a chart of how its orbit rose and fell (a station reboosted, a satellite coming down).
383
+ * The height is averaged over one revolution about the epoch (SGP4 at 24 moments), above the mean Earth radius (6371 km); a set SGP4 cannot start from is left out. Oldest epoch first.
384
+ *
385
+ * @param sets - Element sets of one satellite (or several: each is a point, with its `noradId`).
386
+ * @returns One point for each usable set, sorted by epoch.
387
+ *
388
+ * @example
389
+ * ```ts
390
+ * import { altitudeSeries, type ElementSet } from "@johnmorrisdotca/chikyu-earth/satellites";
391
+ *
392
+ * const set = (epoch: string, motion: number): ElementSet => ({
393
+ * OBJECT_NAME: "ISS (ZARYA)",
394
+ * OBJECT_ID: "1998-067A",
395
+ * EPOCH: epoch,
396
+ * MEAN_MOTION: motion,
397
+ * ECCENTRICITY: 0.0007139,
398
+ * INCLINATION: 51.6332,
399
+ * RA_OF_ASC_NODE: 335.9757,
400
+ * ARG_OF_PERICENTER: 339.3739,
401
+ * MEAN_ANOMALY: 20.6961,
402
+ * NORAD_CAT_ID: 25544,
403
+ * BSTAR: 0.00012,
404
+ * MEAN_MOTION_DOT: 0.0001,
405
+ * MEAN_MOTION_DDOT: 0,
406
+ * });
407
+ * const series = altitudeSeries([set("2026-11-02T10:25:21", 15.49), set("2026-10-02T10:25:21", 15.52)]);
408
+ * console.log(series.map((p) => p.altitudeKm.toFixed(0)));
409
+ * ```
410
+ */
411
+ export function altitudeSeries(sets) {
412
+ const series = [];
413
+ const SAMPLES = 24;
414
+ for (const set of sets) {
415
+ const epochMs = epochOf(set.EPOCH);
416
+ if (!Number.isFinite(epochMs))
417
+ continue;
418
+ try {
419
+ const rec = json2satrec(set);
420
+ if (rec.error !== 0)
421
+ continue;
422
+ const periodMin = 1440 / set.MEAN_MOTION;
423
+ let sum = 0;
424
+ let used = 0;
425
+ for (let k = 0; k < SAMPLES; k += 1) {
426
+ const result = sgp4(rec, (k / SAMPLES - 0.5) * periodMin);
427
+ if (!result || !result.position || !Number.isFinite(result.position.x))
428
+ continue;
429
+ sum += Math.hypot(result.position.x, result.position.y, result.position.z);
430
+ used += 1;
431
+ }
432
+ if (used < SAMPLES)
433
+ continue;
434
+ series.push({ epochMs, altitudeKm: sum / used - EARTH_RADIUS_KM, noradId: set.NORAD_CAT_ID });
435
+ }
436
+ catch {
437
+ // a set SGP4 cannot start from is left out
438
+ }
439
+ }
440
+ return series.sort((a, b) => a.epochMs - b.epochMs);
441
+ }
@@ -1,4 +1,5 @@
1
1
  export { createSatellites, type SatellitesOptions } from "./track.ts";
2
+ export { altitudeSeries, createSatelliteHistory, DEFAULT_UNCERTAINTY, predictionUncertaintyKm, type AltitudePoint, type HistoryMoment, type HistoryOptions, type HistoryStatus, type SatelliteHistory, type UncertaintyModel } from "./history.ts";
2
3
  export { NEAREST_COUNT, closeApproach, nearest, overheadKm, within, type Neighbour, type NearestOptions, type NearestTarget } from "./nearest.ts";
3
4
  export { DEFAULT_DIM_AFTER_DAYS, DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.ts";
4
5
  export type { ElementSet, RefusedElementSet, SatelliteInfo, SatelliteRef, Satellites } from "./types.ts";
@@ -1,5 +1,6 @@
1
1
  // The satellites' pure parts: orbital elements in, positions out (SGP4 by satellite.js, an optional peer). They import on a server. The space view takes a group with `setSatellites`.
2
2
  export { createSatellites } from "./track.js";
3
+ export { altitudeSeries, createSatelliteHistory, DEFAULT_UNCERTAINTY, predictionUncertaintyKm } from "./history.js";
3
4
  export { NEAREST_COUNT, closeApproach, nearest, overheadKm, within } from "./nearest.js";
4
5
  export { DEFAULT_DIM_AFTER_DAYS, DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.js";
5
6
  export { SHORT_NAMES } from "./names.js";
@@ -23,8 +23,11 @@ export interface SatellitesOptions {
23
23
  /**
24
24
  * Keep placing a satellite beyond `maxAgeDays` from its element set, as an estimate (off by default): the same elements carried forward or back by the same SGP4 code, where the satellite would be had its orbit not changed.
25
25
  * Never before its launch date or after its decay date when the elements carry them (`LAUNCH_DATE`, `DECAY_DATE`; else the launch year in `OBJECT_ID` marks the earliest), and a satellite that SGP4 cannot carry that far, or brings down below about 120 km, is left out.
26
+ *
27
+ * `true` carries the elements on with their air drag left in, so with nobody to boost it a low satellite sinks in the model and is left out some months or years on. `"steady"` switches the drag off beyond `maxAgeDays`: the satellite keeps the height and
28
+ * shape its orbit had on that day, for as long as the clock runs, while the orbit's plane and low point go on turning as the Earth's flattening turns them. It is the satellite's usual orbit, not a prediction. Up to `maxAgeDays` the two are the same, and the place does not jump where one hands over to the other.
26
29
  */
27
- estimateFar?: boolean;
30
+ estimateFar?: boolean | "steady";
28
31
  }
29
32
  /**
30
33
  * Make a group of satellites from their element sets. Each starts SGP4 once here; one that does not (bad numbers, decayed at its own epoch) is listed in `refused` and left out.