@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/angles.ts ADDED
@@ -0,0 +1,286 @@
1
+ // Angles as text: reading "12h30m45.6s", "-12d30m45s" or "12:30:45.6", and writing them back
2
+ // in sexagesimal or decimal form. Both follow Astropy's Angle: the same grammar, the same
3
+ // range checks, and to_string's rounding, carrying and padding, so a string written here is
4
+ // the one Astropy writes. The tests compare both with Astropy.
5
+ import { QuantityParseError, UnitConversionError } from './errors.ts'
6
+ import { parseUnit } from './parse-unit.ts'
7
+ import { Quantity } from './quantity.ts'
8
+ import type { Unit } from './units.ts'
9
+
10
+ // --- Reading ----------------------------------------------------------------------------
11
+
12
+ /**
13
+ * Token types, one letter each, so the grammar can be matched as a regular expression over
14
+ * the sequence: I a whole number, F a decimal (with a point), + a sign, H D M S hour, degree,
15
+ * minute and second marks, C a colon, U another angle unit, E east or west, N north or south.
16
+ */
17
+ interface Token {
18
+ readonly type: 'I' | 'F' | '+' | 'H' | 'D' | 'M' | 'S' | 'C' | 'U' | 'E' | 'N'
19
+ readonly value?: number
20
+ readonly unit?: string
21
+ }
22
+
23
+ /**
24
+ * Angle units read after a number, other than degrees and hours. Astropy tries its unit names
25
+ * in alphabetical order and takes the first that matches, so "radian" reads as "rad" followed
26
+ * by "ian", and fails: the long names are left out here for the same result.
27
+ */
28
+ const SIMPLE_UNITS: Record<string, string> = {
29
+ arcmin: 'arcmin', arcsec: 'arcsec', mas: 'mas', mrad: 'mrad', rad: 'rad', uas: 'uas', urad: 'urad',
30
+ }
31
+ const SIMPLE_UNIT = new RegExp(`^(?:${Object.keys(SIMPLE_UNITS).join('|')})`)
32
+
33
+ // Astropy's lexer, rule for rule and in its order. Only a space is ignored.
34
+ const LEXER: readonly [RegExp, (text: string, rest: string) => Token | null][] = [
35
+ [/^(?:\d+\.\d*|\.\d+)(?:[eE][+\-−]?\d+)?/, (t) => ({ type: 'F', value: Number(t.replace('−', '-')) })],
36
+ [/^\d+/, (t) => ({ type: 'I', value: Number(t) })],
37
+ [/^[+\-−]/, (t) => ({ type: '+', value: t === '+' ? 1 : -1 })],
38
+ [/^[EW]/, (t, rest) => (rest.length === 0 ? { type: 'E', value: t === 'W' ? -1 : 1 } : null)],
39
+ [/^[NS]/, (t, rest) => (rest.length === 0 ? { type: 'N', value: t === 'S' ? -1 : 1 } : null)],
40
+ [SIMPLE_UNIT, (t) => ({ type: 'U', unit: SIMPLE_UNITS[t] })],
41
+ [/^(?:m(?:in(?:ute(?:s)?)?)?|′|'|ᵐ)/, () => ({ type: 'M' })],
42
+ [/^(?:s(?:ec(?:ond(?:s)?)?)?|″|"|ˢ)/, () => ({ type: 'S' })],
43
+ [/^(?:d(?:eg(?:ree(?:s)?)?)?|°)/, () => ({ type: 'D' })],
44
+ [/^(?:hour(?:s)?|h(?:r)?|ʰ)/, () => ({ type: 'H' })],
45
+ [/^:/, () => ({ type: 'C' })],
46
+ ]
47
+
48
+ function lex(text: string): Token[] {
49
+ const tokens: Token[] = []
50
+ let rest = text.trim()
51
+ outer: while (rest.length) {
52
+ if (rest[0] === ' ') {
53
+ rest = rest.slice(1)
54
+ continue
55
+ }
56
+ for (const [pattern, make] of LEXER) {
57
+ const match = pattern.exec(rest)?.[0]
58
+ if (match === undefined) continue
59
+ const token = make(match, rest.slice(match.length))
60
+ if (!token) continue
61
+ tokens.push(token)
62
+ rest = rest.slice(match.length)
63
+ continue outer
64
+ }
65
+ throw new QuantityParseError(`Unexpected "${rest[0]}" in the angle "${text}"`)
66
+ }
67
+ return tokens
68
+ }
69
+
70
+ // Astropy's grammar, over the token letters. A number is I or F; "generic" is one to three
71
+ // numbers separated by spaces or colons.
72
+ const NUM = '[IF]'
73
+ const GENERIC = `(?:${NUM}|I${NUM}|IC${NUM}|II${NUM}|ICIC${NUM})`
74
+ const SEXAGESIMAL = (mark: 'H' | 'D') =>
75
+ `(?:I${mark}|I${mark}${NUM}|I${mark}IM|I${mark}FM|I${mark}IM${NUM}|I${mark}IM${NUM}S|${GENERIC}${mark})`
76
+ const GRAMMAR = new RegExp(`^\\+?(?:${SEXAGESIMAL('H')}E?|${SEXAGESIMAL('D')}[EN]?|${GENERIC}[MSU]?[EN]?)$`)
77
+
78
+ /** A unit that may be given as a hint or a target: "deg", "hourangle", or another angle unit. */
79
+ export type AngleUnit = 'deg' | 'hourangle' | 'arcmin' | 'arcsec' | 'mas' | 'uas' | 'rad' | (string & {})
80
+
81
+ function angleUnit(text: AngleUnit): Unit<'angle'> {
82
+ const u = parseUnit(text)
83
+ if (u.kind !== 'angle') throw new UnitConversionError(`${text} isn't an angle unit`)
84
+ return u as Unit<'angle'>
85
+ }
86
+
87
+ /**
88
+ * An angle from text, as Astropy's Angle reads it:
89
+ *
90
+ * - "12h30m45.6s", "12h30m", "12.5h", "12ʰ30ᵐ45ˢ" (hours);
91
+ * - "-12d30m45s", "+41d12m00s", "10d30.5m", "1.5 deg", "12°30′45″" (degrees);
92
+ * - "30m" and "45s" alone are arcminutes and arcseconds; "1.2 mas", "0.5 rad" and the like;
93
+ * - "12:30:45.6" or "12 30 45.6", which need `unit` to say whether they are hours or degrees;
94
+ * - a trailing W or S negates.
95
+ *
96
+ * The sign applies to the whole angle ("-0:30:00" is half a degree below zero). Minutes and
97
+ * seconds must be under 60 (60 itself is allowed, as in Astropy), and hours within 24. The
98
+ * angle is in the unit the text names, else in `unit`.
99
+ */
100
+ export function parseAngle(text: string, unit?: AngleUnit): Quantity<'angle'> {
101
+ const tokens = lex(text)
102
+ const types = tokens.map((t) => t.type).join('')
103
+ if (!GRAMMAR.test(types)) throw new QuantityParseError(`"${text}" isn't an angle Astropy would read`)
104
+
105
+ let sign = 1
106
+ const numbers: number[] = []
107
+ let found: string | null = null
108
+ for (const token of tokens) {
109
+ if (token.type === '+' || token.type === 'E' || token.type === 'N') sign *= token.value ?? 1
110
+ else if (token.type === 'I' || token.type === 'F') numbers.push(token.value ?? 0)
111
+ else if (token.type === 'H') found = 'hourangle'
112
+ else if (token.type === 'D') found = 'deg'
113
+ else if (token.type === 'U') found ??= token.unit ?? null
114
+ }
115
+ if (found === null) {
116
+ if (types.includes('M')) found = 'arcmin'
117
+ else if (types.includes('S')) found = 'arcsec'
118
+ }
119
+ const angleUnitText = found ?? unit
120
+ if (angleUnitText === undefined) {
121
+ throw new QuantityParseError(`"${text}" names no unit: give one, such as parseAngle(text, "hourangle")`)
122
+ }
123
+
124
+ let value: number
125
+ const [first = 0, minutes, seconds] = numbers
126
+ if (minutes === undefined) {
127
+ value = sign * first
128
+ } else {
129
+ // As Astropy: the first field carries the sign, so "-0d30m" is negative.
130
+ const signed = sign * first
131
+ if (angleUnitText === 'hourangle' && !(Math.abs(signed) <= 24)) throw rangeError('hours', signed, text)
132
+ if (!(minutes >= 0 && minutes <= 60)) throw rangeError('minutes', minutes, text)
133
+ let a = Math.abs(signed) + minutes / 60.0
134
+ if (seconds !== undefined) {
135
+ if (!(seconds >= 0 && seconds <= 60)) throw rangeError('seconds', seconds, text)
136
+ a += seconds / 3600.0
137
+ }
138
+ value = Object.is(signed, -0) || signed < 0 ? -a : a
139
+ }
140
+ return new Quantity(value, angleUnit(angleUnitText))
141
+ }
142
+
143
+ function rangeError(field: string, value: number, text: string): QuantityParseError {
144
+ return new QuantityParseError(`${value} ${field} is out of range in the angle "${text}"`)
145
+ }
146
+
147
+ // --- Writing ----------------------------------------------------------------------------
148
+
149
+ export interface FormatAngleOptions {
150
+ /** The unit to write in: "deg" or "hourangle" give sexagesimal. Default: from `sep`, else the angle's own. */
151
+ readonly unit?: AngleUnit
152
+ /** A decimal number rather than sexagesimal. */
153
+ readonly decimal?: boolean
154
+ /**
155
+ * The separators: "dms" or "hms" (one per field), ":" or " " (between fields), or
156
+ * "fromunit", the default: dms for degrees, hms for hours. As in Astropy, a list gives
157
+ * separators longer than a character: `["h ", "m ", "s"]` writes "14h 29m 42.95s".
158
+ */
159
+ readonly sep?: string | readonly string[]
160
+ /** Decimal places of the last field (or of the number, with `decimal`). Default: as needed, up to 8. */
161
+ readonly precision?: number
162
+ /** A "+" on positive angles too. */
163
+ readonly alwaysSign?: boolean
164
+ /** Leading zeros on the first field: "05d" rather than "5d". */
165
+ readonly pad?: boolean
166
+ /** How many fields to write: 1 (degrees), 2 (and minutes) or 3 (and seconds, the default). */
167
+ readonly fields?: 1 | 2 | 3
168
+ }
169
+
170
+ /**
171
+ * An angle as text, as Astropy's Angle.to_string writes it: `formatAngle(q(187.69, "deg"),
172
+ * { unit: "hourangle" })` is "12h30m45.6s". Rounding that reaches 60 carries into the next
173
+ * field, and seconds always have two digits before the point.
174
+ */
175
+ export function formatAngle(angle: Quantity<'angle'>, options: FormatAngleOptions = {}): string {
176
+ const { decimal = false, sep = 'fromunit', precision, alwaysSign = false, pad = false, fields = 3 } = options
177
+ if (decimal && sep !== 'fromunit') throw new TypeError('A decimal angle has no separator')
178
+ const unitText = options.unit ?? (sep === 'dms' ? 'deg' : sep === 'hms' ? 'hourangle' : angle.unit.toString())
179
+ const unit = angleUnit(unitText)
180
+ const value = angle.to(unit).value
181
+ const isDegrees = unit.equals(angleUnit('deg'))
182
+ const sexagesimal = !decimal && (isDegrees || unit.equals(angleUnit('hourangle')))
183
+ let text: string
184
+ if (sexagesimal) {
185
+ const marks = sep === 'fromunit' ? (isDegrees ? 'dms' : 'hms') : sep
186
+ text = sexagesimalString(value, precision, pad, [...marks], fields)
187
+ } else {
188
+ text = precision === undefined ? pythonG(value) : pythonFixed(value, precision)
189
+ const unitString = unit.toString()
190
+ if (!decimal && unitString.length > 1) text += ` ${unitString}`
191
+ else if (!decimal) text += unitString
192
+ }
193
+ if (alwaysSign && !text.startsWith('-')) text = `+${text}`
194
+ return text
195
+ }
196
+
197
+ /** Astropy's _decimal_to_sexagesimal: truncated whole fields, the sign on each, -0 kept. */
198
+ function sexagesimal(a: number): [number, number, number] {
199
+ const sign = Object.is(a, -0) || a < 0 ? -1 : 1
200
+ const abs = Math.abs(a)
201
+ const d = Math.trunc(abs)
202
+ const df = abs - d
203
+ const m = Math.trunc(df * 60.0)
204
+ const mf = df * 60.0 - m
205
+ const s = mf * 60.0
206
+ return [Math.floor(sign * d), sign * Math.floor(m), sign * s]
207
+ }
208
+
209
+ /** Astropy's _decimal_to_sexagesimal_string, step for step. */
210
+ function sexagesimalString(
211
+ angle: number, precision: number | undefined, pad: boolean, sepChars: string[], fields: 1 | 2 | 3,
212
+ ): string {
213
+ const parts = sexagesimal(angle)
214
+ const negative = Object.is(parts[0], -0) || parts[0] < 0
215
+ const values = parts.map((v) => Math.abs(v)) as [number, number, number]
216
+ let sep: [string, string, string]
217
+ if (sepChars.length === 0) sep = ['', '', '']
218
+ else if (sepChars.length === 1) {
219
+ const c = sepChars[0] ?? ''
220
+ sep = fields === 3 ? [c, c, ''] : fields === 2 ? [c, '', ''] : ['', '', '']
221
+ } else if (sepChars.length === 2) sep = [sepChars[0] ?? '', sepChars[1] ?? '', '']
222
+ else if (sepChars.length === 3) sep = [sepChars[0] ?? '', sepChars[1] ?? '', sepChars[2] ?? '']
223
+ else throw new TypeError('Give one, two or three separators')
224
+
225
+ // Rounding that reaches 60 carries upward; a hidden field rounds at its middle.
226
+ const ndp = precision ?? 8
227
+ if (fields === 3) {
228
+ if (Number(pythonFixed(values[2], ndp)) >= 60.0) {
229
+ values[2] = 0.0
230
+ values[1] += 1.0
231
+ }
232
+ } else if (fields === 2) {
233
+ if (values[2] >= 30.0) values[1] += 1.0
234
+ } else if (values[1] + values[2] / 60.0 >= 30.0) {
235
+ values[0] += 1.0
236
+ }
237
+ if (fields >= 2 && values[1] >= 60.0) {
238
+ values[1] = 0.0
239
+ values[0] += 1.0
240
+ }
241
+
242
+ const whole = values[0].toFixed(0)
243
+ let literal = `${negative ? '-' : ''}${pad ? whole.padStart(2, '0') : whole}${sep[0]}`
244
+ if (fields >= 2) literal += `${String(Math.trunc(values[1])).padStart(2, '0')}${sep[1]}`
245
+ if (fields === 3) {
246
+ let last = precision === undefined
247
+ ? pythonFixed(values[2], 8).replace(/0+$/, '').replace(/\.$/, '')
248
+ : pythonFixed(values[2], precision)
249
+ if (last.length === 1 || last[1] === '.') last = `0${last}`
250
+ literal += `${last}${sep[2]}`
251
+ }
252
+ return literal
253
+ }
254
+
255
+ /**
256
+ * Python's "{:.pf}": x to p decimal places, an exact tie rounded to even (JavaScript's
257
+ * toFixed rounds it up), and -0 written "-0".
258
+ */
259
+ export function pythonFixed(x: number, p: number): string {
260
+ let text = x.toFixed(p)
261
+ // A tie has at most p + 1 decimals, so p + 30 places write it exactly.
262
+ const exact = x.toFixed(Math.min(100, p + 30))
263
+ const point = exact.indexOf('.')
264
+ const beyond = exact.slice(point + 1 + p)
265
+ if (/^50*$/.test(beyond)) {
266
+ const kept = p === 0 ? exact.slice(0, point) : exact.slice(0, point + 1 + p)
267
+ const lastDigit = Number(kept.at(-1))
268
+ if (lastDigit % 2 === 0) text = kept
269
+ }
270
+ if ((Object.is(x, -0) || (x < 0 && !text.startsWith('-')))) text = `-${text}`
271
+ return text
272
+ }
273
+
274
+ /** Python's "{:g}": six significant digits, trailing zeros dropped, an exponent outside 1e-4 to 1e6. */
275
+ export function pythonG(x: number): string {
276
+ if (x === 0) return Object.is(x, -0) ? '-0' : '0'
277
+ const exponent = Number(x.toExponential(5).split('e')[1])
278
+ if (exponent >= -4 && exponent < 6) {
279
+ const text = pythonFixed(x, 5 - exponent)
280
+ return text.includes('.') ? text.replace(/0+$/, '').replace(/\.$/, '') : text
281
+ }
282
+ const [mantissa = '', exp = ''] = x.toExponential(5).split('e')
283
+ const trimmed = mantissa.includes('.') ? mantissa.replace(/0+$/, '').replace(/\.$/, '') : mantissa
284
+ const digits = exp.replace(/^[+-]/, '').padStart(2, '0')
285
+ return `${trimmed}e${exp.startsWith('-') ? '-' : '+'}${digits}`
286
+ }
@@ -0,0 +1,51 @@
1
+ // The constants units are defined from. Each is exact by definition, except G, which is
2
+ // measured and carries its standard uncertainty.
3
+ //
4
+ // Sources:
5
+ // - SI (2019): the speed of light is a defining constant.
6
+ // - IAU 2012 Resolution B2: the astronomical unit, exactly 149 597 870 700 m.
7
+ // - IAU 2015 Resolution B2: the parsec, exactly 648 000/pi au.
8
+ // - IAU 2015 Resolution B3 (Prsa et al. 2016, AJ 152, 41): nominal solar and planetary
9
+ // values, used as units. They are conversion constants, not measurements of the Sun,
10
+ // Earth or Jupiter.
11
+ // - CODATA 2018: the Newtonian constant of gravitation. CODATA 2022 gives the same value.
12
+ // - IAU: a Julian year is 365.25 days of 86 400 SI seconds.
13
+
14
+ /** Speed of light in vacuum, m/s. Exact (SI). */
15
+ export const SPEED_OF_LIGHT = 299_792_458
16
+
17
+ /** Astronomical unit, m. Exact (IAU 2012 B2). */
18
+ export const ASTRONOMICAL_UNIT = 149_597_870_700
19
+
20
+ /** Julian year, s: 365.25 days of 86 400 s. Exact (IAU). */
21
+ export const JULIAN_YEAR = 31_557_600
22
+
23
+ /** Light year, m: the distance light travels in a Julian year. Exact: 9 460 730 472 580 800 m. */
24
+ export const LIGHT_YEAR = SPEED_OF_LIGHT * JULIAN_YEAR
25
+
26
+ /**
27
+ * Newtonian constant of gravitation, m^3 kg^-1 s^-2, with its one-sigma standard uncertainty
28
+ * (CODATA 2018). Masses in kilograms divide a GM by it; mass ratios don't need it.
29
+ */
30
+ export const GRAVITATIONAL_CONSTANT = { value: 6.674_30e-11, sigma: 0.000_15e-11 } as const
31
+
32
+ /** Nominal solar radius, m (IAU 2015 B3). */
33
+ export const NOMINAL_SOLAR_RADIUS = 6.957e8
34
+ /** Nominal solar luminosity, W (IAU 2015 B3). */
35
+ export const NOMINAL_SOLAR_LUMINOSITY = 3.828e26
36
+ /** Nominal total solar irradiance at 1 au, W/m^2 (IAU 2015 B3). The flux Earth receives. */
37
+ export const NOMINAL_SOLAR_IRRADIANCE = 1361
38
+ /** Nominal solar effective temperature, K (IAU 2015 B3). */
39
+ export const NOMINAL_SOLAR_TEMPERATURE = 5772
40
+ /** Nominal solar mass parameter GM, m^3/s^2 (IAU 2015 B3). */
41
+ export const NOMINAL_SOLAR_GM = 1.327_124_4e20
42
+
43
+ /** Nominal equatorial radius of Earth, m (IAU 2015 B3). */
44
+ export const NOMINAL_EARTH_RADIUS = 6.378_1e6
45
+ /** Nominal mass parameter GM of Earth, m^3/s^2 (IAU 2015 B3). */
46
+ export const NOMINAL_EARTH_GM = 3.986_004e14
47
+
48
+ /** Nominal equatorial radius of Jupiter, m (IAU 2015 B3). */
49
+ export const NOMINAL_JUPITER_RADIUS = 7.149_2e7
50
+ /** Nominal mass parameter GM of Jupiter, m^3/s^2 (IAU 2015 B3). */
51
+ export const NOMINAL_JUPITER_GM = 1.266_865_3e17