@johnmorrisdotca/wakusei-planets 0.21.0 → 0.23.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,399 @@
1
+ // Which bodies are nearest to a body on a date, and when two bodies come closest over a span: for the Sun, the planets, the dwarf planets and the moons, by the angle between them in the sky of an observer
2
+ // or by the distance between them in space. The positions are this package's own (heliocentric, ephemeris.ts): a sky angle is astrometric (the Earth's or the observer's place at the date, the body's place when
3
+ // its light left, no aberration or light bending), a distance is the geometry at one instant. Each result carries the accuracy the theories are held to (docs/guides/accuracy.md). Pure: no DOM, no three.js.
4
+ import { heliocentric, heliocentricModel, meanSunAu, moonVector } from "./ephemeris.js";
5
+ import { julianCenturies } from "./clock.js";
6
+ import { BODIES, BODY_IDS } from "./facts.js";
7
+ import { ORBITS } from "./data/orbits.js";
8
+ import { moonTheoryOf } from "./data/theories.js";
9
+ import { eclipticJ2000ToTrueEquatorialOfDate } from "./sky/frames.js";
10
+ import { observerVector } from "./sky/engine.js";
11
+ import { cross, DEG, length, scale, sub } from "./vec.js";
12
+ import { moment } from "./when.js";
13
+ const AU_KM = 149_597_870.7;
14
+ const LIGHT_SECONDS_PER_AU = 499.004784;
15
+ const DAY_MS = 86_400_000;
16
+ const ARCSECONDS_PER_RADIAN = 206_264.806;
17
+ const KINDS = ["star", "planet", "dwarf-planet", "moon"];
18
+ /** The worst direction error from the Sun in arc-seconds over 60 dates from 1800 to 2200, as the accuracy guide holds each planet to. */
19
+ const PLANET_ARCSECONDS = { mercury: 4.5, venus: 2.6, earth: 4, mars: 6, jupiter: 3.6, saturn: 5.7, uranus: 5, neptune: 3.4, pluto: 0.2 };
20
+ /** The same for a dwarf planet inside its fitted table's years. */
21
+ const DWARF_ARCSECONDS = { ceres: 0.3, orcus: 0.1, haumea: 0.1, quaoar: 0.15, makemake: 0.15, gonggong: 0.1, eris: 0.1, sedna: 0.1 };
22
+ /** A dwarf planet outside its table's years runs on the osculating elements of one epoch, and Pluto outside 1800 to 2200 on JPL's approximate elements. */
23
+ const OSCULATING_ARCSECONDS = 3600;
24
+ const APPROXIMATE_ARCSECONDS = 120;
25
+ /** The worst direction error from the planet in degrees over 60 dates, for the Moon and each moon; a moon the accuracy guide does not measure is given 5 degrees. */
26
+ const MOON_DEGREES = {
27
+ moon: 0.0016, phobos: 0.55, deimos: 0.55, io: 0.15, europa: 0.05, ganymede: 0.03, callisto: 0.02,
28
+ mimas: 2.1, enceladus: 0.72, tethys: 0.27, dione: 0.23, rhea: 0.27, titan: 0.06, iapetus: 0.04,
29
+ miranda: 3, ariel: 0.3, umbriel: 0.28, titania: 0.52, oberon: 0.6,
30
+ triton: 0.17, nereid: 6.3, proteus: 0.17, charon: 0.06, nix: 2.6, hydra: 2.1,
31
+ };
32
+ /** The same for the moons of Jupiter and Saturn when `tables` has not been imported and their fitted orbits answer. */
33
+ const FITTED_MOON_DEGREES = { io: 0.15, europa: 0.18, ganymede: 0.6, callisto: 0.09, mimas: 7.5, enceladus: 0.72, tethys: 0.45, dione: 0.23, rhea: 0.27, titan: 0.08, iapetus: 0.72 };
34
+ const finite = (name, value) => {
35
+ if (typeof value !== "number" || !Number.isFinite(value))
36
+ throw new RangeError(`${name} must be a finite number, got ${String(value)}`);
37
+ return value;
38
+ };
39
+ function bodyOf(name, value) {
40
+ if (typeof value !== "string" || !BODY_IDS.includes(value))
41
+ throw new RangeError(`${name} must be a body such as "mars" or "io", got ${JSON.stringify(value)}`);
42
+ return value;
43
+ }
44
+ function byOf(by) {
45
+ if (by === undefined)
46
+ return "sky";
47
+ if (by !== "sky" && by !== "space")
48
+ throw new RangeError(`by must be "sky" or "space", got ${JSON.stringify(by)}`);
49
+ return by;
50
+ }
51
+ function viewOf(observer) {
52
+ if (observer === undefined)
53
+ return { body: "earth" };
54
+ if (typeof observer === "string")
55
+ return { body: bodyOf("observer", observer) };
56
+ if (typeof observer !== "object" || observer === null)
57
+ throw new TypeError(`observer must be a body name or { latitude, longitude }, got ${String(observer)}`);
58
+ const latitude = finite("observer.latitude", observer.latitude);
59
+ const longitude = finite("observer.longitude", observer.longitude);
60
+ if (latitude < -90 || latitude > 90)
61
+ throw new RangeError(`observer.latitude must be between -90 and 90, got ${latitude}`);
62
+ return { body: "earth", place: { latitude, longitude, heightM: observer.heightM === undefined ? 0 : finite("observer.heightM", observer.heightM) } };
63
+ }
64
+ /** A body's centre in the Sun's frame (J2000 ecliptic, au) at an instant. */
65
+ function placeAu(id, ms) {
66
+ if (id === "sun")
67
+ return [0, 0, 0];
68
+ const facts = BODIES[id];
69
+ if (facts.kind !== "moon")
70
+ return heliocentric(id, ms);
71
+ const host = heliocentric(facts.parent ?? "earth", ms);
72
+ const offset = moonVector(id, ms);
73
+ return [host[0] + offset[0] / AU_KM, host[1] + offset[1] / AU_KM, host[2] + offset[2] / AU_KM];
74
+ }
75
+ /** The unit direction to a body and its distance in km from a view at an instant, with the light time allowed for. */
76
+ function sight(view, id, ms) {
77
+ const origin = placeAu(view.body, ms);
78
+ let emit = ms;
79
+ let v = sub(placeAu(id, emit), origin);
80
+ for (let i = 0; i < 2; i += 1) {
81
+ emit = ms - length(v) * LIGHT_SECONDS_PER_AU * 1000;
82
+ v = sub(placeAu(id, emit), origin);
83
+ }
84
+ if (view.place !== undefined) {
85
+ const turned = eclipticJ2000ToTrueEquatorialOfDate(scale(v, AU_KM), julianCenturies(ms));
86
+ const topocentric = sub(turned, observerVector(view.place, ms));
87
+ const km = length(topocentric);
88
+ return { v: scale(topocentric, 1 / km), km };
89
+ }
90
+ const km = length(v) * AU_KM;
91
+ return { v: scale(v, 1 / length(v)), km };
92
+ }
93
+ function sample(by, view, ids, ms) {
94
+ const at = new Map();
95
+ for (const id of ids)
96
+ at.set(id, by === "sky" ? sight(view, id, ms) : { v: placeAu(id, ms), km: 0 });
97
+ return at;
98
+ }
99
+ /** Degrees between two unit directions, or kilometres between two positions in au; atan2 keeps it exact near 0 and 180 degrees. */
100
+ function separation(by, a, b) {
101
+ if (by === "space")
102
+ return length(sub(a.v, b.v)) * AU_KM;
103
+ return Math.atan2(length(cross(a.v, b.v)), a.v[0] * b.v[0] + a.v[1] * b.v[1] + a.v[2] * b.v[2]) * DEG;
104
+ }
105
+ function hostErrorKm(host, ms) {
106
+ const model = heliocentricModel(host, ms);
107
+ const arcseconds = model.theory === "vsop87b" ? PLANET_ARCSECONDS[host] : model.theory === "chebyshev" ? (PLANET_ARCSECONDS[host] ?? DWARF_ARCSECONDS[host]) : model.theory === "osculating-elements" ? OSCULATING_ARCSECONDS : APPROXIMATE_ARCSECONDS;
108
+ return length(heliocentric(host, ms)) * AU_KM * Math.tan(arcseconds / ARCSECONDS_PER_RADIAN);
109
+ }
110
+ /** The independent parts of how far a body's place may be off, kilometres: the planet it goes round (which its moons share) and its own part. */
111
+ function partsOf(id, ms) {
112
+ const parts = new Map();
113
+ if (id === "sun")
114
+ return parts;
115
+ const facts = BODIES[id];
116
+ if (facts.kind !== "moon")
117
+ return parts.set(id, hostErrorKm(id, ms));
118
+ const host = facts.parent ?? "earth";
119
+ const fitted = host === "jupiter" || host === "saturn" ? moonTheoryOf(id) === undefined : false;
120
+ const degrees = (fitted ? FITTED_MOON_DEGREES[id] : undefined) ?? MOON_DEGREES[id] ?? 5;
121
+ parts.set(host, hostErrorKm(host, ms));
122
+ return parts.set(`${id} orbit`, length(moonVector(id, ms)) * Math.tan((degrees * Math.PI) / 180));
123
+ }
124
+ /**
125
+ * How far the separation of a and b may be off: each part of the places' errors moves a and b by its size over their distance, in the same direction for a part they share (the planet two moons go round,
126
+ * the Earth's own error seen from the Earth), so a shared part cancels in the difference. The parts add in quadrature; a part is taken as acting across the line of sight, the worst case.
127
+ */
128
+ function separationError(a, b, from, distanceA, distanceB, ms) {
129
+ const parts = [partsOf(a, ms), partsOf(b, ms), from === undefined ? new Map() : partsOf(from, ms)];
130
+ let sum = 0;
131
+ for (const key of new Set(parts.flatMap((part) => [...part.keys()]))) {
132
+ const size = parts.find((part) => part.has(key)).get(key);
133
+ const onA = (parts[0].has(key) ? 1 : 0) - (parts[2].has(key) ? 1 : 0);
134
+ const onB = (parts[1].has(key) ? 1 : 0) - (parts[2].has(key) ? 1 : 0);
135
+ sum += (size * onA / distanceA - size * onB / distanceB) ** 2;
136
+ }
137
+ return Math.sqrt(sum);
138
+ }
139
+ function skyUncertainty(view, a, b, at, ms) {
140
+ return separationError(a, b, view.body, at.get(a).km, at.get(b).km, ms) * ARCSECONDS_PER_RADIAN;
141
+ }
142
+ function spaceUncertainty(a, b, ms) {
143
+ return separationError(a, b, undefined, 1, 1, ms);
144
+ }
145
+ function kindsOf(kind) {
146
+ if (kind === undefined)
147
+ return undefined;
148
+ const list = typeof kind === "string" ? [kind] : kind;
149
+ for (const one of list)
150
+ if (!KINDS.includes(one))
151
+ throw new RangeError(`kind must be one of ${KINDS.join(", ")}, got ${JSON.stringify(one)}`);
152
+ return list;
153
+ }
154
+ function lookup(target, options, defaultCount) {
155
+ bodyOf("target", target);
156
+ const by = byOf(options.by);
157
+ const view = viewOf(options.observer);
158
+ const ms = options.date === undefined ? Date.now() : moment(options.date, "date");
159
+ const kinds = kindsOf(options.kind);
160
+ const radius = options.within === undefined ? Infinity : finite("within", options.within);
161
+ if (radius < 0)
162
+ throw new RangeError(`within must not be negative, got ${radius}`);
163
+ const count = options.count === undefined ? (options.within === undefined ? defaultCount ?? 5 : Infinity) : finite("count", options.count);
164
+ if (count < 0 || !Number.isInteger(count) && count !== Infinity)
165
+ throw new RangeError(`count must be a whole number of 0 or more, got ${count}`);
166
+ if (by === "sky" && target === view.body)
167
+ throw new RangeError(`target ${target} is where the sky is seen from (the observer), so it is not in that sky`);
168
+ const pool = (options.bodies ?? BODY_IDS).map((id) => bodyOf("bodies", id));
169
+ const ids = pool.filter((id) => id !== target && (by === "space" || id !== view.body) && (kinds === undefined || kinds.includes(BODIES[id].kind)));
170
+ const at = sample(by, view, [target, ...ids], ms);
171
+ const here = at.get(target);
172
+ const rows = ids.map((id) => ({ id, value: separation(by, here, at.get(id)) })).filter((row) => row.value <= radius).sort((a, b) => a.value - b.value).slice(0, count);
173
+ if (by === "sky")
174
+ return rows.map((row) => ({ id: row.id, kind: BODIES[row.id].kind, angle: row.value, uncertaintyArcseconds: skyUncertainty(view, target, row.id, at, ms) }));
175
+ return rows.map((row) => ({ id: row.id, kind: BODIES[row.id].kind, distanceKm: row.value, distanceAu: row.value / AU_KM, uncertaintyKm: spaceUncertainty(target, row.id, ms) }));
176
+ }
177
+ export function nearest(target, options = {}) {
178
+ return lookup(target, options, undefined);
179
+ }
180
+ export function within(target, radius, options = {}) {
181
+ return lookup(target, { ...options, within: radius, count: undefined }, undefined);
182
+ }
183
+ /** Days a body takes to go once round what it goes round (the Earth's own orbit for the Earth). */
184
+ function periodDays(id) {
185
+ if (id === "sun")
186
+ return Infinity;
187
+ const facts = BODIES[id];
188
+ if (facts.kind === "moon")
189
+ return 360 / Math.abs(ORBITS[id]?.sid ?? 1);
190
+ return 365.25 * Math.pow(meanSunAu(id), 1.5);
191
+ }
192
+ /** How far apart to look: the fastest body of the pairs goes round forty times in this many steps, never more than two days. */
193
+ function stepMs(ids, view) {
194
+ const fastest = Math.min(...ids.map(periodDays), periodDays(view.body));
195
+ return Math.max(60_000, Math.min(2 * DAY_MS, (fastest * DAY_MS) / 40));
196
+ }
197
+ const GOLDEN = (Math.sqrt(5) - 1) / 2;
198
+ /** The moment of the smallest value of a function with one minimum in [low, high], to within `tolerance` ms. */
199
+ function golden(f, low, high, tolerance) {
200
+ let a = low;
201
+ let b = high;
202
+ let c = b - GOLDEN * (b - a);
203
+ let d = a + GOLDEN * (b - a);
204
+ let fc = f(c);
205
+ let fd = f(d);
206
+ while (b - a > tolerance) {
207
+ if (fc < fd) {
208
+ b = d;
209
+ d = c;
210
+ fd = fc;
211
+ c = b - GOLDEN * (b - a);
212
+ fc = f(c);
213
+ }
214
+ else {
215
+ a = c;
216
+ c = d;
217
+ fc = fd;
218
+ d = a + GOLDEN * (b - a);
219
+ fd = f(d);
220
+ }
221
+ }
222
+ return (a + b) / 2;
223
+ }
224
+ function valueAt(by, view, a, b, ms) {
225
+ const at = sample(by, view, [a, b], ms);
226
+ return separation(by, at.get(a), at.get(b));
227
+ }
228
+ /** Every minimum of the separation of each pair inside [from, to] (every maximum, for a sign of -1): a coarse scan, then each bracket narrowed to about a second. */
229
+ function minima(pairs, by, view, from, to, sign = 1) {
230
+ const ids = [...new Set(pairs.flat())];
231
+ const step = stepMs(ids, view);
232
+ const count = Math.ceil((to - from) / step) + 3;
233
+ const times = Array.from({ length: count }, (_, i) => from - step + i * step);
234
+ const values = pairs.map(() => new Float64Array(count));
235
+ times.forEach((ms, i) => {
236
+ const at = sample(by, view, ids, ms);
237
+ pairs.forEach(([a, b], p) => {
238
+ values[p][i] = sign * separation(by, at.get(a), at.get(b));
239
+ });
240
+ });
241
+ const found = [];
242
+ pairs.forEach(([a, b], p) => {
243
+ const v = values[p];
244
+ for (let i = 1; i < count - 1; i += 1) {
245
+ if (!(v[i] <= v[i - 1] && v[i] < v[i + 1]))
246
+ continue;
247
+ const ms = golden((t) => sign * valueAt(by, view, a, b, t), times[i - 1], times[i + 1], 500);
248
+ if (ms >= from && ms <= to)
249
+ found.push({ a, b, ms, value: valueAt(by, view, a, b, ms) });
250
+ }
251
+ });
252
+ return found;
253
+ }
254
+ /** The expected accuracy of a separation and of the moment of its minimum. */
255
+ function describe(by, view, a, b, ms, value, atEdge) {
256
+ const at = sample(by, view, [a, b], ms);
257
+ const half = 30_000;
258
+ const before = sample(by, view, [a, b], ms - half);
259
+ const after = sample(by, view, [a, b], ms + half);
260
+ const chord = (s) => sub(s.get(b).v, s.get(a).v);
261
+ const moved = length(sub(chord(after), chord(before))) / (2 * half / 1000);
262
+ const base = { a, b, time: new Date(ms), atEdge };
263
+ if (by === "sky") {
264
+ const uncertaintyArcseconds = skyUncertainty(view, a, b, at, ms);
265
+ return { ...base, angle: value, uncertaintyArcseconds, uncertaintySeconds: moved > 0 ? uncertaintyArcseconds / ARCSECONDS_PER_RADIAN / moved : Infinity };
266
+ }
267
+ const uncertaintyKm = spaceUncertainty(a, b, ms);
268
+ return { ...base, distanceKm: value, distanceAu: value / AU_KM, uncertaintyKm, uncertaintySeconds: moved > 0 ? uncertaintyKm / (moved * AU_KM) : Infinity };
269
+ }
270
+ function span(options) {
271
+ const from = moment(options.from, "from");
272
+ const to = moment(options.to, "to");
273
+ if (to < from)
274
+ throw new RangeError("to must not be before from");
275
+ return { from, to, by: byOf(options.by), view: viewOf(options.observer) };
276
+ }
277
+ /**
278
+ * When two bodies come closest in a span, and how close: the span is scanned in coarse steps (the fastest body goes round forty times in the step, at most two days), then the smallest minimum is narrowed to about a second of time by golden-section search. If the separation only falls or only rises through the span, the end that is smaller is returned and `atEdge` says so. With `by: "sky"` the separation is the angle in the sky of the observer and a minimum may be an occultation, the angle falling through 0; with `by: "space"` it is the distance between the centres.
279
+ *
280
+ * The result carries `uncertaintyArcseconds` (or `uncertaintyKm`) for the separation, from the accuracy guide's limits, and `uncertaintySeconds` for the moment: that error over how fast the pair moves past each other.
281
+ *
282
+ * @param a - One body.
283
+ * @param b - The other.
284
+ * @param options - `from` and `to` (the span), `by` and `observer` as in `nearest`.
285
+ * @returns The moment, the separation, and the accuracy to expect.
286
+ * @throws RangeError for bodies, a span or an observer that is not valid, or two bodies that are the same, or one of them the observer.
287
+ *
288
+ * @example
289
+ * ```ts
290
+ * import { closestApproach } from "@johnmorrisdotca/wakusei-planets/nearest";
291
+ *
292
+ * const great = closestApproach("jupiter", "saturn", { from: Date.UTC(2020, 11, 1), to: Date.UTC(2021, 0, 1) });
293
+ * console.log(great.time.toISOString(), great.angle?.toFixed(3), "degrees");
294
+ * ```
295
+ */
296
+ export function closestApproach(a, b, options) {
297
+ bodyOf("a", a);
298
+ bodyOf("b", b);
299
+ if (a === b)
300
+ throw new RangeError(`a and b must be different bodies, got ${a} twice`);
301
+ const { from, to, by, view } = span(options);
302
+ if (by === "sky" && (a === view.body || b === view.body))
303
+ throw new RangeError(`${a === view.body ? a : b} is where the sky is seen from (the observer), so it is not in that sky`);
304
+ const inside = minima([[a, b]], by, view, from, to);
305
+ const best = inside.sort((x, y) => x.value - y.value)[0];
306
+ const start = valueAt(by, view, a, b, from);
307
+ const end = valueAt(by, view, a, b, to);
308
+ const edge = start <= end ? { ms: from, value: start } : { ms: to, value: end };
309
+ if (best !== undefined && best.value <= edge.value)
310
+ return describe(by, view, a, b, best.ms, best.value, false);
311
+ return describe(by, view, a, b, edge.ms, edge.value, true);
312
+ }
313
+ const DEFAULT_BODIES = ["sun", "mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune"];
314
+ /**
315
+ * The close approaches of every pair of bodies in a span, soonest first: each pair's separation is scanned in coarse steps (the fastest body goes round forty times in the step, at most two days), and every minimum inside the span that is within `within` is narrowed to about a second of time. Each is the same as `closestApproach` would return for that pair and that minimum.
316
+ *
317
+ * @param options - `from` and `to`, `within` (degrees for the sky, default 5; kilometres for space, default all), `bodies` (default the Sun and Mercury to Neptune, less the body the sky is seen from), `by` and `observer`.
318
+ * @returns The approaches, soonest first, each with its moment, separation and the accuracy to expect.
319
+ * @throws RangeError for a span, body or observer that is not valid.
320
+ *
321
+ * @example
322
+ * ```ts
323
+ * import { conjunctions } from "@johnmorrisdotca/wakusei-planets/nearest";
324
+ *
325
+ * const found = conjunctions({ from: Date.UTC(2023, 0, 1), to: Date.UTC(2024, 0, 1), bodies: ["venus", "jupiter"], within: 2 });
326
+ * console.log(found.map((one) => `${one.a}-${one.b} ${one.time.toISOString().slice(0, 10)} ${one.angle?.toFixed(2)}`).join("\n"));
327
+ * ```
328
+ */
329
+ export function conjunctions(options) {
330
+ const { from, to, by, view } = span(options);
331
+ const radius = options.within === undefined ? (by === "sky" ? 5 : Infinity) : finite("within", options.within);
332
+ const ids = [...new Set((options.bodies ?? DEFAULT_BODIES).map((id) => bodyOf("bodies", id)))].filter((id) => by === "space" || id !== view.body);
333
+ const pairs = [];
334
+ ids.forEach((a, i) => ids.slice(i + 1).forEach((b) => pairs.push([a, b])));
335
+ if (pairs.length === 0)
336
+ return [];
337
+ return minima(pairs, by, view, from, to)
338
+ .filter((found) => found.value <= radius)
339
+ .sort((x, y) => x.ms - y.ms)
340
+ .map((found) => describe(by, view, found.a, found.b, found.ms, found.value, false));
341
+ }
342
+ /**
343
+ * The distance between two bodies on a date: the straight line between their centres at that instant, in kilometres and astronomical units, with no light time. Any two of the Sun, the planets, the dwarf planets and the moons.
344
+ *
345
+ * @param a - One body.
346
+ * @param b - The other.
347
+ * @param date - The moment, a `Date` or milliseconds since 1970 (UTC). Default: now.
348
+ * @returns The distance and the accuracy to expect of it.
349
+ * @throws RangeError for a body or a date that is not valid, or two bodies that are the same.
350
+ *
351
+ * @example
352
+ * ```ts
353
+ * import { distance } from "@johnmorrisdotca/wakusei-planets/nearest";
354
+ *
355
+ * const mars = distance("earth", "mars", Date.UTC(2003, 7, 27, 9));
356
+ * console.log(mars.distanceAu.toFixed(4), Math.round(mars.distanceKm), "km");
357
+ * ```
358
+ */
359
+ export function distance(a, b, date) {
360
+ bodyOf("a", a);
361
+ bodyOf("b", b);
362
+ if (a === b)
363
+ throw new RangeError(`a and b must be different bodies, got ${a} twice`);
364
+ const ms = date === undefined ? Date.now() : moment(date, "date");
365
+ const km = valueAt("space", viewOf(undefined), a, b, ms);
366
+ return { a, b, time: ms, distanceKm: km, distanceAu: km / AU_KM, uncertaintyKm: spaceUncertainty(a, b, ms) };
367
+ }
368
+ /**
369
+ * The least and the greatest distance between two bodies over a span, each with its moment: the span is scanned in coarse steps (as `closestApproach` does) and each turning point is narrowed to about a second of time by golden-section search, the greatest on the negated distance. If the distance only falls or only rises through the span, the end that is the extreme is returned and `atEdge` says so.
370
+ *
371
+ * @param a - One body.
372
+ * @param b - The other.
373
+ * @param options - `from` and `to`, the span.
374
+ * @returns `min` and `max`, each `{ time, distanceKm, distanceAu, uncertaintyKm, atEdge }`.
375
+ * @throws RangeError for a body or a span that is not valid, or two bodies that are the same.
376
+ *
377
+ * @example
378
+ * ```ts
379
+ * import { distanceRange } from "@johnmorrisdotca/wakusei-planets/nearest";
380
+ *
381
+ * const { min, max } = distanceRange("earth", "mars", { from: Date.UTC(1990, 0, 1), to: Date.UTC(2020, 0, 1) });
382
+ * console.log(min.time.toISOString().slice(0, 10), min.distanceAu.toFixed(3), "to", max.distanceAu.toFixed(3), "au");
383
+ * ```
384
+ */
385
+ export function distanceRange(a, b, options) {
386
+ bodyOf("a", a);
387
+ bodyOf("b", b);
388
+ if (a === b)
389
+ throw new RangeError(`a and b must be different bodies, got ${a} twice`);
390
+ const { from, to, view } = span({ ...options, by: "space" });
391
+ const start = valueAt("space", view, a, b, from);
392
+ const end = valueAt("space", view, a, b, to);
393
+ const pick = (sign) => {
394
+ const candidates = [...minima([[a, b]], "space", view, from, to, sign).map((found) => ({ ms: found.ms, value: found.value, atEdge: false })), { ms: from, value: start, atEdge: true }, { ms: to, value: end, atEdge: true }];
395
+ const best = candidates.sort((x, y) => sign * (x.value - y.value) || Number(x.atEdge) - Number(y.atEdge))[0];
396
+ return { time: new Date(best.ms), distanceKm: best.value, distanceAu: best.value / AU_KM, uncertaintyKm: spaceUncertainty(a, b, best.ms), atEdge: best.atEdge };
397
+ };
398
+ return { a, b, min: pick(1), max: pick(-1) };
399
+ }
@@ -9,7 +9,7 @@ import type * as THREE from "three";
9
9
  * console.log(TEXTURE_BASE);
