@arcosmos/astronomy 0.0.0-stage → 0.1.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.
Files changed (63) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +227 -2
  3. package/dist/angles.d.ts +51 -0
  4. package/dist/angles.d.ts.map +1 -0
  5. package/dist/angles.js +261 -0
  6. package/dist/angles.js.map +1 -0
  7. package/dist/constants.d.ts +35 -0
  8. package/dist/constants.d.ts.map +1 -0
  9. package/dist/constants.js +44 -0
  10. package/dist/constants.js.map +1 -0
  11. package/dist/coordinates.d.ts +213 -0
  12. package/dist/coordinates.d.ts.map +1 -0
  13. package/dist/coordinates.js +474 -0
  14. package/dist/coordinates.js.map +1 -0
  15. package/dist/distance.d.ts +26 -0
  16. package/dist/distance.d.ts.map +1 -0
  17. package/dist/distance.js +54 -0
  18. package/dist/distance.js.map +1 -0
  19. package/dist/errors.d.ts +24 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/errors.js +24 -0
  22. package/dist/errors.js.map +1 -0
  23. package/dist/index.d.ts +13 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +15 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/kinds.d.ts +86 -0
  28. package/dist/kinds.d.ts.map +1 -0
  29. package/dist/kinds.js +29 -0
  30. package/dist/kinds.js.map +1 -0
  31. package/dist/parse-unit.d.ts +11 -0
  32. package/dist/parse-unit.d.ts.map +1 -0
  33. package/dist/parse-unit.js +222 -0
  34. package/dist/parse-unit.js.map +1 -0
  35. package/dist/quantity.d.ts +150 -0
  36. package/dist/quantity.d.ts.map +1 -0
  37. package/dist/quantity.js +452 -0
  38. package/dist/quantity.js.map +1 -0
  39. package/dist/rounding.d.ts +18 -0
  40. package/dist/rounding.d.ts.map +1 -0
  41. package/dist/rounding.js +35 -0
  42. package/dist/rounding.js.map +1 -0
  43. package/dist/time.d.ts +100 -0
  44. package/dist/time.d.ts.map +1 -0
  45. package/dist/time.js +448 -0
  46. package/dist/time.js.map +1 -0
  47. package/dist/units.d.ts +394 -0
  48. package/dist/units.d.ts.map +1 -0
  49. package/dist/units.js +353 -0
  50. package/dist/units.js.map +1 -0
  51. package/package.json +44 -3
  52. package/src/angles.ts +286 -0
  53. package/src/constants.ts +51 -0
  54. package/src/coordinates.ts +591 -0
  55. package/src/distance.ts +58 -0
  56. package/src/errors.ts +27 -0
  57. package/src/index.ts +27 -0
  58. package/src/kinds.ts +110 -0
  59. package/src/parse-unit.ts +230 -0
  60. package/src/quantity.ts +539 -0
  61. package/src/rounding.ts +33 -0
  62. package/src/time.ts +511 -0
  63. package/src/units.ts +445 -0
