@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
@@ -0,0 +1,591 @@
1
+ // Directions on the sky and the frames they are given in. Each frame is Astropy's, defined
2
+ // as Astropy defines it, so a position converted here agrees with Astropy's SkyCoord:
3
+ //
4
+ // - ICRS, the frame every other is defined from.
5
+ // - FK5 at an equinox: the USNO Circular 179 rotation from ICRS (Astropy's B-matrix), then
6
+ // precession from J2000 by the IAU 2006 model (ERFA's bp06).
7
+ // - Galactic: Astropy's rotation from FK5 J2000 (the north galactic pole at RA
8
+ // 192.8594812065348°, Dec 27.12825118085622°, and l = 0 at 122.9319185680026° from the
9
+ // pole's meridian). ERFA's icrs2g uses the Hipparcos definition instead, which differs by
10
+ // up to a few tens of milliarcseconds.
11
+ // - Supergalactic: de Vaucouleurs' rotation from Galactic (the pole at l 47.37°, b 6.32°).
12
+ // - Barycentric mean ecliptic at an equinox: ERFA's ecm06 (IAU 2006 precession and obliquity).
13
+ //
14
+ // A coordinate may carry its distance, proper motion, radial velocity and the time they hold
15
+ // at, and applySpaceMotion moves it to another time as Astropy does, through ERFA's pmsafe. It
16
+ // carries no uncertainty yet. The tests compare every frame and every motion with Astropy.
17
+ import {
18
+ anp, bp06, c2s, ecm06, epb2jd, epj2jd, ir, type Mat3, pas, pmsafe, rx, rxp, rxr, ry, rz, s2c, seps, tr, trxp, type Vec3,
19
+ } from '@arcosmos/erfa'
20
+ import { type FormatAngleOptions, formatAngle, parseAngle } from './angles.ts'
21
+ import { QuantityParseError, UncertaintyError, UnitConversionError } from './errors.ts'
22
+ import { parseUnit } from './parse-unit.ts'
23
+ import { Quantity } from './quantity.ts'
24
+ import { type Time, time } from './time.ts'
25
+ import type { Unit } from './units.ts'
26
+
27
+ // --- Frames -----------------------------------------------------------------------------
28
+
29
+ /** The frames a coordinate may be given in, named as Astropy names them. */
30
+ export type FrameName = 'icrs' | 'fk5' | 'galactic' | 'supergalactic' | 'barycentricmeanecliptic'
31
+
32
+ /** An equinox: "J2000", "J1975.5", "B1950", or a Julian year as a number. Read on the TT scale, as Astropy reads it. */
33
+ export type Equinox = string | number
34
+
35
+ /** The two components of each frame, longitude then latitude, as Astropy names them. */
36
+ export const FRAME_COMPONENTS = {
37
+ icrs: ['ra', 'dec'],
38
+ fk5: ['ra', 'dec'],
39
+ galactic: ['l', 'b'],
40
+ supergalactic: ['sgl', 'sgb'],
41
+ barycentricmeanecliptic: ['lon', 'lat'],
42
+ } as const satisfies Record<FrameName, readonly [string, string]>
43
+
44
+ const TAKES_EQUINOX = new Set<FrameName>(['fk5', 'barycentricmeanecliptic'])
45
+
46
+ /** An equinox as Julian or Besselian, its year, its label ("J2000") and its TT Julian date in two parts. */
47
+ interface ParsedEquinox {
48
+ readonly label: string
49
+ readonly jd: readonly [number, number]
50
+ }
51
+
52
+ function parseEquinox(equinox: Equinox): ParsedEquinox {
53
+ if (typeof equinox === 'number') {
54
+ if (!Number.isFinite(equinox)) throw new RangeError(`An equinox must be a finite year, not ${equinox}`)
55
+ return { label: `J${equinox}`, jd: epj2jd(equinox) }
56
+ }
57
+ const match = /^\s*([JB])\s*(\d+(?:\.\d*)?)\s*$/.exec(equinox)
58
+ if (!match) throw new QuantityParseError(`"${equinox}" isn't an equinox, such as "J2000" or "B1950"`)
59
+ const year = Number(match[2])
60
+ return match[1] === 'J'
61
+ ? { label: `J${year}`, jd: epj2jd(year) }
62
+ : { label: `B${year}`, jd: epb2jd(year) }
63
+ }
64
+
65
+ const J2000 = parseEquinox('J2000')
66
+
67
+ /** Astropy's rotation_matrix(angle, axis): a rotation of the frame by `deg` degrees about an axis. */
68
+ function rotation(axis: 'x' | 'y' | 'z', deg: number): Mat3 {
69
+ const rad = deg * (Math.PI / 180)
70
+ return axis === 'x' ? rx(rad, ir()) : axis === 'y' ? ry(rad, ir()) : rz(rad, ir())
71
+ }
72
+
73
+ /** Astropy's ICRS to FK5 J2000 matrix, from USNO Circular 179 (offsets in degrees). */
74
+ const ICRS_TO_FK5_J2000: Mat3 = (() => {
75
+ const eta0 = -19.9 / 3600000.0
76
+ const xi0 = 9.1 / 3600000.0
77
+ const da0 = -22.9 / 3600000.0
78
+ return rxr(rxr(rotation('x', -eta0), rotation('y', xi0)), rotation('z', da0))
79
+ })()
80
+
81
+ /** Astropy's FK5 J2000 to Galactic matrix. */
82
+ const FK5_J2000_TO_GALACTIC: Mat3 = rxr(
83
+ rxr(rotation('z', 180 - 122.9319185680026), rotation('y', 90 - 27.12825118085622)),
84
+ rotation('z', 192.8594812065348),
85
+ )
86
+
87
+ /** Astropy's Galactic to Supergalactic matrix. */
88
+ const GALACTIC_TO_SUPERGALACTIC: Mat3 = rxr(rxr(rotation('z', 90), rotation('y', 90 - 6.32)), rotation('z', 47.37))
89
+
90
+ /** FK5 precession from one equinox to another, through J2000, without frame bias (Astropy's _precession_matrix). */
91
+ function precession(from: ParsedEquinox, to: ParsedEquinox): Mat3 {
92
+ const fromToJ2000 = tr(bp06(from.jd[0], from.jd[1])[1])
93
+ const j2000ToTo = bp06(to.jd[0], to.jd[1])[1]
94
+ return rxr(j2000ToTo, fromToJ2000)
95
+ }
96
+
97
+ // Astropy's path from ICRS to Galactic, step for step: ICRS to FK5 J2000 (with its precession
98
+ // from J2000 to J2000, an identity to rounding), then FK5 J2000 to Galactic (with another).
99
+ const ICRS_TO_GALACTIC = rxr(
100
+ rxr(FK5_J2000_TO_GALACTIC, precession(J2000, J2000)),
101
+ rxr(precession(J2000, J2000), ICRS_TO_FK5_J2000),
102
+ )
103
+
104
+ /** The matrix from ICRS to a frame, cached per frame and equinox. */
105
+ const matrices = new Map<string, Mat3>()
106
+
107
+ function icrsTo(frame: FrameName, equinox: ParsedEquinox | null): Mat3 {
108
+ const key = `${frame}@${equinox?.label ?? ''}`
109
+ const cached = matrices.get(key)
110
+ if (cached) return cached
111
+ let m: Mat3
112
+ switch (frame) {
113
+ case 'icrs':
114
+ m = ir()
115
+ break
116
+ case 'fk5':
117
+ m = rxr(precession(J2000, equinox ?? J2000), ICRS_TO_FK5_J2000)
118
+ break
119
+ case 'galactic':
120
+ m = ICRS_TO_GALACTIC
121
+ break
122
+ case 'supergalactic':
123
+ m = rxr(GALACTIC_TO_SUPERGALACTIC, ICRS_TO_GALACTIC)
124
+ break
125
+ case 'barycentricmeanecliptic': {
126
+ const jd = (equinox ?? J2000).jd
127
+ m = ecm06(jd[0], jd[1])
128
+ break
129
+ }
130
+ }
131
+ if (matrices.size >= 64) matrices.clear()
132
+ matrices.set(key, m)
133
+ return m
134
+ }
135
+
136
+ // --- Coordinates ------------------------------------------------------------------------
137
+
138
+ /** An angle given as a quantity, or as text parseAngle reads ("12h30m45.6s", "-12d30m45s"). */
139
+ export type AngleInput = Quantity<'angle'> | string
140
+
141
+ /**
142
+ * A coordinate's distance and motion, any of them optional, as Astropy's SkyCoord takes them:
143
+ * a distance (or a parallax), proper motions in the frame's own names, a radial velocity, and
144
+ * the time they hold at (`obstime`), which applySpaceMotion needs.
145
+ */
146
+ export interface MotionInput {
147
+ readonly distance?: Quantity<'length'>
148
+ /** In place of a distance: the distance is 1/parallax, the parallax in arcseconds giving parsecs. */
149
+ readonly parallax?: Quantity<'angle'>
150
+ readonly radialVelocity?: Quantity<'speed'>
151
+ readonly obstime?: Time
152
+ }
153
+
154
+ /** What a coordinate is made from: its two components and proper motions, named as its frame names them. */
155
+ export type SkyCoordInput = MotionInput & (
156
+ | {
157
+ readonly ra: AngleInput; readonly dec: AngleInput; readonly frame?: 'icrs' | 'fk5'; readonly equinox?: Equinox
158
+ readonly pmRaCosdec?: Quantity<'angular speed'>; readonly pmDec?: Quantity<'angular speed'>
159
+ }
160
+ | {
161
+ readonly l: AngleInput; readonly b: AngleInput; readonly frame: 'galactic'
162
+ readonly pmLCosb?: Quantity<'angular speed'>; readonly pmB?: Quantity<'angular speed'>
163
+ }
164
+ | {
165
+ readonly sgl: AngleInput; readonly sgb: AngleInput; readonly frame: 'supergalactic'
166
+ readonly pmSglCossgb?: Quantity<'angular speed'>; readonly pmSgb?: Quantity<'angular speed'>
167
+ }
168
+ | {
169
+ readonly lon: AngleInput; readonly lat: AngleInput; readonly frame: 'barycentricmeanecliptic'; readonly equinox?: Equinox
170
+ readonly pmLonCoslat?: Quantity<'angular speed'>; readonly pmLat?: Quantity<'angular speed'>
171
+ }
172
+ )
173
+
174
+ /** The two proper-motion components of each frame, as Astropy names them (pm_ra_cosdec, pm_dec...). */
175
+ export const FRAME_PROPER_MOTIONS = {
176
+ icrs: ['pmRaCosdec', 'pmDec'],
177
+ fk5: ['pmRaCosdec', 'pmDec'],
178
+ galactic: ['pmLCosb', 'pmB'],
179
+ supergalactic: ['pmSglCossgb', 'pmSgb'],
180
+ barycentricmeanecliptic: ['pmLonCoslat', 'pmLat'],
181
+ } as const satisfies Record<FrameName, readonly [string, string]>
182
+
183
+ /** How toString writes a coordinate, as Astropy's SkyCoord.to_string: degrees, sexagesimal degrees, or hours and degrees. */
184
+ export type SkyCoordStyle = 'decimal' | 'dms' | 'hmsdms'
185
+
186
+ const RAD: Unit<'angle'> = parseUnit('rad') as Unit<'angle'>
187
+ const DEG: Unit<'angle'> = parseUnit('deg') as Unit<'angle'>
188
+ const ARCSEC: Unit<'angle'> = parseUnit('arcsec') as Unit<'angle'>
189
+ const PC: Unit<'length'> = parseUnit('pc') as Unit<'length'>
190
+ const RAD_PER_YR: Unit<'angular speed'> = parseUnit('rad/yr') as Unit<'angular speed'>
191
+ const MAS_PER_YR: Unit<'angular speed'> = parseUnit('mas/yr') as Unit<'angular speed'>
192
+ const KM_PER_S: Unit<'speed'> = parseUnit('km/s') as Unit<'speed'>
193
+
194
+ function radians(input: AngleInput, name: string): number {
195
+ const angle = typeof input === 'string' ? parseAngle(input) : input
196
+ if (angle.kind !== 'angle') throw new UnitConversionError(`${name} must be an angle, not ${angle.kind}`)
197
+ return angle.to(RAD).value
198
+ }
199
+
200
+ /** A quantity's value in a unit, refusing an uncertainty or a limit, which a coordinate can't carry yet. */
201
+ function plainValue<K extends string>(q: Quantity<K>, unit: Unit<K>, name: string): number {
202
+ if (q.uncertainty !== null || q.limit !== null) {
203
+ throw new UncertaintyError(`${name} has an uncertainty or is a limit, which a coordinate can't carry yet`)
204
+ }
205
+ if (q.kind !== unit.kind) throw new UnitConversionError(`${name} must be a quantity of ${unit.kind}, not ${q.kind}`)
206
+ return (q as Quantity<string>).to(unit).value
207
+ }
208
+
209
+ /** A coordinate's distance and motion in the units held: pc, rad/yr, km/s. Null where not given. */
210
+ interface Motion {
211
+ readonly distancePc: number | null
212
+ readonly pmLonCoslat: number | null
213
+ readonly pmLat: number | null
214
+ readonly rv: number | null
215
+ readonly obstime: Time | null
216
+ }
217
+
218
+ const NO_MOTION: Motion = { distancePc: null, pmLonCoslat: null, pmLat: null, rv: null, obstime: null }
219
+
220
+ /** Unit vectors east and north at a direction, the axes of a proper motion. */
221
+ function tangentBasis(lon: number, lat: number): [Vec3, Vec3] {
222
+ const sl = Math.sin(lon)
223
+ const cl = Math.cos(lon)
224
+ const sb = Math.sin(lat)
225
+ return [[-sl, cl, 0], [-sb * cl, -sb * sl, Math.cos(lat)]]
226
+ }
227
+
228
+ const dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
229
+
230
+ /**
231
+ * A direction on the sky in a frame, with its distance and motion if known:
232
+ * `skyCoord({ ra: q(10.684, 'deg'), dec: q(41.269, 'deg') })`. Immutable. Named after Astropy's
233
+ * SkyCoord, of which it is the part for directions and space motion.
234
+ */
235
+ export class SkyCoord {
236
+ readonly frame: FrameName
237
+ /** The equinox of FK5 and ecliptic coordinates ("J2000" by default); null for the others. */
238
+ readonly equinox: string | null
239
+ /** @internal Longitude in radians, 0 <= lon < 2pi. */
240
+ readonly lonRad: number
241
+ /** @internal Latitude in radians. */
242
+ readonly latRad: number
243
+ /** @internal Distance, proper motion (rad/yr, the longitude's times cos(latitude)) and radial velocity. */
244
+ readonly motion: Motion
245
+ readonly #equinox: ParsedEquinox | null
246
+
247
+ /** @internal Use skyCoord(). */
248
+ constructor(frame: FrameName, lonRad: number, latRad: number, equinox: ParsedEquinox | null, motion: Motion = NO_MOTION) {
249
+ if (!Number.isFinite(lonRad) || !Number.isFinite(latRad)) throw new RangeError('A coordinate must be finite')
250
+ if (Math.abs(latRad) > Math.PI / 2) {
251
+ throw new RangeError(`A latitude must be within ±90°, not ${latRad * (180 / Math.PI)}°`)
252
+ }
253
+ if (motion.distancePc !== null && !(motion.distancePc > 0 && Number.isFinite(motion.distancePc))) {
254
+ throw new RangeError(`A distance must be positive and finite, not ${motion.distancePc} pc`)
255
+ }
256
+ this.frame = frame
257
+ this.#equinox = equinox
258
+ this.equinox = equinox?.label ?? null
259
+ this.lonRad = anp(lonRad)
260
+ this.latRad = latRad
261
+ this.motion = motion
262
+ }
263
+
264
+ /**
265
+ * The longitude component (ra, l, sgl or lon), in degrees from 0 up to 360. A longitude just
266
+ * under 2pi can round to 360 in degrees: it wraps to 0, as Astropy's Longitude does.
267
+ */
268
+ get lon(): Quantity<'angle'> {
269
+ const deg = new Quantity(this.lonRad, RAD).to(DEG)
270
+ return deg.value >= 360 ? new Quantity(deg.value - 360, DEG) : deg
271
+ }
272
+
273
+ /** The latitude component (dec, b, sgb or lat), in degrees. */
274
+ get lat(): Quantity<'angle'> {
275
+ return new Quantity(this.latRad, RAD).to(DEG)
276
+ }
277
+
278
+ get ra(): Quantity<'angle'> { return this.component('ra', this.lon) }
279
+ get dec(): Quantity<'angle'> { return this.component('dec', this.lat) }
280
+ get l(): Quantity<'angle'> { return this.component('l', this.lon) }
281
+ get b(): Quantity<'angle'> { return this.component('b', this.lat) }
282
+ get sgl(): Quantity<'angle'> { return this.component('sgl', this.lon) }
283
+ get sgb(): Quantity<'angle'> { return this.component('sgb', this.lat) }
284
+
285
+ /** The distance, in parsecs, or null when not known. */
286
+ get distance(): Quantity<'length'> | null {
287
+ return this.motion.distancePc === null ? null : new Quantity(this.motion.distancePc, PC)
288
+ }
289
+
290
+ /** The proper motion along the longitude, times cos(latitude) (pm_ra_cosdec in ICRS), in mas/yr; null when not known. */
291
+ get pmLonCoslat(): Quantity<'angular speed'> | null {
292
+ return this.motion.pmLonCoslat === null ? null : new Quantity(this.motion.pmLonCoslat, RAD_PER_YR).to(MAS_PER_YR)
293
+ }
294
+
295
+ /** The proper motion along the latitude (pm_dec in ICRS), in mas/yr; null when not known. */
296
+ get pmLat(): Quantity<'angular speed'> | null {
297
+ return this.motion.pmLat === null ? null : new Quantity(this.motion.pmLat, RAD_PER_YR).to(MAS_PER_YR)
298
+ }
299
+
300
+ get pmRaCosdec(): Quantity<'angular speed'> | null { return this.properMotion('pmRaCosdec', this.pmLonCoslat) }
301
+ get pmDec(): Quantity<'angular speed'> | null { return this.properMotion('pmDec', this.pmLat) }
302
+ get pmLCosb(): Quantity<'angular speed'> | null { return this.properMotion('pmLCosb', this.pmLonCoslat) }
303
+ get pmB(): Quantity<'angular speed'> | null { return this.properMotion('pmB', this.pmLat) }
304
+
305
+ /** The radial velocity, in km/s, or null when not known. */
306
+ get radialVelocity(): Quantity<'speed'> | null {
307
+ return this.motion.rv === null ? null : new Quantity(this.motion.rv, KM_PER_S)
308
+ }
309
+
310
+ /** The time the position and motion hold at, or null. */
311
+ get obstime(): Time | null {
312
+ return this.motion.obstime
313
+ }
314
+
315
+ /**
316
+ * The same direction in another frame: `c.transformTo('galactic')`,
317
+ * `c.transformTo('fk5', { equinox: 'J1975' })`. A proper motion turns with it; the distance
318
+ * and radial velocity don't change.
319
+ */
320
+ transformTo(frame: FrameName, options: { readonly equinox?: Equinox } = {}): SkyCoord {
321
+ const equinox = frameEquinox(frame, options.equinox)
322
+ const from = icrsTo(this.frame, this.#equinox)
323
+ const to = icrsTo(frame, equinox)
324
+ const [lon, lat] = c2s(rxp(to, trxp(from, s2c(this.lonRad, this.latRad))))
325
+ let motion = this.motion
326
+ if (motion.pmLonCoslat !== null && motion.pmLat !== null) {
327
+ const [east, north] = tangentBasis(this.lonRad, this.latRad)
328
+ const v: Vec3 = [
329
+ motion.pmLonCoslat * east[0] + motion.pmLat * north[0],
330
+ motion.pmLonCoslat * east[1] + motion.pmLat * north[1],
331
+ motion.pmLonCoslat * east[2] + motion.pmLat * north[2],
332
+ ]
333
+ const turned = rxp(to, trxp(from, v))
334
+ const [east2, north2] = tangentBasis(lon, lat)
335
+ motion = { ...motion, pmLonCoslat: dot(turned, east2), pmLat: dot(turned, north2) }
336
+ }
337
+ return new SkyCoord(frame, lon, lat, equinox, motion)
338
+ }
339
+
340
+ get icrs(): SkyCoord { return this.transformTo('icrs') }
341
+ /** In FK5 at J2000. */
342
+ get fk5(): SkyCoord { return this.transformTo('fk5') }
343
+ get galactic(): SkyCoord { return this.transformTo('galactic') }
344
+ get supergalactic(): SkyCoord { return this.transformTo('supergalactic') }
345
+ /** In the barycentric mean ecliptic at J2000. */
346
+ get barycentricmeanecliptic(): SkyCoord { return this.transformTo('barycentricmeanecliptic') }
347
+
348
+ /**
349
+ * Where the star is at another time, by its proper motion, and its parallax and radial
350
+ * velocity where known: Astropy's apply_space_motion, through ERFA's pmsafe. Give the new
351
+ * time (`newObstime`, which needs this coordinate's `obstime`) or the interval (`dt`; with
352
+ * no `obstime`, the interval is counted from J2000 and the result has none either). The
353
+ * motion is rigorous: along a straight line in space, with the light-time and perspective
354
+ * effects ERFA's starpm includes. Needs a proper motion, or as Astropy, a distance and a
355
+ * radial velocity (the proper motion then taken as zero).
356
+ *
357
+ * Unlike Astropy, a radial velocity that wasn't given stays unknown. Astropy reports pmsafe's,
358
+ * which for a star with no radial velocity comes from the distance pmsafe assumes, up to about
359
+ * 1 km/s, and isn't a measurement.
360
+ */
361
+ applySpaceMotion(options: { readonly newObstime?: Time; readonly dt?: Quantity<'time'> }): SkyCoord {
362
+ if ((options.newObstime === undefined) === (options.dt === undefined)) {
363
+ throw new TypeError('Give newObstime or dt, not both')
364
+ }
365
+ const radialOnly = this.motion.pmLonCoslat === null && this.motion.rv !== null && this.motion.distancePc !== null
366
+ if ((this.motion.pmLonCoslat === null || this.motion.pmLat === null) && !radialOnly) {
367
+ throw new TypeError('Moving a coordinate needs its proper motion, or a distance and a radial velocity')
368
+ }
369
+ if (options.newObstime !== undefined && this.motion.obstime === null) {
370
+ throw new TypeError('This coordinate has no obstime: give dt, the interval, rather than a new time')
371
+ }
372
+ let t1: Time
373
+ let t2: Time
374
+ let newObstime: Time | null
375
+ if (options.dt === undefined) {
376
+ t1 = this.motion.obstime as Time
377
+ t2 = options.newObstime as Time
378
+ newObstime = t2
379
+ } else if (this.motion.obstime === null) {
380
+ // As Astropy: with no obstime, the interval is counted from J2000, which only sets dt.
381
+ t1 = time('J2000')
382
+ t2 = t1.plus(options.dt)
383
+ newObstime = null
384
+ } else {
385
+ t1 = this.motion.obstime
386
+ t2 = t1.plus(options.dt)
387
+ newObstime = t2
388
+ }
389
+ const icrs = this.transformTo('icrs')
390
+ const start = radialOnly ? { ...icrs.motion, pmLonCoslat: 0, pmLat: 0 } : icrs.motion
391
+ const [ra2, dec2, motion] = moveIcrs(icrs.lonRad, icrs.latRad, start, t1.tdb, t2.tdb)
392
+ const moved = new SkyCoord('icrs', ra2, dec2, null, { ...motion, obstime: newObstime })
393
+ return moved.transformTo(this.frame, this.equinox === null ? {} : { equinox: this.equinox })
394
+ }
395
+
396
+ /** The angle between two directions, in degrees. The other is converted to this one's frame first. */
397
+ separation(other: SkyCoord): Quantity<'angle'> {
398
+ const o = other.inFrameOf(this)
399
+ return new Quantity(seps(this.lonRad, this.latRad, o.lonRad, o.latRad), RAD).to(DEG)
400
+ }
401
+
402
+ /** The position angle of the other direction from this one, east of north, in degrees from 0 to 360. */
403
+ positionAngle(other: SkyCoord): Quantity<'angle'> {
404
+ const o = other.inFrameOf(this)
405
+ return new Quantity(anp(pas(this.lonRad, this.latRad, o.lonRad, o.latRad)), RAD).to(DEG)
406
+ }
407
+
408
+ /**
409
+ * The coordinate as text, as Astropy's SkyCoord.to_string writes it: "10.6847 41.2690" in
410
+ * the "decimal" style (with `precision: 4`), "00h42m44.3s +41d16m09s" in "hmsdms". Options
411
+ * are formatAngle's, applied to both components.
412
+ */
413
+ toString(style: SkyCoordStyle = 'decimal', options: FormatAngleOptions = {}): string {
414
+ const styles: Record<SkyCoordStyle, [FormatAngleOptions, FormatAngleOptions]> = {
415
+ hmsdms: [{ unit: 'hourangle', pad: true }, { unit: 'deg', pad: true, alwaysSign: true }],
416
+ dms: [{ unit: 'deg' }, { unit: 'deg' }],
417
+ decimal: [{ unit: 'deg', decimal: true }, { unit: 'deg', decimal: true }],
418
+ }
419
+ const [lonOptions, latOptions] = styles[style]
420
+ return `${formatAngle(this.lon, { ...lonOptions, ...options })} ${formatAngle(this.lat, { ...latOptions, ...options })}`
421
+ }
422
+
423
+ /** Its frame, components and motion in the units the getters give, and `obstime` as the Time writes itself. */
424
+ toJSON(): Record<string, string | number | ReturnType<Time['toJSON']>> {
425
+ const [lonName, latName] = FRAME_COMPONENTS[this.frame]
426
+ const [pmLonName, pmLatName] = FRAME_PROPER_MOTIONS[this.frame]
427
+ const json: Record<string, string | number | ReturnType<Time['toJSON']>> = {
428
+ frame: this.frame,
429
+ ...(this.equinox ? { equinox: this.equinox } : {}),
430
+ [lonName]: this.lon.value,
431
+ [latName]: this.lat.value,
432
+ }
433
+ if (this.motion.distancePc !== null) json.distance = this.motion.distancePc
434
+ const pmLon = this.pmLonCoslat
435
+ const pmLat = this.pmLat
436
+ if (pmLon && pmLat) {
437
+ json[pmLonName] = pmLon.value
438
+ json[pmLatName] = pmLat.value
439
+ }
440
+ if (this.motion.rv !== null) json.radialVelocity = this.motion.rv
441
+ if (this.motion.obstime) json.obstime = this.motion.obstime.toJSON()
442
+ return json
443
+ }
444
+
445
+ private component(name: string, value: Quantity<'angle'>): Quantity<'angle'> {
446
+ if (!(FRAME_COMPONENTS[this.frame] as readonly string[]).includes(name)) {
447
+ const [lonName, latName] = FRAME_COMPONENTS[this.frame]
448
+ throw new TypeError(`A ${this.frame} coordinate has ${lonName} and ${latName}, not ${name}`)
449
+ }
450
+ return value
451
+ }
452
+
453
+ private properMotion(name: string, value: Quantity<'angular speed'> | null): Quantity<'angular speed'> | null {
454
+ if (!(FRAME_PROPER_MOTIONS[this.frame] as readonly string[]).includes(name)) {
455
+ const [lonName, latName] = FRAME_PROPER_MOTIONS[this.frame]
456
+ throw new TypeError(`A ${this.frame} coordinate's proper motions are ${lonName} and ${latName}, not ${name}`)
457
+ }
458
+ return value
459
+ }
460
+
461
+ private inFrameOf(target: SkyCoord): SkyCoord {
462
+ if (this.frame === target.frame && this.equinox === target.equinox) return this
463
+ return this.transformTo(target.frame, target.equinox === null ? {} : { equinox: target.equinox })
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Astropy's apply_space_motion on an ICRS position and its motion, between two TDB times:
469
+ * ERFA's pmsafe, with the proper motion in RA taken without cos(dec), a parallax of 0 where the
470
+ * distance isn't known, and a radial velocity of 0 where it isn't. A distance or radial
471
+ * velocity not known stays unknown.
472
+ */
473
+ function moveIcrs(ra: number, dec: number, m: Motion, from: Time, to: Time): [number, number, Motion] {
474
+ const pmr = (m.pmLonCoslat as number) / Math.cos(dec)
475
+ const parallaxZero = m.distancePc === null
476
+ const px = parallaxZero ? 0.0 : 1 / (m.distancePc as number)
477
+ const rv = m.rv ?? 0.0
478
+ const [ra2, dec2, pmr2, pmd2, px2, rv2, status] = pmsafe(
479
+ ra, dec, pmr, m.pmLat as number, px, rv, from.jd1, from.jd2, to.jd1, to.jd2,
480
+ )
481
+ if (status < 0) throw new RangeError(`ERFA couldn't move this star (pmsafe status ${status})`)
482
+ return [ra2, dec2, {
483
+ distancePc: parallaxZero ? null : 1 / px2,
484
+ pmLonCoslat: pmr2 * Math.cos(dec2),
485
+ pmLat: pmd2,
486
+ rv: m.rv === null ? null : rv2,
487
+ obstime: null,
488
+ }]
489
+ }
490
+
491
+ /** A star in ICRS as plain numbers in fixed units, for moving many at once. */
492
+ export interface StarAt {
493
+ readonly raDeg: number
494
+ readonly decDeg: number
495
+ /** Proper motion in RA times cos(dec), mas/yr. */
496
+ readonly pmRaCosdecMasYr: number
497
+ readonly pmDecMasYr: number
498
+ /** Null (or zero or less) when the distance isn't known. */
499
+ readonly parallaxMas: number | null
500
+ readonly radialVelocityKmS: number | null
501
+ }
502
+
503
+ const MAS_YR_TO_RAD_YR = MAS_PER_YR.to(RAD_PER_YR)
504
+
505
+ /**
506
+ * Where an ICRS star is at another time: the same computation as SkyCoord.applySpaceMotion
507
+ * (Astropy's apply_space_motion through ERFA's pmsafe), on plain numbers, for moving many stars
508
+ * between the same two times without making a coordinate for each. A parallax of zero or
509
+ * less counts as unknown, as no distance.
510
+ */
511
+ export function moveStar(star: StarAt, from: Time, to: Time): StarAt {
512
+ const plx = star.parallaxMas !== null && star.parallaxMas > 0 ? star.parallaxMas : null
513
+ const motion: Motion = {
514
+ distancePc: plx === null ? null : 1000 / plx,
515
+ pmLonCoslat: star.pmRaCosdecMasYr * MAS_YR_TO_RAD_YR,
516
+ pmLat: star.pmDecMasYr * MAS_YR_TO_RAD_YR,
517
+ rv: star.radialVelocityKmS,
518
+ obstime: null,
519
+ }
520
+ const [ra, dec, moved] = moveIcrs(star.raDeg * (Math.PI / 180), star.decDeg * (Math.PI / 180), motion, from.tdb, to.tdb)
521
+ const raDeg = anp(ra) * (180 / Math.PI)
522
+ return {
523
+ raDeg: raDeg >= 360 ? raDeg - 360 : raDeg,
524
+ decDeg: dec * (180 / Math.PI),
525
+ pmRaCosdecMasYr: (moved.pmLonCoslat as number) / MAS_YR_TO_RAD_YR,
526
+ pmDecMasYr: (moved.pmLat as number) / MAS_YR_TO_RAD_YR,
527
+ parallaxMas: moved.distancePc === null ? null : 1000 / moved.distancePc,
528
+ radialVelocityKmS: moved.rv,
529
+ }
530
+ }
531
+
532
+ /**
533
+ * The rotation from one frame to another, as `transformTo` turns a direction: a vector `v`
534
+ * (a direction or a cartesian position) in `from` is `M v` in `to`, and the transpose turns it
535
+ * back. For code that turns many positions on plain numbers, where a SkyCoord each would cost
536
+ * too much: `frameRotation('icrs', 'galactic')` is Astropy's ICRS-to-Galactic matrix. Each
537
+ * equinox defaults to J2000, and only FK5 and the ecliptic take one.
538
+ */
539
+ export function frameRotation(
540
+ from: FrameName, to: FrameName, options: { readonly fromEquinox?: Equinox; readonly toEquinox?: Equinox } = {},
541
+ ): Mat3 {
542
+ const source = icrsTo(from, frameEquinox(from, options.fromEquinox))
543
+ return rxr(icrsTo(to, frameEquinox(to, options.toEquinox)), tr(source))
544
+ }
545
+
546
+ function frameEquinox(frame: FrameName, equinox: Equinox | undefined): ParsedEquinox | null {
547
+ if (!TAKES_EQUINOX.has(frame)) {
548
+ if (equinox !== undefined) throw new TypeError(`The ${frame} frame takes no equinox`)
549
+ return null
550
+ }
551
+ return equinox === undefined ? J2000 : parseEquinox(equinox)
552
+ }
553
+
554
+ /**
555
+ * A direction on the sky, and its distance and motion if given: `skyCoord({ ra: q(10.684,
556
+ * 'deg'), dec: q(41.269, 'deg') })` (ICRS by default), `skyCoord({ ra: '00h42m44.3s', dec:
557
+ * '+41d16m09s' })`, `skyCoord({ l: q(121.17, 'deg'), b: q(-21.57, 'deg'), frame: 'galactic' })`.
558
+ * Proper motions come both or neither, named as the frame names them (`pmRaCosdec` and
559
+ * `pmDec` in ICRS). A latitude beyond ±90° is refused; a longitude is wrapped into 0 to 360°.
560
+ */
561
+ export function skyCoord(input: SkyCoordInput): SkyCoord {
562
+ const frame: FrameName = input.frame ?? 'icrs'
563
+ const [lonName, latName] = FRAME_COMPONENTS[frame]
564
+ const [pmLonName, pmLatName] = FRAME_PROPER_MOTIONS[frame]
565
+ const values = input as unknown as Record<string, unknown>
566
+ const lon = values[lonName] as AngleInput | undefined
567
+ const lat = values[latName] as AngleInput | undefined
568
+ if (lon === undefined || lat === undefined) {
569
+ throw new TypeError(`A ${frame} coordinate is made from ${lonName} and ${latName}`)
570
+ }
571
+ const pmLon = values[pmLonName] as Quantity<'angular speed'> | undefined
572
+ const pmLat = values[pmLatName] as Quantity<'angular speed'> | undefined
573
+ if ((pmLon === undefined) !== (pmLat === undefined)) {
574
+ throw new TypeError(`Give both proper motions, ${pmLonName} and ${pmLatName}, or neither`)
575
+ }
576
+ if (input.distance !== undefined && input.parallax !== undefined) {
577
+ throw new TypeError('Give a distance or a parallax, not both')
578
+ }
579
+ let distancePc: number | null = null
580
+ if (input.distance !== undefined) distancePc = plainValue(input.distance, PC, 'The distance')
581
+ else if (input.parallax !== undefined) distancePc = 1 / plainValue(input.parallax, ARCSEC, 'The parallax')
582
+ const motion: Motion = {
583
+ distancePc,
584
+ pmLonCoslat: pmLon === undefined ? null : plainValue(pmLon, RAD_PER_YR, pmLonName),
585
+ pmLat: pmLat === undefined ? null : plainValue(pmLat, RAD_PER_YR, pmLatName),
586
+ rv: input.radialVelocity === undefined ? null : plainValue(input.radialVelocity, KM_PER_S, 'The radial velocity'),
587
+ obstime: input.obstime ?? null,
588
+ }
589
+ const equinox = frameEquinox(frame, 'equinox' in input ? input.equinox : undefined)
590
+ return new SkyCoord(frame, radians(lon, lonName), radians(lat, latName), equinox, motion)
591
+ }
@@ -0,0 +1,58 @@
1
+ // Distances from parallaxes, and the distance modulus, as Astropy's Distance gives them
2
+ // (Distance(parallax=...) and Distance.distmod). Each comes in two forms: on quantities, with
3
+ // the error propagated to first order as any computation here is, and on plain numbers, for
4
+ // many stars at once (a map's, a diagram's), as moveStar is for applySpaceMotion.
5
+ //
6
+ // 1 / parallax is biased once the parallax error is more than about a tenth of the parallax,
7
+ // and a parallax of zero or less gives no distance at all. These helpers don't correct for
8
+ // either: they compute what Astropy computes.
9
+ import { type Quantity, q, requireArithmetic } from './quantity.ts'
10
+
11
+ /** 1000 pc mas: a parallax of 1 mas is 1000 pc away. Exact. */
12
+ const PARSEC_MAS = q(1000, 'pc mas', { sigma: 0 })
13
+
14
+ /**
15
+ * The distance a parallax puts a star at, 1 / parallax, in parsecs: Astropy's
16
+ * Distance(parallax=...). Its error is propagated to first order, d × sigma / parallax. A
17
+ * parallax of zero or less gives no distance and throws (Astropy refuses a negative one), as
18
+ * do a limit, asymmetric errors and percentiles, as in any arithmetic here.
19
+ */
20
+ export function distanceFromParallax(parallax: Quantity<'angle'>): Quantity<'length'> {
21
+ requireArithmetic(parallax, 'turned into a distance')
22
+ if (!(parallax.value > 0)) {
23
+ throw new RangeError(`A parallax of ${parallax} gives no distance: only a positive parallax does`)
24
+ }
25
+ return PARSEC_MAS.div(parallax).as('length').to('pc')
26
+ }
27
+
28
+ /**
29
+ * The distance modulus, 5 log10(d / 10 pc), in magnitudes: Astropy's Distance.distmod. An
30
+ * absolute magnitude is the apparent magnitude less it. Its error is propagated to first
31
+ * order, 5 / ln 10 × sigma / d. A distance of zero or less throws, as do a limit, asymmetric
32
+ * errors and percentiles.
33
+ */
34
+ export function distanceModulus(distance: Quantity<'length'>): Quantity<'magnitude'> {
35
+ requireArithmetic(distance, 'turned into a distance modulus')
36
+ const pc = distance.to('pc')
37
+ if (!(pc.value > 0)) {
38
+ throw new RangeError(`A distance of ${distance} has no distance modulus: only a positive distance does`)
39
+ }
40
+ const sigma = pc.sigma === null ? null : (5 / Math.LN10) * pc.sigma / pc.value
41
+ return q(distanceModulusPc(pc.value), 'mag', sigma === null ? {} : { sigma })
42
+ }
43
+
44
+ /**
45
+ * 1000 / parallax: the distance in parsecs for a parallax in mas, on plain numbers. NaN for a
46
+ * parallax of zero or less, which gives no distance.
47
+ */
48
+ export function parallaxDistancePc(parallaxMas: number): number {
49
+ return parallaxMas > 0 ? 1000 / parallaxMas : NaN
50
+ }
51
+
52
+ /**
53
+ * 5 log10(d / 10 pc): the distance modulus in magnitudes for a distance in parsecs, on plain
54
+ * numbers, as Astropy computes it. NaN for a distance of zero or less.
55
+ */
56
+ export function distanceModulusPc(distancePc: number): number {
57
+ return distancePc > 0 ? 5 * Math.log10(distancePc) - 5 : NaN
58
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,27 @@
1
+ /** A unit written in a form the parser doesn't accept, or a symbol it doesn't know. */
2
+ export class UnitParseError extends Error {
3
+ override readonly name = 'UnitParseError'
4
+ }
5
+
6
+ /** Two units of different kinds, such as a length and a time, which no factor converts. */
7
+ export class UnitConversionError extends Error {
8
+ override readonly name = 'UnitConversionError'
9
+ }
10
+
11
+ /**
12
+ * Arithmetic the uncertainties don't allow as given: an asymmetric error, percentiles, or a
13
+ * limit, where first-order propagation isn't defined. The message says what to do instead.
14
+ */
15
+ export class UncertaintyError extends Error {
16
+ override readonly name = 'UncertaintyError'
17
+ }
18
+
19
+ /** Text that isn't a number followed by a unit. */
20
+ export class QuantityParseError extends Error {
21
+ override readonly name = 'QuantityParseError'
22
+ }
23
+
24
+ /** Text that isn't a time: not ISO 8601, not a J or B year, or an impossible date. */
25
+ export class TimeParseError extends Error {
26
+ override readonly name = 'TimeParseError'
27
+ }