10
10
  * ```
11
11
  */
12
- export declare const TEXTURE_BASE = "https://cdn.jsdelivr.net/npm/@johnmorrisdotca/wakusei-planets@0.21.0/dist/textures/";
12
+ export declare const TEXTURE_BASE = "https://cdn.jsdelivr.net/npm/@johnmorrisdotca/wakusei-planets@0.23.0/dist/textures/";
13
13
  /**
14
14
  * Where the sharpest surface pictures are: the files of this exact version in the repository, on jsDelivr's GitHub address. The npm package holds only the two smaller widths, so a page that
15
15
  * never zooms in never fetches them. Set `texture-far-base` on an element to serve them yourself.
@@ -21,7 +21,7 @@ export declare const TEXTURE_BASE = "https://cdn.jsdelivr.net/npm/@johnmorrisdot
21
21
  * console.log(TEXTURE_FAR_BASE);
22
22
  * ```
23
23
  */
24
- export declare const TEXTURE_FAR_BASE = "https://cdn.jsdelivr.net/gh/johnmorrisdotca/wakusei-planets@v0.21.0/textures/";
24
+ export declare const TEXTURE_FAR_BASE = "https://cdn.jsdelivr.net/gh/johnmorrisdotca/wakusei-planets@v0.23.0/textures/";
25
25
  export declare const slash: (base: string) => string;