package/src/time.ts ADDED
@@ -0,0 +1,511 @@
1
+ // Times: an instant in a time scale, held as Astropy holds it, as two numbers whose sum is a
2
+ // Julian date: a whole day and a fraction within half a day. Every step follows Astropy's
3
+ // Time, so the same input gives the same two numbers:
4
+ //
5
+ // - Scales: UTC, TAI, TT, TDB, TCG and TCB, converted through ERFA's functions along
6
+ // Astropy's paths (UTC to TT goes through TAI; TT to TCB through TDB), renormalizing after.
7
+ // TDB − TT is ERFA's dtdb at the geocenter, as Astropy computes it with no location. UT1,
8
+ // which needs Earth orientation data, isn't here yet.
9
+ // - Formats: Julian and modified Julian dates, Julian and Besselian years ("J2000.5",
10
+ // "B1950"), Unix time, and ISO text ("2000-01-01T12:00:00.000").
11
+ // - Arithmetic on a UTC time happens in TAI, so a leap second counts as the second it is.
12
+ //
13
+ // Leap seconds are ERFA's table (@arcosmos/erfa's dat): the last was at the end of 2016. ERFA
14
+ // calls UTC more than five years past its release (2023) dubious, since a leap second could
15
+ // be announced; Astropy warns then, and this library carries on as Astropy does.
16
+ import {
17
+ DJM0, d2dtf, dtdb, dtf2d, epb, epb2jd, epj, epj2jd, taitt, taiutc, tcbtdb, tcgtt, tdbtcb, tdbtt, tttai, tttcg,
18
+ tttdb, utctai,
19
+ } from '@arcosmos/erfa'
20
+ import { pythonFixed } from './angles.ts'
21
+ import { TimeParseError, UncertaintyError, UnitConversionError } from './errors.ts'
22
+ import { parseUnit } from './parse-unit.ts'
23
+ import { Quantity } from './quantity.ts'
24
+ import type { Unit } from './units.ts'
25
+
26
+ /** The time scales, named as Astropy names them. */
27
+ export type TimeScale = 'utc' | 'tai' | 'tt' | 'tdb' | 'tcg' | 'tcb'
28
+
29
+ /** The formats a time is read from and written in, named as Astropy names them. */
30
+ export type TimeFormat = 'jd' | 'mjd' | 'jyear' | 'byear' | 'unix' | 'iso' | 'isot' | 'jyear_str' | 'byear_str'
31
+
32
+ const SCALES: readonly TimeScale[] = ['utc', 'tai', 'tt', 'tdb', 'tcg', 'tcb']
33
+
34
+ /** Astropy's default scale for each format. */
35
+ const DEFAULT_SCALE: Record<TimeFormat, TimeScale> = {
36
+ jd: 'utc', mjd: 'utc', unix: 'utc', iso: 'utc', isot: 'utc', jyear: 'tt', byear: 'tt', jyear_str: 'tt', byear_str: 'tt',
37
+ }
38
+
39
+ // --- Two-number arithmetic (astropy.time.utils) -----------------------------------------
40
+
41
+ /** a + b as a sum and its rounding error, exactly (Shewchuk's two-sum). */
42
+ function twoSum(a: number, b: number): [number, number] {
43
+ const x = a + b
44
+ let eb = x - a
45
+ let ea = x - eb
46
+ eb = b - eb
47
+ ea = a - ea
48
+ return [x, ea + eb]
49
+ }
50
+
51
+ /** Splits a into two halves whose product terms are exact (Dekker). */
52
+ function split(a: number): [number, number] {
53
+ const c = 134217729.0 * a
54
+ const abig = c - a
55
+ const ah = c - abig
56
+ return [ah, a - ah]
57
+ }
58
+
59
+ /** a × b as a product and its rounding error, exactly. */
60
+ function twoProduct(a: number, b: number): [number, number] {
61
+ const x = a * b
62
+ const [ah, al] = split(a)
63
+ const [bh, bl] = split(b)
64
+ const y1 = ah * bh
65
+ let y = x - y1
66
+ const y2 = al * bh
67
+ y -= y2
68
+ const y3 = ah * bl
69
+ y -= y3
70
+ const y4 = al * bl
71
+ y = y4 - y
72
+ return [x, y]
73
+ }
74
+
75
+ /** NumPy's round: to the nearest whole number, an exact half to even. */
76
+ function roundHalfEven(x: number): number {
77
+ const f = Math.floor(x)
78
+ const d = x - f
79
+ if (d < 0.5) return f
80
+ if (d > 0.5) return f + 1
81
+ return f % 2 === 0 ? f : f + 1
82
+ }
83
+
84
+ /**
85
+ * Astropy's day_frac: val1 + val2 (times factor, or divided by divisor) as a whole day and a
86
+ * fraction within half a day, the sum kept to twice double precision.
87
+ */
88
+ export function dayFrac(val1: number, val2: number, { factor, divisor }: { factor?: number; divisor?: number } = {}): [number, number] {
89
+ let [sum12, err12] = twoSum(val1, val2)
90
+ if (factor !== undefined) {
91
+ let carry: number
92
+ ;[sum12, carry] = twoProduct(sum12, factor)
93
+ carry += err12 * factor
94
+ ;[sum12, err12] = twoSum(sum12, carry)
95
+ }
96
+ if (divisor !== undefined) {
97
+ const q1 = sum12 / divisor
98
+ const [p1, p2] = twoProduct(q1, divisor)
99
+ const [d1, d2first] = twoSum(sum12, -p1)
100
+ let d2 = d2first
101
+ d2 += err12
102
+ d2 -= p2
103
+ const q2 = (d1 + d2) / divisor
104
+ ;[sum12, err12] = twoSum(q1, q2)
105
+ }
106
+ let day = roundHalfEven(sum12)
107
+ const [frac0, check] = twoSum(sum12 - day, err12)
108
+ const excess = frac0 * Math.sign(check) !== 0.5 ? roundHalfEven(frac0) : roundHalfEven(frac0 + 2 * check)
109
+ day += excess
110
+ let frac = sum12 - day
111
+ frac += err12
112
+ return [day, frac]
113
+ }
114
+
115
+ // --- Scale conversions (astropy.time.core) ----------------------------------------------
116
+
117
+ /** Astropy's MULTI_HOPS: the scales passed through between two others, keyed by the sorted pair. */
118
+ const MULTI_HOPS: Record<string, readonly TimeScale[]> = {
119
+ 'tai,tcb': ['tt', 'tdb'],
120
+ 'tai,tcg': ['tt'],
121
+ 'tai,tdb': ['tt'],
122
+ 'tcb,tcg': ['tdb', 'tt'],
123
+ 'tcb,tt': ['tdb'],
124
+ 'tcb,utc': ['tdb', 'tt', 'tai'],
125
+ 'tcg,tdb': ['tt'],
126
+ 'tcg,utc': ['tt', 'tai'],
127
+ 'tdb,utc': ['tt', 'tai'],
128
+ 'tt,utc': ['tai'],
129
+ }
130
+
131
+ /** The path from one scale to another, both ends included, as Astropy takes it. */
132
+ function scalePath(from: TimeScale, to: TimeScale): TimeScale[] {
133
+ const sorted = [from, to].sort() as [TimeScale, TimeScale]
134
+ const path = [sorted[0], ...(MULTI_HOPS[sorted.join(',')] ?? []), sorted[1]]
135
+ return sorted[0] === from ? path : path.reverse()
136
+ }
137
+
138
+ /** Throws for ERFA's error statuses; a dubious-year warning (1) passes, as in Astropy. */
139
+ function checked<T extends readonly number[]>(result: readonly [...T, number], what: string): T {
140
+ const status = result[result.length - 1] as number
141
+ if (status < 0) throw new RangeError(`ERFA refused ${what} (status ${status}): the date is outside its range`)
142
+ return result.slice(0, -1) as unknown as T
143
+ }
144
+
145
+ /**
146
+ * Astropy's _get_delta_tdb_tt: TDB − TT in seconds at the geocenter, from the TT (or TDB)
147
+ * date given, with UT approximated by UTC.
148
+ */
149
+ function deltaTdbTt(jd1: number, jd2: number): number {
150
+ let [n1, n2] = checked<[number, number]>(tttai(jd1, jd2), 'TT to TAI')
151
+ ;[n1, n2] = checked<[number, number]>(taiutc(n1, n2), 'TAI to UTC')
152
+ const ut = dayFrac(n1 - 0.5, n2)[1]
153
+ return dtdb(jd1, jd2, ut, 0.0, 0.0, 0.0)
154
+ }
155
+
156
+ interface Converted {
157
+ readonly jd: [number, number]
158
+ readonly deltaTdbTt: number | null
159
+ }
160
+
161
+ /** One hop of a conversion, through ERFA's function for it. */
162
+ function hop(from: TimeScale, to: TimeScale, jd1: number, jd2: number, delta: number | null): Converted {
163
+ const pair = `${from}${to}`
164
+ const tdbDelta = () => delta ?? deltaTdbTt(jd1, jd2)
165
+ switch (pair) {
166
+ case 'utctai': return { jd: checked<[number, number]>(utctai(jd1, jd2), 'UTC to TAI'), deltaTdbTt: delta }
167
+ case 'taiutc': return { jd: checked<[number, number]>(taiutc(jd1, jd2), 'TAI to UTC'), deltaTdbTt: delta }
168
+ case 'taitt': return { jd: checked<[number, number]>(taitt(jd1, jd2), 'TAI to TT'), deltaTdbTt: delta }
169
+ case 'tttai': return { jd: checked<[number, number]>(tttai(jd1, jd2), 'TT to TAI'), deltaTdbTt: delta }
170
+ case 'tttcg': return { jd: checked<[number, number]>(tttcg(jd1, jd2), 'TT to TCG'), deltaTdbTt: delta }
171
+ case 'tcgtt': return { jd: checked<[number, number]>(tcgtt(jd1, jd2), 'TCG to TT'), deltaTdbTt: delta }
172
+ case 'tdbtcb': return { jd: checked<[number, number]>(tdbtcb(jd1, jd2), 'TDB to TCB'), deltaTdbTt: delta }
173
+ case 'tcbtdb': return { jd: checked<[number, number]>(tcbtdb(jd1, jd2), 'TCB to TDB'), deltaTdbTt: delta }
174
+ case 'tttdb': {
175
+ const d = tdbDelta()
176
+ return { jd: checked<[number, number]>(tttdb(jd1, jd2, d), 'TT to TDB'), deltaTdbTt: d }
177
+ }
178
+ case 'tdbtt': {
179
+ const d = tdbDelta()
180
+ return { jd: checked<[number, number]>(tdbtt(jd1, jd2, d), 'TDB to TT'), deltaTdbTt: d }
181
+ }
182
+ default:
183
+ throw new Error(`No conversion from ${from} to ${to}`)
184
+ }
185
+ }
186
+
187
+ /** Astropy's _set_scale: hop by hop along the path, then renormalized. */
188
+ function convert(from: TimeScale, to: TimeScale, jd1: number, jd2: number, delta: number | null): Converted {
189
+ if (from === to) return { jd: [jd1, jd2], deltaTdbTt: delta }
190
+ const path = scalePath(from, to)
191
+ let jd: [number, number] = [jd1, jd2]
192
+ let d = delta
193
+ for (let i = 0; i + 1 < path.length; i++) {
194
+ const step = hop(path[i] as TimeScale, path[i + 1] as TimeScale, jd[0], jd[1], d)
195
+ jd = step.jd
196
+ d = step.deltaTdbTt
197
+ }
198
+ return { jd: dayFrac(jd[0], jd[1]), deltaTdbTt: d }
199
+ }
200
+
201
+ // --- Reading ----------------------------------------------------------------------------
202
+
203
+ /** "2000-01-01", "2000-01-01 12:00", "2000-01-01T12:00:00.123", optionally ending in Z (UTC). */
204
+ const ISO = /^(\d{4})-(\d{1,2})-(\d{1,2})(?:([ T])(\d{1,2}):(\d{1,2})(?::(\d{1,2})(\.\d*)?)?)?(Z)?$/
205
+ // As Astropy: J or B in either case, then what Python's float() reads, spaces around it allowed.
206
+ const EPOCH = /^([JjBb])\s*([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)\s*$/
207
+
208
+ /** The two parts of a date from ISO text, by ERFA's dtf2d in the given scale. */
209
+ function readIso(text: string, scale: TimeScale): { jd: [number, number]; format: 'iso' | 'isot'; separator: boolean } {
210
+ const match = ISO.exec(text)
211
+ if (!match) throw new TimeParseError(`"${text}" isn't a time Astropy reads, such as "2000-01-01T12:00:00"`)
212
+ const [, y, mo, d, sep, h = '0', mi = '0', s = '0', frac, z] = match
213
+ if (z && scale !== 'utc') throw new TimeParseError(`"${text}" ends in Z, which means UTC, but the scale is ${scale}`)
214
+ // Astropy reads a trailing point ("12:00:00.") as no fraction.
215
+ const seconds = Number(s) + (frac && frac !== '.' ? Number(frac) : 0)
216
+ const [d1, d2, status] = dtf2d(scale.toUpperCase(), Number(y), Number(mo), Number(d), Number(h), Number(mi), seconds)
217
+ if (status < 0) {
218
+ const field = ['', 'year', 'month', 'day', 'hour', 'minute', 'second'][-status] ?? 'field'
219
+ throw new TimeParseError(`"${text}" has an impossible ${field}`)
220
+ }
221
+ return { jd: dayFrac(d1, d2), format: sep === 'T' ? 'isot' : 'iso', separator: sep !== undefined }
222
+ }
223
+
224
+ /** A Julian or Besselian year as text: "J2000", "J2000.5", "B1950.0". */
225
+ function readEpoch(text: string): { jd: [number, number]; format: 'jyear_str' | 'byear_str' } {
226
+ const match = EPOCH.exec(text)
227
+ if (!match) throw new TimeParseError(`"${text}" isn't an epoch, such as "J2000" or "B1950"`)
228
+ const year = Number(match[2])
229
+ const julian = match[1]?.toUpperCase() === 'J'
230
+ const [a, b] = julian ? epj2jd(year) : epb2jd(year)
231
+ return { jd: dayFrac(a, b), format: julian ? 'jyear_str' : 'byear_str' }
232
+ }
233
+
234
+ /** Astropy's Unix epoch, 1970-01-01 00:00:00 UTC, as it holds it. */
235
+ let unixEpoch: [number, number] | null = null
236
+ function unixEpochJd(): [number, number] {
237
+ unixEpoch ??= readIso('1970-01-01 00:00:00', 'utc').jd
238
+ return unixEpoch
239
+ }
240
+
241
+ // --- Times ------------------------------------------------------------------------------
242
+
243
+ /** How a time is made from a number: its format and scale, and an optional second part. */
244
+ export interface TimeOptions {
245
+ /** How to read a number: required for numbers, inferred for text. */
246
+ readonly format?: TimeFormat
247
+ /** The time scale. Default: Astropy's for the format (UTC, or TT for years). */
248
+ readonly scale?: TimeScale
249
+ /** Decimal places of seconds (ISO) or of the year (J and B text). Default 3. */
250
+ readonly precision?: number
251
+ }
252
+
253
+ export type TimeInput = string | number | readonly [number, number] | Date
254
+
255
+ /**
256
+ * An instant in a time scale: `time('2000-01-01T12:00:00', { scale: 'tt' })`,
257
+ * `time(2451545.0, { format: 'jd', scale: 'tt' })`, `time('J2000')`. Immutable; named after
258
+ * Astropy's Time and held as it holds one.
259
+ */
260
+ export class Time {
261
+ readonly scale: TimeScale
262
+ /** The format it was made in, which value and toString write. */
263
+ readonly format: TimeFormat
264
+ /** Decimal places when written as text. */
265
+ readonly precision: number
266
+ /** @internal The whole day of the two-part Julian date. */
267
+ readonly jd1: number
268
+ /** @internal The fraction, within half a day. */
269
+ readonly jd2: number
270
+ readonly #deltaTdbTt: number | null
271
+
272
+ /** @internal Use time(). */
273
+ constructor(scale: TimeScale, jd1: number, jd2: number, format: TimeFormat, precision: number, deltaTdbTt: number | null = null) {
274
+ if (!Number.isFinite(jd1) || !Number.isFinite(jd2)) throw new RangeError('A time must be finite')
275
+ if (!Number.isInteger(precision) || precision < 0 || precision > 9) {
276
+ throw new RangeError(`A time's precision is a whole number from 0 to 9, not ${precision}`)
277
+ }
278
+ this.scale = scale
279
+ this.jd1 = jd1
280
+ this.jd2 = jd2
281
+ this.format = format
282
+ this.precision = precision
283
+ this.#deltaTdbTt = deltaTdbTt
284
+ }
285
+
286
+ /** The same instant in another scale. */
287
+ to(scale: TimeScale): Time {
288
+ if (!SCALES.includes(scale)) throw new TypeError(`Unknown time scale "${scale}"`)
289
+ const { jd, deltaTdbTt } = convert(this.scale, scale, this.jd1, this.jd2, this.#deltaTdbTt)
290
+ return new Time(scale, jd[0], jd[1], this.format, this.precision, deltaTdbTt)
291
+ }
292
+
293
+ get utc(): Time { return this.to('utc') }
294
+ get tai(): Time { return this.to('tai') }
295
+ get tt(): Time { return this.to('tt') }
296
+ get tdb(): Time { return this.to('tdb') }
297
+ get tcg(): Time { return this.to('tcg') }
298
+ get tcb(): Time { return this.to('tcb') }
299
+
300
+ /** The same instant written in another format, or at another precision. */
301
+ inFormat(format: TimeFormat, precision = this.precision): Time {
302
+ return new Time(this.scale, this.jd1, this.jd2, format, precision, this.#deltaTdbTt)
303
+ }
304
+
305
+ /** The Julian date, as one number (precise to about 40 microseconds near the present). */
306
+ get jd(): number {
307
+ return this.jd1 + this.jd2
308
+ }
309
+
310
+ /** The modified Julian date (JD − 2400000.5). */
311
+ get mjd(): number {
312
+ return (this.jd1 - DJM0) + this.jd2
313
+ }
314
+
315
+ /** The Julian year, such as 2000.0 for J2000.0. */
316
+ get jyear(): number {
317
+ return epj(this.jd1, this.jd2)
318
+ }
319
+
320
+ /** The Besselian year, such as 1950.0 for B1950.0. */
321
+ get byear(): number {
322
+ return epb(this.jd1, this.jd2)
323
+ }
324
+
325
+ /** Seconds since 1970-01-01 00:00:00 UTC, every UTC day 86 400 s (leap seconds aren't counted), as Astropy's unix. */
326
+ get unix(): number {
327
+ const utc = this.scale === 'utc' ? this : this.to('utc')
328
+ const [e1, e2] = unixEpochJd()
329
+ return (utc.jd1 - e1) * 86400 + (utc.jd2 - e2) * 86400
330
+ }
331
+
332
+ /** ISO text with a space: "2000-01-01 12:00:00.000", to `precision` places. */
333
+ get iso(): string {
334
+ return this.isoText(' ')
335
+ }
336
+
337
+ /** ISO text with a T: "2000-01-01T12:00:00.000". */
338
+ get isot(): string {
339
+ return this.isoText('T')
340
+ }
341
+
342
+ /** The Julian year as text: "J2000.000". */
343
+ get jyearStr(): string {
344
+ return `J${pythonFixed(this.jyear, this.precision)}`
345
+ }
346
+
347
+ /** The Besselian year as text: "B1950.000". */
348
+ get byearStr(): string {
349
+ return `B${pythonFixed(this.byear, this.precision)}`
350
+ }
351
+
352
+ /** The value in the time's own format. */
353
+ get value(): number | string {
354
+ switch (this.format) {
355
+ case 'jd': return this.jd
356
+ case 'mjd': return this.mjd
357
+ case 'jyear': return this.jyear
358
+ case 'byear': return this.byear
359
+ case 'unix': return this.unix
360
+ case 'iso': return this.iso
361
+ case 'isot': return this.isot
362
+ case 'jyear_str': return this.jyearStr
363
+ case 'byear_str': return this.byearStr
364
+ }
365
+ }
366
+
367
+ /** The time later by a duration: `t.plus(q(1, 'd'))`. On a UTC time this counts in TAI, so leap seconds count. */
368
+ plus(duration: Quantity<'time'>): Time {
369
+ const [d1, d2] = durationDays(duration)
370
+ const working: TimeScale = this.scale === 'utc' ? 'tai' : this.scale
371
+ const start = convert(this.scale, working, this.jd1, this.jd2, this.#deltaTdbTt)
372
+ const [s1, s2] = dayFrac(start.jd[0] + d1, start.jd[1] + d2)
373
+ const back = convert(working, this.scale, s1, s2, null)
374
+ return new Time(this.scale, back.jd[0], back.jd[1], this.format, this.precision)
375
+ }
376
+
377
+ /**
378
+ * The time earlier by a duration, or the interval from another time to this one, in seconds:
379
+ * `t2.minus(t1)`. Between UTC times it counts in TAI; another time is converted to this one's
380
+ * scale first.
381
+ */
382
+ minus(duration: Quantity<'time'>): Time
383
+ minus(other: Time): Quantity<'time'>
384
+ minus(other: Quantity<'time'> | Time): Time | Quantity<'time'> {
385
+ if (!(other instanceof Time)) return this.plus(other.negate())
386
+ const working: TimeScale = this.scale === 'utc' ? 'tai' : this.scale
387
+ const a = convert(this.scale, working, this.jd1, this.jd2, this.#deltaTdbTt).jd
388
+ const b = convert(other.scale, working, other.jd1, other.jd2, other.#deltaTdbTt).jd
389
+ const [j1, j2] = dayFrac(a[0] - b[0], a[1] - b[1])
390
+ // Astropy's TimeDelta in seconds: each part times 86400 (exact), then the sum.
391
+ return new Quantity(j1 * 86400 + j2 * 86400, SECOND)
392
+ }
393
+
394
+ /** -1, 0 or 1 as this time is before, at or after the other. */
395
+ compare(other: Time): number {
396
+ return Math.sign(this.minus(other).value)
397
+ }
398
+
399
+ /** A JavaScript Date at this instant, to the millisecond, from its Unix time. */
400
+ toDate(): Date {
401
+ return new Date(Math.round(this.unix * 1000))
402
+ }
403
+
404
+ toString(): string {
405
+ return String(this.value)
406
+ }
407
+
408
+ toJSON(): { value: number | string; format: TimeFormat; scale: TimeScale } {
409
+ return { value: this.value, format: this.format, scale: this.scale }
410
+ }
411
+
412
+ /** Astropy's TimeString value, through ERFA's d2dtf. */
413
+ private isoText(sep: ' ' | 'T'): string {
414
+ const [iy, im, id, ihmsf, status] = d2dtf(this.scale.toUpperCase(), this.precision, this.jd1, this.jd2)
415
+ if (status < 0) throw new RangeError(`ERFA can't write ${this.jd1 + this.jd2} as a date (status ${status})`)
416
+ const two = (n: number) => String(n).padStart(2, '0')
417
+ let text = `${iy}-${two(im)}-${two(id)}${sep}${two(ihmsf[0])}:${two(ihmsf[1])}:${two(ihmsf[2])}`
418
+ if (this.precision > 0) text += `.${String(ihmsf[3]).padStart(this.precision, '0')}`
419
+ return text
420
+ }
421
+ }
422
+
423
+ const SECOND = parseUnit('s') as Unit<'time'>
424
+ const DAY = parseUnit('d') as Unit<'time'>
425
+
426
+ /** Astropy's quantity_day_frac: a duration as two parts of a day, exact for the usual units. */
427
+ function durationDays(duration: Quantity<'time'>): [number, number] {
428
+ if (duration.kind !== 'time') throw new UnitConversionError(`${duration} isn't a duration`)
429
+ if (duration.uncertainty !== null || duration.limit !== null) {
430
+ throw new UncertaintyError(`${duration} has an uncertainty or is a limit, which a time can't carry`)
431
+ }
432
+ const factor = duration.unit.to(DAY)
433
+ if (factor === 1) return dayFrac(duration.value, 0)
434
+ if (factor > 1) return dayFrac(duration.value, 0, { factor })
435
+ return dayFrac(duration.value, 0, { divisor: DAY.to(duration.unit) })
436
+ }
437
+
438
+ /**
439
+ * A time: from ISO text (`'2000-01-01T12:00:00'`, UTC by default), a Julian or Besselian year
440
+ * as text (`'J2000'`, TT), a number in a given format (`time(2451545, { format: 'jd' })`), a
441
+ * two-part Julian date (`time([2451545, 0.25], { format: 'jd' })`), or a JavaScript Date.
442
+ */
443
+ export function time(input: TimeInput, options: TimeOptions = {}): Time {
444
+ const precision = options.precision ?? 3
445
+ if (input instanceof Date) {
446
+ return fromNumbers(input.getTime() / 1000, 0, 'unix', options.scale ?? 'utc', precision).inFormat('isot')
447
+ }
448
+ if (typeof input === 'string') {
449
+ // Not trimmed: Astropy refuses a leading space in ISO text.
450
+ const text = input
451
+ if (EPOCH.test(text)) {
452
+ const { jd, format } = readEpoch(text)
453
+ if (options.format && options.format !== format) throw new TimeParseError(`"${text}" isn't in the ${options.format} format`)
454
+ return new Time(options.scale ?? 'tt', jd[0], jd[1], format, precision)
455
+ }
456
+ const scale = options.scale ?? 'utc'
457
+ const { jd, format, separator } = readIso(text, scale)
458
+ // A date alone reads as either; with a time, ISO has a space and ISOT a T, as in Astropy.
459
+ const wanted = options.format ?? format
460
+ if ((wanted !== 'iso' && wanted !== 'isot') || (separator && wanted !== format)) {
461
+ throw new TimeParseError(`"${text}" isn't in the ${wanted} format`)
462
+ }
463
+ return new Time(scale, jd[0], jd[1], wanted, precision)
464
+ }
465
+ const format = options.format
466
+ if (!format || format === 'iso' || format === 'isot' || format === 'jyear_str' || format === 'byear_str') {
467
+ throw new TypeError('A number needs its format: "jd", "mjd", "jyear", "byear" or "unix"')
468
+ }
469
+ const [val1, val2] = typeof input === 'number' ? [input, 0] : input
470
+ return fromNumbers(val1, val2, format, options.scale ?? DEFAULT_SCALE[format], precision)
471
+ }
472
+
473
+ /** Astropy's set_jds for the numeric formats. */
474
+ function fromNumbers(val1: number, val2: number, format: TimeFormat, scale: TimeScale, precision: number): Time {
475
+ if (!Number.isFinite(val1) || !Number.isFinite(val2)) throw new RangeError('A time must be finite')
476
+ let jd: [number, number]
477
+ switch (format) {
478
+ case 'jd':
479
+ jd = dayFrac(val1, val2)
480
+ break
481
+ case 'mjd': {
482
+ const [a, b] = dayFrac(val1, val2)
483
+ jd = dayFrac(a + DJM0, b)
484
+ break
485
+ }
486
+ case 'jyear':
487
+ jd = dayFrac(...epj2jd(val1 + val2))
488
+ break
489
+ case 'byear':
490
+ jd = dayFrac(...epb2jd(val1 + val2))
491
+ break
492
+ case 'unix': {
493
+ const [day, frac] = dayFrac(val1, val2, { divisor: 86400 })
494
+ const [e1, e2] = unixEpochJd()
495
+ let jd1 = e1 + day
496
+ let jd2 = e2 + frac
497
+ if (scale === 'utc') {
498
+ const extra = roundHalfEven(jd2)
499
+ jd1 += extra
500
+ jd2 -= extra
501
+ jd = [jd1, jd2]
502
+ } else {
503
+ jd = convert('utc', scale, jd1, jd2, null).jd
504
+ }
505
+ break
506
+ }
507
+ default:
508
+ throw new TypeError(`A number can't be in the ${format} format`)
509
+ }
510
+ return new Time(scale, jd[0], jd[1], format, precision)
511
+ }