@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.
- package/LICENSE +202 -0
- package/README.md +227 -2
- package/dist/angles.d.ts +51 -0
- package/dist/angles.d.ts.map +1 -0
- package/dist/angles.js +261 -0
- package/dist/angles.js.map +1 -0
- package/dist/constants.d.ts +35 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +44 -0
- package/dist/constants.js.map +1 -0
- package/dist/coordinates.d.ts +213 -0
- package/dist/coordinates.d.ts.map +1 -0
- package/dist/coordinates.js +474 -0
- package/dist/coordinates.js.map +1 -0
- package/dist/distance.d.ts +26 -0
- package/dist/distance.d.ts.map +1 -0
- package/dist/distance.js +54 -0
- package/dist/distance.js.map +1 -0
- package/dist/errors.d.ts +24 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/kinds.d.ts +86 -0
- package/dist/kinds.d.ts.map +1 -0
- package/dist/kinds.js +29 -0
- package/dist/kinds.js.map +1 -0
- package/dist/parse-unit.d.ts +11 -0
- package/dist/parse-unit.d.ts.map +1 -0
- package/dist/parse-unit.js +222 -0
- package/dist/parse-unit.js.map +1 -0
- package/dist/quantity.d.ts +150 -0
- package/dist/quantity.d.ts.map +1 -0
- package/dist/quantity.js +452 -0
- package/dist/quantity.js.map +1 -0
- package/dist/rounding.d.ts +18 -0
- package/dist/rounding.d.ts.map +1 -0
- package/dist/rounding.js +35 -0
- package/dist/rounding.js.map +1 -0
- package/dist/time.d.ts +100 -0
- package/dist/time.d.ts.map +1 -0
- package/dist/time.js +448 -0
- package/dist/time.js.map +1 -0
- package/dist/units.d.ts +394 -0
- package/dist/units.d.ts.map +1 -0
- package/dist/units.js +353 -0
- package/dist/units.js.map +1 -0
- package/package.json +44 -3
- package/src/angles.ts +286 -0
- package/src/constants.ts +51 -0
- package/src/coordinates.ts +591 -0
- package/src/distance.ts +58 -0
- package/src/errors.ts +27 -0
- package/src/index.ts +27 -0
- package/src/kinds.ts +110 -0
- package/src/parse-unit.ts +230 -0
- package/src/quantity.ts +539 -0
- package/src/rounding.ts +33 -0
- package/src/time.ts +511 -0
- package/src/units.ts +445 -0
package/src/units.ts
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
// Units: what each symbol means, how units combine, and the factor between two of them.
|
|
2
|
+
//
|
|
3
|
+
// A unit is a product of base units, as in Astropy: the seven SI base units and the radian,
|
|
4
|
+
// since an angle is a dimension of its own (a rad doesn't convert to a plain number). Each unit
|
|
5
|
+
// has a dimension (the base units' exponents) and a size, and two units convert only when
|
|
6
|
+
// their dimensions match.
|
|
7
|
+
//
|
|
8
|
+
// Logarithmic units (mag, dex, log10(X)) are not sizes of anything. They live here as a unit
|
|
9
|
+
// with a `log` part, and Quantity converts them; Unit.to refuses them.
|
|
10
|
+
import {
|
|
11
|
+
ASTRONOMICAL_UNIT, GRAVITATIONAL_CONSTANT, JULIAN_YEAR, LIGHT_YEAR, NOMINAL_EARTH_GM, NOMINAL_EARTH_RADIUS,
|
|
12
|
+
NOMINAL_JUPITER_GM, NOMINAL_JUPITER_RADIUS, NOMINAL_SOLAR_GM, NOMINAL_SOLAR_IRRADIANCE, NOMINAL_SOLAR_LUMINOSITY,
|
|
13
|
+
NOMINAL_SOLAR_RADIUS,
|
|
14
|
+
} from './constants.ts'
|
|
15
|
+
import { UnitConversionError } from './errors.ts'
|
|
16
|
+
|
|
17
|
+
// --- Dimensions -------------------------------------------------------------------------
|
|
18
|
+
|
|
19
|
+
/** The base units, in the order a dimension lists their exponents. */
|
|
20
|
+
export const BASE_UNITS = ['m', 'kg', 's', 'A', 'K', 'mol', 'cd', 'rad'] as const
|
|
21
|
+
type Base = (typeof BASE_UNITS)[number]
|
|
22
|
+
|
|
23
|
+
/** Exponents of the base units, in BASE_UNITS' order. */
|
|
24
|
+
type Dims = readonly number[]
|
|
25
|
+
|
|
26
|
+
function dims(spec: Partial<Record<Base, number>>): Dims {
|
|
27
|
+
return BASE_UNITS.map((base) => spec[base] ?? 0)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const dimsKey = (d: Dims) => d.join(',')
|
|
31
|
+
const sameDims = (a: Dims, b: Dims) => a.every((x, i) => x === b[i])
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Each kind of quantity this library names, by its dimension. The names are Astropy's
|
|
35
|
+
* physical types (its first name where it has several, such as "speed" for speed/velocity).
|
|
36
|
+
*/
|
|
37
|
+
const KIND_DIMS = {
|
|
38
|
+
dimensionless: {},
|
|
39
|
+
length: { m: 1 },
|
|
40
|
+
mass: { kg: 1 },
|
|
41
|
+
time: { s: 1 },
|
|
42
|
+
'electrical current': { A: 1 },
|
|
43
|
+
temperature: { K: 1 },
|
|
44
|
+
'amount of substance': { mol: 1 },
|
|
45
|
+
'luminous intensity': { cd: 1 },
|
|
46
|
+
angle: { rad: 1 },
|
|
47
|
+
'solid angle': { rad: 2 },
|
|
48
|
+
area: { m: 2 },
|
|
49
|
+
volume: { m: 3 },
|
|
50
|
+
speed: { m: 1, s: -1 },
|
|
51
|
+
acceleration: { m: 1, s: -2 },
|
|
52
|
+
frequency: { s: -1 },
|
|
53
|
+
'angular speed': { rad: 1, s: -1 },
|
|
54
|
+
momentum: { kg: 1, m: 1, s: -1 },
|
|
55
|
+
force: { kg: 1, m: 1, s: -2 },
|
|
56
|
+
energy: { kg: 1, m: 2, s: -2 },
|
|
57
|
+
power: { kg: 1, m: 2, s: -3 },
|
|
58
|
+
'energy flux': { kg: 1, s: -3 },
|
|
59
|
+
'spectral flux density': { kg: 1, s: -2 },
|
|
60
|
+
pressure: { kg: 1, m: -1, s: -2 },
|
|
61
|
+
'mass density': { kg: 1, m: -3 },
|
|
62
|
+
} as const satisfies Record<string, Partial<Record<Base, number>>>
|
|
63
|
+
|
|
64
|
+
/** A kind of quantity with a linear unit, such as "length" or "angular speed". */
|
|
65
|
+
export type LinearKind = keyof typeof KIND_DIMS
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A kind this library names. Logarithmic units have kinds of their own: "magnitude", "dex"
|
|
69
|
+
* (a dimensionless dex, such as a metallicity), and "log(K)" for log10 of a unit of kind K.
|
|
70
|
+
*/
|
|
71
|
+
export type KnownKind = LinearKind | 'magnitude' | 'dex' | `log(${LinearKind})`
|
|
72
|
+
|
|
73
|
+
/** Any kind. One with no name is written as its dimension in base units, such as "m^3 kg^-1 s^-2". */
|
|
74
|
+
export type Kind = KnownKind | (string & {})
|
|
75
|
+
|
|
76
|
+
const KIND_BY_DIMS = new Map<string, LinearKind>(
|
|
77
|
+
Object.entries(KIND_DIMS).map(([kind, spec]) => [dimsKey(dims(spec)), kind as LinearKind]),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
function kindOfDims(d: Dims): string {
|
|
81
|
+
const known = KIND_BY_DIMS.get(dimsKey(d))
|
|
82
|
+
if (known) return known
|
|
83
|
+
return BASE_UNITS.flatMap((base, i) => {
|
|
84
|
+
const power = d[i] ?? 0
|
|
85
|
+
return power === 0 ? [] : [power === 1 ? base : `${base}^${power}`]
|
|
86
|
+
}).join(' ')
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// --- Sizes ------------------------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* A unit's size in base units: num / den × pi^pi × G^g. Pi and G are kept apart so they
|
|
93
|
+
* cancel exactly: arcsec to deg is then exactly 180/648000, and a mass ratio is a ratio of GMs,
|
|
94
|
+
* free of G's uncertainty. num and den are exact wherever the definitions allow.
|
|
95
|
+
*/
|
|
96
|
+
interface Scale {
|
|
97
|
+
readonly num: number
|
|
98
|
+
readonly den: number
|
|
99
|
+
readonly pi: number
|
|
100
|
+
readonly g: number
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const size = (num: number, den = 1, pi = 0, g = 0): Scale => ({ num, den, pi, g })
|
|
104
|
+
|
|
105
|
+
const ONE = size(1)
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* A power snapped to the nearest fraction with a denominator up to 10, as Astropy does, so
|
|
109
|
+
* float error doesn't build up: 0.1 × 3 is 0.3, and 1/6 six times is 1.
|
|
110
|
+
*/
|
|
111
|
+
export function snapPower(p: number): number {
|
|
112
|
+
for (let den = 1; den <= 10; den++) {
|
|
113
|
+
const num = Math.round(p * den)
|
|
114
|
+
if (Math.abs(p - num / den) <= 8 * Number.EPSILON * Math.max(1, Math.abs(p))) return num / den + 0
|
|
115
|
+
}
|
|
116
|
+
return p
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Throws when a size has overflowed or underflowed, rather than carrying Infinity or 0 along. */
|
|
120
|
+
function checkScale(s: Scale): Scale {
|
|
121
|
+
for (const x of [s.num, s.den]) {
|
|
122
|
+
if (!Number.isFinite(x) || x === 0) throw new RangeError('A unit this large or small is out of range')
|
|
123
|
+
}
|
|
124
|
+
return s
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function timesScale(a: Scale, b: Scale): Scale {
|
|
128
|
+
return checkScale({ num: a.num * b.num, den: a.den * b.den, pi: snapPower(a.pi + b.pi), g: snapPower(a.g + b.g) })
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function powScale(a: Scale, n: number): Scale {
|
|
132
|
+
const pi = snapPower(a.pi * n)
|
|
133
|
+
const g = snapPower(a.g * n)
|
|
134
|
+
return checkScale(n >= 0
|
|
135
|
+
? { num: a.num ** n, den: a.den ** n, pi, g }
|
|
136
|
+
: { num: a.den ** -n, den: a.num ** -n, pi, g })
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Multiplies by x^n, dividing for n = -1 so the result is correctly rounded. */
|
|
140
|
+
function timesPower(value: number, x: number, n: number): number {
|
|
141
|
+
if (n === 0) return value
|
|
142
|
+
if (n === 1) return value * x
|
|
143
|
+
if (n === -1) return value / x
|
|
144
|
+
return value * x ** n
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** A size in base units as one number: num pi^pi G^g / den, so a parsec is (au × 648000)/pi. */
|
|
148
|
+
function sizeInBase(s: Scale): number {
|
|
149
|
+
return timesPower(timesPower(s.num, Math.PI, s.pi), GRAVITATIONAL_CONSTANT.value, s.g) / s.den
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The factor from a to b. Where pi and G cancel, it is one division of exact products, so
|
|
154
|
+
* arcsec to deg is exactly 1/3600. Where they don't, it is the ratio of the two sizes, as
|
|
155
|
+
* Astropy computes it: light years to parsecs agrees with Astropy to the last digit.
|
|
156
|
+
*/
|
|
157
|
+
function ratio(a: Scale, b: Scale): number {
|
|
158
|
+
let factor = a.pi === b.pi && a.g === b.g ? (a.num * b.den) / (a.den * b.num) : sizeInBase(a) / sizeInBase(b)
|
|
159
|
+
// The products can overflow where the factor itself wouldn't: divide pairwise instead.
|
|
160
|
+
if (!Number.isFinite(factor) || factor === 0) {
|
|
161
|
+
factor = (a.num / b.num) * (b.den / a.den)
|
|
162
|
+
factor = timesPower(factor, Math.PI, a.pi - b.pi)
|
|
163
|
+
factor = timesPower(factor, GRAVITATIONAL_CONSTANT.value, a.g - b.g)
|
|
164
|
+
}
|
|
165
|
+
if (!Number.isFinite(factor) || factor === 0) throw new RangeError('The factor between these units is out of range')
|
|
166
|
+
return factor
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// --- Definitions ------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
interface Definition {
|
|
172
|
+
readonly kind: LinearKind
|
|
173
|
+
readonly size: Scale
|
|
174
|
+
readonly aliases?: readonly string[]
|
|
175
|
+
/** Whether SI prefixes apply, as in km, Myr or mas... (mas and uas are defined on their own). */
|
|
176
|
+
readonly prefixes?: boolean
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Every unit symbol this library reads, with Astropy's spellings as aliases. The kind is
|
|
181
|
+
* repeated here for the type system, which reads it to type a quantity from its unit; a test
|
|
182
|
+
* checks it matches the dimension.
|
|
183
|
+
*/
|
|
184
|
+
export const DEFINITIONS = {
|
|
185
|
+
// Length
|
|
186
|
+
m: { kind: 'length', size: ONE, prefixes: true },
|
|
187
|
+
au: { kind: 'length', size: size(ASTRONOMICAL_UNIT), aliases: ['AU'] },
|
|
188
|
+
pc: { kind: 'length', size: size(ASTRONOMICAL_UNIT * 648_000, 1, -1), prefixes: true, aliases: ['parsec'] },
|
|
189
|
+
lyr: { kind: 'length', size: size(LIGHT_YEAR), aliases: ['ly', 'lightyear'] },
|
|
190
|
+
Angstrom: { kind: 'length', size: size(1, 1e10), aliases: ['AA', 'angstrom'] },
|
|
191
|
+
R_sun: { kind: 'length', size: size(NOMINAL_SOLAR_RADIUS), aliases: ['solRad'] },
|
|
192
|
+
R_earth: { kind: 'length', size: size(NOMINAL_EARTH_RADIUS), aliases: ['earthRad'] },
|
|
193
|
+
R_jup: { kind: 'length', size: size(NOMINAL_JUPITER_RADIUS), aliases: ['jupiterRad'] },
|
|
194
|
+
// Mass. The Sun's, Earth's and Jupiter's are their nominal GM divided by G.
|
|
195
|
+
g: { kind: 'mass', size: size(1, 1000), prefixes: true },
|
|
196
|
+
M_sun: { kind: 'mass', size: size(NOMINAL_SOLAR_GM, 1, 0, -1), aliases: ['solMass'] },
|
|
197
|
+
M_earth: { kind: 'mass', size: size(NOMINAL_EARTH_GM, 1, 0, -1), aliases: ['earthMass'] },
|
|
198
|
+
M_jup: { kind: 'mass', size: size(NOMINAL_JUPITER_GM, 1, 0, -1), aliases: ['jupiterMass'] },
|
|
199
|
+
// Time. A year is a Julian year.
|
|
200
|
+
s: { kind: 'time', size: ONE, prefixes: true },
|
|
201
|
+
min: { kind: 'time', size: size(60) },
|
|
202
|
+
h: { kind: 'time', size: size(3600) },
|
|
203
|
+
d: { kind: 'time', size: size(86_400) },
|
|
204
|
+
yr: { kind: 'time', size: size(JULIAN_YEAR), prefixes: true, aliases: ['year'] },
|
|
205
|
+
// Temperature, current, amount, luminous intensity
|
|
206
|
+
K: { kind: 'temperature', size: ONE, prefixes: true },
|
|
207
|
+
A: { kind: 'electrical current', size: ONE },
|
|
208
|
+
mol: { kind: 'amount of substance', size: ONE },
|
|
209
|
+
cd: { kind: 'luminous intensity', size: ONE },
|
|
210
|
+
// Angles
|
|
211
|
+
rad: { kind: 'angle', size: ONE, prefixes: true },
|
|
212
|
+
deg: { kind: 'angle', size: size(1, 180, 1), aliases: ['degree'] },
|
|
213
|
+
arcmin: { kind: 'angle', size: size(1, 10_800, 1) },
|
|
214
|
+
arcsec: { kind: 'angle', size: size(1, 648_000, 1) },
|
|
215
|
+
mas: { kind: 'angle', size: size(1, 648_000_000, 1) },
|
|
216
|
+
uas: { kind: 'angle', size: size(1, 648_000_000_000, 1) },
|
|
217
|
+
hourangle: { kind: 'angle', size: size(1, 12, 1) },
|
|
218
|
+
sr: { kind: 'solid angle', size: ONE },
|
|
219
|
+
// Frequency, energy, power, flux
|
|
220
|
+
Hz: { kind: 'frequency', size: ONE, prefixes: true },
|
|
221
|
+
J: { kind: 'energy', size: ONE, prefixes: true },
|
|
222
|
+
erg: { kind: 'energy', size: size(1, 1e7) },
|
|
223
|
+
// The elementary charge is exact (SI 2019), so the electronvolt is too.
|
|
224
|
+
eV: { kind: 'energy', size: size(1.602_176_634e-19), prefixes: true },
|
|
225
|
+
W: { kind: 'power', size: ONE, prefixes: true },
|
|
226
|
+
L_sun: { kind: 'power', size: size(NOMINAL_SOLAR_LUMINOSITY), aliases: ['solLum'] },
|
|
227
|
+
Jy: { kind: 'spectral flux density', size: size(1, 1e26), prefixes: true },
|
|
228
|
+
// Not an Astropy unit: the flux Earth receives from the Sun, as the NASA Exoplanet Archive
|
|
229
|
+
// gives insolation. Taken as the nominal total solar irradiance at 1 au.
|
|
230
|
+
S_earth: { kind: 'energy flux', size: size(NOMINAL_SOLAR_IRRADIANCE) },
|
|
231
|
+
} as const satisfies Record<string, Definition>
|
|
232
|
+
|
|
233
|
+
/** SI prefixes and their powers of ten. `u` is micro; µ and μ are read as u. */
|
|
234
|
+
export const PREFIXES = {
|
|
235
|
+
Y: 24, Z: 21, E: 18, P: 15, T: 12, G: 9, M: 6, k: 3, h: 2, da: 1,
|
|
236
|
+
d: -1, c: -2, m: -3, u: -6, n: -9, p: -12, f: -15, a: -18, z: -21, y: -24,
|
|
237
|
+
} as const
|
|
238
|
+
|
|
239
|
+
/** A symbol the parser knows: its canonical spelling, dimension and size. */
|
|
240
|
+
interface Entry {
|
|
241
|
+
readonly key: string
|
|
242
|
+
readonly dims: Dims
|
|
243
|
+
readonly size: Scale
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function prefixed(base: Scale, power: number): Scale {
|
|
247
|
+
return power >= 0 ? { ...base, num: base.num * 10 ** power } : { ...base, den: base.den * 10 ** -power }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Every symbol, alias and prefixed symbol. Built once; a clash between two is a bug here. */
|
|
251
|
+
export const REGISTRY: ReadonlyMap<string, Entry> = (() => {
|
|
252
|
+
const registry = new Map<string, Entry>()
|
|
253
|
+
const add = (symbol: string, entry: Entry) => {
|
|
254
|
+
if (registry.has(symbol)) throw new Error(`Unit symbol ${symbol} is defined twice`)
|
|
255
|
+
registry.set(symbol, entry)
|
|
256
|
+
}
|
|
257
|
+
for (const [symbol, def] of Object.entries(DEFINITIONS) as [string, Definition][]) {
|
|
258
|
+
const d = dims(KIND_DIMS[def.kind])
|
|
259
|
+
add(symbol, { key: symbol, dims: d, size: def.size })
|
|
260
|
+
for (const alias of def.aliases ?? []) add(alias, { key: symbol, dims: d, size: def.size })
|
|
261
|
+
if (def.prefixes) {
|
|
262
|
+
for (const [prefix, power] of Object.entries(PREFIXES)) {
|
|
263
|
+
const name = prefix + symbol
|
|
264
|
+
add(name, { key: name, dims: d, size: prefixed(def.size, power) })
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return registry
|
|
269
|
+
})()
|
|
270
|
+
|
|
271
|
+
// --- Units ------------------------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
/** One symbol of a unit and its power, as written: `display` keeps the spelling given. */
|
|
274
|
+
interface Term {
|
|
275
|
+
readonly key: string
|
|
276
|
+
readonly display: string
|
|
277
|
+
readonly power: number
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** The logarithmic part of mag, dex and log10(X): which logarithm, and of what unit. */
|
|
281
|
+
export interface LogPart {
|
|
282
|
+
readonly type: 'mag' | 'dex'
|
|
283
|
+
readonly physical: Unit
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* A unit: a product of symbols with powers, such as km/s or log10(cm/s^2). Make one with
|
|
288
|
+
* `unit("km/s")`. `K` is its kind, such as "speed", where the type system can tell.
|
|
289
|
+
*/
|
|
290
|
+
export class Unit<K extends string = Kind> {
|
|
291
|
+
/** @internal The symbols and their powers, in the order written. */
|
|
292
|
+
readonly terms: readonly Term[]
|
|
293
|
+
/** @internal Exponents of the base units. */
|
|
294
|
+
readonly dims: Dims
|
|
295
|
+
/** @internal The size in base units. */
|
|
296
|
+
readonly size: Scale
|
|
297
|
+
/** @internal Set for mag, dex and log10(X). */
|
|
298
|
+
readonly log: LogPart | null
|
|
299
|
+
|
|
300
|
+
/** @internal Use `unit()`. */
|
|
301
|
+
constructor(terms: readonly Term[], dims: Dims, size: Scale, log: LogPart | null = null) {
|
|
302
|
+
this.terms = terms
|
|
303
|
+
this.dims = dims
|
|
304
|
+
this.size = size
|
|
305
|
+
this.log = log
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** @internal A logarithmic unit: mag, dex, or log10 of `physical` ("dex(X)" in Astropy). */
|
|
309
|
+
static logarithmic(type: 'mag' | 'dex', physical: Unit): Unit {
|
|
310
|
+
return new Unit([], physical.dims, physical.size, { type, physical })
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** The kind of quantity, such as "length", "speed", "magnitude" or "log(power)". */
|
|
314
|
+
get kind(): K {
|
|
315
|
+
if (this.log) {
|
|
316
|
+
if (this.log.type === 'mag') return 'magnitude' as K
|
|
317
|
+
const physical = this.log.physical.kind
|
|
318
|
+
return (physical === 'dimensionless' ? 'dex' : `log(${physical})`) as K
|
|
319
|
+
}
|
|
320
|
+
return kindOfDims(this.dims) as K
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Whether this is mag, dex or log10(X). */
|
|
324
|
+
get isLogarithmic(): boolean {
|
|
325
|
+
return this.log !== null
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** This unit times another, such as `unit("km").times(unit("s"))` for km s. */
|
|
329
|
+
times(other: Unit): Unit {
|
|
330
|
+
this.requireLinear('multiplied')
|
|
331
|
+
other.requireLinear('multiplied')
|
|
332
|
+
return new Unit(mergeTerms(this.terms, other.terms, 1), this.dims.map((x, i) => snapPower(x + (other.dims[i] ?? 0))),
|
|
333
|
+
timesScale(this.size, other.size))
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** This unit divided by another. */
|
|
337
|
+
div(other: Unit): Unit {
|
|
338
|
+
this.requireLinear('divided')
|
|
339
|
+
other.requireLinear('divided')
|
|
340
|
+
return new Unit(mergeTerms(this.terms, other.terms, -1), this.dims.map((x, i) => snapPower(x - (other.dims[i] ?? 0))),
|
|
341
|
+
timesScale(this.size, powScale(other.size, -1)))
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** This unit to a power, which may be a fraction (`unit("m^2").pow(0.5)` is m). */
|
|
345
|
+
pow(n: number): Unit {
|
|
346
|
+
this.requireLinear('raised to a power')
|
|
347
|
+
if (!Number.isFinite(n)) throw new RangeError(`A unit's power must be a finite number, not ${n}`)
|
|
348
|
+
const terms = n === 0 ? [] : this.terms.map((t) => ({ ...t, power: snapPower(t.power * n) })).filter((t) => t.power !== 0)
|
|
349
|
+
return new Unit(terms, this.dims.map((x) => snapPower(x * n)), powScale(this.size, n))
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* The number a value in this unit is multiplied by to give it in `other`: `unit("km").to(unit("m"))`
|
|
354
|
+
* is 1000. Throws a UnitConversionError for units of different kinds. Logarithmic units
|
|
355
|
+
* don't convert by a factor: convert a quantity in them with Quantity.to.
|
|
356
|
+
*/
|
|
357
|
+
to(other: Unit): number {
|
|
358
|
+
if (this.log || other.log) {
|
|
359
|
+
throw new UnitConversionError(
|
|
360
|
+
`${this} to ${other} isn't a factor: convert a quantity with Quantity.to for magnitudes and dex`,
|
|
361
|
+
)
|
|
362
|
+
}
|
|
363
|
+
if (!sameDims(this.dims, other.dims)) {
|
|
364
|
+
const self = this.toString() || 'dimensionless'
|
|
365
|
+
const target = other.toString() || 'dimensionless'
|
|
366
|
+
throw new UnitConversionError(`${self} (${this.kind}) can't be converted to ${target} (${other.kind})`)
|
|
367
|
+
}
|
|
368
|
+
return ratio(this.size, other.size)
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Whether a quantity in this unit converts to `other`: the same kind, both logarithmic of one
|
|
373
|
+
* kind, or log10 of a unit and the unit (mag and dex of a plain number).
|
|
374
|
+
*/
|
|
375
|
+
isEquivalent(other: Unit): boolean {
|
|
376
|
+
if (this.log || other.log) {
|
|
377
|
+
return (this.log?.physical ?? this).isEquivalent(other.log?.physical ?? other)
|
|
378
|
+
}
|
|
379
|
+
return sameDims(this.dims, other.dims)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** Whether the two units are the same size and kind, however written: km/s equals m/ms. */
|
|
383
|
+
equals(other: Unit): boolean {
|
|
384
|
+
if (this.log || other.log) {
|
|
385
|
+
return !!this.log && !!other.log && this.log.type === other.log.type && this.log.physical.equals(other.log.physical)
|
|
386
|
+
}
|
|
387
|
+
return sameDims(this.dims, other.dims) && Math.abs(ratio(this.size, other.size) - 1) <= 4 * Number.EPSILON
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** The unit as written: "km/s", "erg/(cm^2 s)", "log10(cm/s^2)". Dimensionless is "". */
|
|
391
|
+
toString(): string {
|
|
392
|
+
if (this.log) {
|
|
393
|
+
if (this.log.type === 'mag') return 'mag'
|
|
394
|
+
const physical = this.log.physical.toString()
|
|
395
|
+
return physical ? `log10(${physical})` : 'dex'
|
|
396
|
+
}
|
|
397
|
+
return formatTerms(this.terms)
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
toJSON(): string {
|
|
401
|
+
return this.toString()
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
private requireLinear(verb: string): void {
|
|
405
|
+
if (this.log) throw new UnitConversionError(`${this} is logarithmic and can't be ${verb}`)
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** a's terms with b's added at `sign` times their power, keeping the order first written. */
|
|
410
|
+
function mergeTerms(a: readonly Term[], b: readonly Term[], sign: 1 | -1): Term[] {
|
|
411
|
+
const terms = a.map((t) => ({ ...t }))
|
|
412
|
+
for (const t of b) {
|
|
413
|
+
const same = terms.find((x) => x.key === t.key)
|
|
414
|
+
if (same) same.power = snapPower(same.power + sign * t.power)
|
|
415
|
+
else terms.push({ ...t, power: sign * t.power })
|
|
416
|
+
}
|
|
417
|
+
return terms.filter((t) => t.power !== 0)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** A power as written back: "2", "-1", or a fraction in parentheses, "(1/2)", which reads back exactly. */
|
|
421
|
+
function powerText(p: number): string {
|
|
422
|
+
if (Number.isInteger(p)) return String(p)
|
|
423
|
+
for (let den = 2; den <= 10; den++) {
|
|
424
|
+
const num = Math.round(p * den)
|
|
425
|
+
if (num / den === p) return `(${num}/${den})`
|
|
426
|
+
}
|
|
427
|
+
return String(p)
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function formatTerms(terms: readonly Term[]): string {
|
|
431
|
+
const term = (t: Term, power: number) => (power === 1 ? t.display : `${t.display}^${powerText(power)}`)
|
|
432
|
+
const top = terms.filter((t) => t.power > 0).map((t) => term(t, t.power))
|
|
433
|
+
const bottom = terms.filter((t) => t.power < 0).map((t) => term(t, -t.power))
|
|
434
|
+
if (bottom.length === 0) return top.join(' ')
|
|
435
|
+
const below = bottom.length === 1 ? bottom[0] : `(${bottom.join(' ')})`
|
|
436
|
+
return `${top.length ? top.join(' ') : '1'}/${below}`
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** @internal The unit of one symbol, as written. */
|
|
440
|
+
export function symbolUnit(display: string, entry: Entry): Unit {
|
|
441
|
+
return new Unit([{ key: entry.key, display, power: 1 }], entry.dims, entry.size)
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** The dimensionless unit, written "". */
|
|
445
|
+
export const DIMENSIONLESS: Unit<'dimensionless'> = new Unit([], dims({}), ONE)
|