26
26
  export declare function texturePaths(element: Element): {
27
27
  textureBase(): string;
@@ -1,4 +1,5 @@
1
1
  import { greenwichApparentSiderealTime as greenwichSiderealTime } from "../sidereal.ts";
2
+ import type { Vec3 as Vec } from "../vec.ts";
2
3
  import type { EquatorialAngles, HorizontalAngles, Observer } from "./types.ts";
3
4
  export type { Observer } from "./types.ts";
4
5
  /** A body's place on the sky of date, as the Earth's centre sees it (apparent: light time, aberration for the Sun, nutation): angles in degrees, distance in kilometres. */
@@ -18,6 +19,8 @@ export declare function sunEquatorial(ms: number): Equatorial;
18
19
  export declare function moonEquatorial(ms: number): Equatorial;
19
20
  /** The apparent sidereal time at Greenwich in degrees, from the UTC instant taken as UT1. */
20
21
  export { greenwichSiderealTime };
22
+ /** The observer's place from the Earth's centre in the true equator of date, in kilometres, with the turn of the Earth (Meeus ch. 11). */
23
+ export declare function observerVector(observer: Observer, ms: number): Vec;
21
24
  /**
22
25
  * Altitude, azimuth, hour angle and parallactic angle of a body for an observer: topocentric (parallax taken out of the Earth's centre to the place) and geometric, with no refraction.
23
26
  * `ms` is the instant the observer's sky turns for; the body's place `equatorial` is its apparent place at that instant.
@@ -45,7 +45,7 @@ export function moonEquatorial(ms) {
45
45
  /** The apparent sidereal time at Greenwich in degrees, from the UTC instant taken as UT1. */
46
46
  export { greenwichSiderealTime };
47
47
  /** The observer's place from the Earth's centre in the true equator of date, in kilometres, with the turn of the Earth (Meeus ch. 11). */
48
- function observerVector(observer, ms) {
48
+ export function observerVector(observer, ms) {
49
49
  const lat = observer.latitude * RAD;
50
50
  const height = (observer.heightM ?? 0) / 1000;
51
51
  const u = Math.atan((1 - EARTH_FLATTENING) * Math.tan(lat));
@@ -1,2 +1,4 @@
1
1
  import "./ceres.ts";
2
2
  import "./dwarfs.ts";
3
+ import "./galilean.ts";
4
+ import "./saturn-moons.ts";
@@ -1,2 +1,4 @@
1
1
  import "./ceres.js";
2
2
  import "./dwarfs.js";
3
+ import "./galilean.js";
4
+ import "./saturn-moons.js";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ // The Galilean moons from the theory L1.2 (Lainey, Duriez and Vienne 2006, IMCCE): importing this teaches `moonVector` Io, Europa, Ganymede and Callisto, 1130 to 2760.
2
+ import { registerMoonTheory } from "../data/theories.js";
3
+ import { galileanPosition } from "../theories/galilean.js";
4
+ ["io", "europa", "ganymede", "callisto"].forEach((id, index) => registerMoonTheory(id, (ms) => galileanPosition(index, ms)));
@@ -0,0 +1,2 @@
1
+ /** Fetch the theory for a planet's moons: resolves true for the one call that fetched it, false when it was already asked for or loaded, there is none for that planet, or it could not be fetched. */
2
+ export declare function loadMoonTheory(planet: string): Promise<boolean>;
@@ -0,0 +1,15 @@
1
+ // Loads a planet's moon theory when a picture asks for its moons, so a page that shows one planet does not carry Jupiter's and Saturn's theories. A bundler with code splitting makes each a chunk of its own.
2
+ import { moonTheoryOf } from "../data/theories.js";
3
+ const LOADERS = {
4
+ jupiter: { moon: "io", load: () => import("./galilean.js") },
5
+ saturn: { moon: "mimas", load: () => import("./saturn-moons.js") },
6
+ };
7
+ const asked = new Set();
8
+ /** Fetch the theory for a planet's moons: resolves true for the one call that fetched it, false when it was already asked for or loaded, there is none for that planet, or it could not be fetched. */
9
+ export function loadMoonTheory(planet) {
10
+ const loader = LOADERS[planet];
11
+ if (loader === undefined || asked.has(planet) || moonTheoryOf(loader.moon) !== undefined)
12
+ return Promise.resolve(false);
13
+ asked.add(planet);
14
+ return loader.load().then(() => true, () => false);
15
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ // The seven Saturnian moons Mimas to Iapetus (not Hyperion) from the theory TASS1.7 (Vienne and Duriez 1995, IMCCE): importing this teaches `moonVector` their places.
2
+ import { registerMoonTheory } from "../data/theories.js";
3
+ import { tass17Position } from "../theories/tass17.js";
4
+ ["mimas", "enceladus", "tethys", "dione", "rhea", "titan", "iapetus"].forEach((id, index) => registerMoonTheory(id, (ms) => tass17Position(index, ms)));
@@ -0,0 +1 @@
1
+ export {};