@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/quantity.ts
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
// Quantities: a value, its unit, its uncertainty and whether it is a limit.
|
|
2
|
+
//
|
|
3
|
+
// Uncertainties take the forms the Arcosmos API publishes: a symmetric one-sigma error,
|
|
4
|
+
// asymmetric errors (plus >= 0, minus <= 0), 16th and 84th percentiles, or the error ellipse
|
|
5
|
+
// SIMBAD gives a proper motion. Missing (null) means none is known, and anything computed
|
|
6
|
+
// from it has none either; an exact value has sigma 0.
|
|
7
|
+
//
|
|
8
|
+
// - Converting units and scaling by a number are exact, and carry every form of uncertainty
|
|
9
|
+
// (but scaling an ellipse, below) and any limit along. A negative factor swaps plus and
|
|
10
|
+
// minus, and upper and lower. Between log10 of a unit and the unit itself, which isn't
|
|
11
|
+
// linear, each end of an error is converted, so a symmetric error becomes an asymmetric one.
|
|
12
|
+
// - Arithmetic between quantities propagates symmetric errors to first order, treating the
|
|
13
|
+
// operands as independent: `a.minus(a)` has sigma times sqrt(2), not 0. Asymmetric errors,
|
|
14
|
+
// percentiles and limits are refused there, since first-order propagation doesn't define
|
|
15
|
+
// them: call `symmetrized()` first, saying how.
|
|
16
|
+
// - An error ellipse belongs to a vector, a proper motion's two components together, so it
|
|
17
|
+
// only follows a change of unit. Scaling by a number, arithmetic and `symmetrized()` refuse
|
|
18
|
+
// it: what it means for one component depends on what is done to the other.
|
|
19
|
+
import { QuantityParseError, UncertaintyError, UnitConversionError } from './errors.ts'
|
|
20
|
+
import type { ConvertibleKind, KindOf, TargetKind, UnitTarget } from './kinds.ts'
|
|
21
|
+
import { parseUnit } from './parse-unit.ts'
|
|
22
|
+
import { DIMENSIONLESS, type Kind, type LogPart, Unit } from './units.ts'
|
|
23
|
+
|
|
24
|
+
/** A one-sigma error, in the value's unit. */
|
|
25
|
+
export interface SymmetricUncertainty {
|
|
26
|
+
readonly kind: 'symmetric'
|
|
27
|
+
readonly value: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Upper and lower errors, in the value's unit: plus >= 0, minus <= 0. Either may be unknown. */
|
|
31
|
+
export interface AsymmetricUncertainty {
|
|
32
|
+
readonly kind: 'asymmetric'
|
|
33
|
+
readonly plus: number | null
|
|
34
|
+
readonly minus: number | null
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The 16th and 84th percentiles of a distribution whose median is the value, in its unit. */
|
|
38
|
+
export interface PercentileUncertainty {
|
|
39
|
+
readonly kind: 'percentiles'
|
|
40
|
+
readonly p16: number | null
|
|
41
|
+
readonly p84: number | null
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* An error ellipse, as SIMBAD gives for a proper motion: the uncertainty of the motion as a
|
|
46
|
+
* vector, so both of its components carry the same ellipse. Its axes are one-sigma errors in
|
|
47
|
+
* the value's unit, and `angle_deg` is the major axis's position angle, east of north, in
|
|
48
|
+
* degrees. Any part may be unknown.
|
|
49
|
+
*/
|
|
50
|
+
export interface EllipseUncertainty {
|
|
51
|
+
readonly kind: 'error_ellipse'
|
|
52
|
+
readonly major: number | null
|
|
53
|
+
readonly minor: number | null
|
|
54
|
+
readonly angle_deg: number | null
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** An uncertainty in the form its source publishes it. */
|
|
58
|
+
export type Uncertainty = SymmetricUncertainty | AsymmetricUncertainty | PercentileUncertainty | EllipseUncertainty
|
|
59
|
+
|
|
60
|
+
/** An error ellipse as the API writes it: its axes in `unit`, which may differ from the value's. */
|
|
61
|
+
export interface EllipseUncertaintyJSON extends EllipseUncertainty {
|
|
62
|
+
readonly unit: string | null
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** An uncertainty as the API writes it. */
|
|
66
|
+
export type UncertaintyJSON = Exclude<Uncertainty, EllipseUncertainty> | EllipseUncertaintyJSON
|
|
67
|
+
|
|
68
|
+
/** Set when a value is a limit rather than a measurement. */
|
|
69
|
+
export type Limit = 'upper' | 'lower'
|
|
70
|
+
|
|
71
|
+
export interface QuantityOptions {
|
|
72
|
+
/** A one-sigma error, in the value's unit. 0 for an exact value. */
|
|
73
|
+
readonly sigma?: number
|
|
74
|
+
/** Any other form of uncertainty. Give this or sigma, not both. */
|
|
75
|
+
readonly uncertainty?: Uncertainty | null
|
|
76
|
+
readonly limit?: Limit | null
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A quantity as JSON, in the shape of the API's measurements. Dimensionless is a null unit. */
|
|
80
|
+
export interface QuantityJSON {
|
|
81
|
+
readonly value: number
|
|
82
|
+
readonly unit: string | null
|
|
83
|
+
readonly uncertainty: UncertaintyJSON | null
|
|
84
|
+
readonly limit?: Limit
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** How symmetrized() turns asymmetric errors into one: the larger side, or the mean of the two. */
|
|
88
|
+
export type SymmetrizeRule = 'larger' | 'mean'
|
|
89
|
+
|
|
90
|
+
const symmetric = (value: number): SymmetricUncertainty => ({ kind: 'symmetric', value })
|
|
91
|
+
|
|
92
|
+
/** Normalizes -0 to 0, which would otherwise print as "-0". */
|
|
93
|
+
const plain = (x: number) => x + 0
|
|
94
|
+
|
|
95
|
+
function checkUncertainty(u: Uncertainty | null, unit: Unit<string>): void {
|
|
96
|
+
if (!u) return
|
|
97
|
+
const bad = (message: string) => new RangeError(`Invalid uncertainty: ${message}`)
|
|
98
|
+
if (u.kind === 'error_ellipse') {
|
|
99
|
+
for (const axis of [u.major, u.minor]) {
|
|
100
|
+
if (axis !== null && (!(axis >= 0) || !Number.isFinite(axis))) throw bad(`an axis must be a finite number >= 0, not ${axis}`)
|
|
101
|
+
}
|
|
102
|
+
if (u.angle_deg !== null && !Number.isFinite(u.angle_deg)) throw bad(`the angle must be finite, not ${u.angle_deg}`)
|
|
103
|
+
if (unit.log) throw bad(`an error ellipse can't be in a logarithmic unit (${unit})`)
|
|
104
|
+
} else if (u.kind === 'symmetric') {
|
|
105
|
+
if (!(u.value >= 0) || !Number.isFinite(u.value)) throw bad(`sigma must be a finite number >= 0, not ${u.value}`)
|
|
106
|
+
} else if (u.kind === 'asymmetric') {
|
|
107
|
+
if (u.plus !== null && (!(u.plus >= 0) || !Number.isFinite(u.plus))) throw bad(`plus must be >= 0, not ${u.plus}`)
|
|
108
|
+
if (u.minus !== null && (!(u.minus <= 0) || !Number.isFinite(u.minus))) throw bad(`minus must be <= 0, not ${u.minus}`)
|
|
109
|
+
} else if (u.kind === 'percentiles') {
|
|
110
|
+
for (const p of [u.p16, u.p84]) if (p !== null && !Number.isFinite(p)) throw bad(`a percentile must be finite, not ${p}`)
|
|
111
|
+
if (u.p16 !== null && u.p84 !== null && u.p16 > u.p84) throw bad(`p16 (${u.p16}) is above p84 (${u.p84})`)
|
|
112
|
+
} else {
|
|
113
|
+
throw bad(`unknown kind "${(u as { kind: unknown }).kind}"`)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The quantity under a linear map: `map` for values, `scale` for differences (errors), and
|
|
119
|
+
* `flip` when the map reverses order, swapping plus and minus, p16 and p84, upper and lower.
|
|
120
|
+
*/
|
|
121
|
+
function transform<K extends string>(
|
|
122
|
+
q: Quantity<string>, unit: Unit<K>, map: (x: number) => number, scale: (dx: number) => number, flip: boolean,
|
|
123
|
+
): Quantity<K> {
|
|
124
|
+
const u = q.uncertainty
|
|
125
|
+
const side = (x: number | null) => (x === null ? null : plain(scale(x)))
|
|
126
|
+
const point = (x: number | null) => (x === null ? null : map(x))
|
|
127
|
+
let uncertainty: Uncertainty | null = null
|
|
128
|
+
if (u?.kind === 'symmetric') uncertainty = symmetric(Math.abs(scale(u.value)))
|
|
129
|
+
else if (u?.kind === 'asymmetric') {
|
|
130
|
+
uncertainty = flip
|
|
131
|
+
? { kind: 'asymmetric', plus: side(u.minus), minus: side(u.plus) }
|
|
132
|
+
: { kind: 'asymmetric', plus: side(u.plus), minus: side(u.minus) }
|
|
133
|
+
} else if (u?.kind === 'percentiles') {
|
|
134
|
+
uncertainty = flip
|
|
135
|
+
? { kind: 'percentiles', p16: point(u.p84), p84: point(u.p16) }
|
|
136
|
+
: { kind: 'percentiles', p16: point(u.p16), p84: point(u.p84) }
|
|
137
|
+
} else if (u?.kind === 'error_ellipse') {
|
|
138
|
+
// Only a change of unit reaches here (scaled() refuses an ellipse), which keeps its angle.
|
|
139
|
+
const axis = (x: number | null) => (x === null ? null : plain(Math.abs(scale(x))))
|
|
140
|
+
uncertainty = { kind: 'error_ellipse', major: axis(u.major), minor: axis(u.minor), angle_deg: u.angle_deg }
|
|
141
|
+
}
|
|
142
|
+
const limit = q.limit && flip ? (q.limit === 'upper' ? 'lower' : 'upper') : q.limit
|
|
143
|
+
return new Quantity(map(q.value), unit, uncertainty, limit)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The linear map from one logarithmic unit to another: x_to = a x + b. 1 mag is -0.4 dex. */
|
|
147
|
+
function logConversion(from: LogPart, to: LogPart): { a: number; b: number } {
|
|
148
|
+
const factor = from.physical.to(to.physical)
|
|
149
|
+
const toDex = from.type === 'mag' ? -0.4 : 1
|
|
150
|
+
const fromDex = to.type === 'mag' ? -2.5 : 1
|
|
151
|
+
const a = from.type === to.type ? 1 : toDex * fromDex
|
|
152
|
+
return { a, b: fromDex * Math.log10(factor) }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Between a logarithmic unit and the linear unit it is the logarithm of: log10(X) and X (Astropy's
|
|
157
|
+
* dex(X) and X), or mag and dex and a plain number. value = factor × 10^(k x), k = 1 for dex and
|
|
158
|
+
* -0.4 for mag. The map isn't linear, so an error's size doesn't convert: each end of the
|
|
159
|
+
* interval it stands for does, as do percentiles, and a symmetric error becomes an asymmetric
|
|
160
|
+
* one. mag runs the other way, swapping plus and minus, p16 and p84, upper and lower.
|
|
161
|
+
*/
|
|
162
|
+
function logLinear<K extends string>(q: Quantity<string>, unit: Unit<K>): Quantity<K> {
|
|
163
|
+
const toLinear = q.unit.log !== null
|
|
164
|
+
const log = (toLinear ? q.unit.log : unit.log) as LogPart
|
|
165
|
+
const linear = toLinear ? unit : q.unit
|
|
166
|
+
if (!log.physical.isEquivalent(linear)) {
|
|
167
|
+
throw new UnitConversionError(`${String(q.unit) || 'dimensionless'} can't be converted to ${String(unit) || 'dimensionless'}`)
|
|
168
|
+
}
|
|
169
|
+
const k = log.type === 'mag' ? -0.4 : 1
|
|
170
|
+
let map: (x: number) => number
|
|
171
|
+
if (toLinear) {
|
|
172
|
+
const factor = log.physical.to(linear)
|
|
173
|
+
map = (x) => factor * 10 ** (k * x)
|
|
174
|
+
} else {
|
|
175
|
+
const factor = linear.to(log.physical)
|
|
176
|
+
map = (x) => Math.log10(factor * x) / k
|
|
177
|
+
}
|
|
178
|
+
const flip = k < 0
|
|
179
|
+
if (!toLinear && !(q.value > 0)) {
|
|
180
|
+
throw new RangeError(`${q} has no logarithm: only a positive value converts to ${unit}`)
|
|
181
|
+
}
|
|
182
|
+
const center = map(q.value)
|
|
183
|
+
/** Where value + dx lands, less where the value does. */
|
|
184
|
+
const end = (dx: number | null): number | null => {
|
|
185
|
+
if (dx === null) return null
|
|
186
|
+
if (dx === 0) return 0
|
|
187
|
+
if (!toLinear && !(q.value + dx > 0)) {
|
|
188
|
+
throw new UncertaintyError(
|
|
189
|
+
`${q} reaches ${q.value + dx} ${linear}, which has no logarithm: its errors can't follow it into ${unit}`,
|
|
190
|
+
)
|
|
191
|
+
}
|
|
192
|
+
return plain(map(q.value + dx) - center)
|
|
193
|
+
}
|
|
194
|
+
const point = (x: number | null): number | null => {
|
|
195
|
+
if (x === null) return null
|
|
196
|
+
if (!toLinear && !(x > 0)) {
|
|
197
|
+
throw new UncertaintyError(`${q} has a percentile at ${x} ${linear}, which has no logarithm`)
|
|
198
|
+
}
|
|
199
|
+
return map(x)
|
|
200
|
+
}
|
|
201
|
+
const u = q.uncertainty
|
|
202
|
+
let uncertainty: Uncertainty | null = null
|
|
203
|
+
if (u?.kind === 'error_ellipse') {
|
|
204
|
+
throw new UncertaintyError(`${q} has an error ellipse, which can't be in a logarithmic unit`)
|
|
205
|
+
} else if (u?.kind === 'symmetric') {
|
|
206
|
+
uncertainty = u.value === 0 ? symmetric(0) : {
|
|
207
|
+
kind: 'asymmetric',
|
|
208
|
+
plus: flip ? end(-u.value) : end(u.value),
|
|
209
|
+
minus: flip ? end(u.value) : end(-u.value),
|
|
210
|
+
}
|
|
211
|
+
} else if (u?.kind === 'asymmetric') {
|
|
212
|
+
uncertainty = flip
|
|
213
|
+
? { kind: 'asymmetric', plus: end(u.minus), minus: end(u.plus) }
|
|
214
|
+
: { kind: 'asymmetric', plus: end(u.plus), minus: end(u.minus) }
|
|
215
|
+
} else if (u?.kind === 'percentiles') {
|
|
216
|
+
uncertainty = flip
|
|
217
|
+
? { kind: 'percentiles', p16: point(u.p84), p84: point(u.p16) }
|
|
218
|
+
: { kind: 'percentiles', p16: point(u.p16), p84: point(u.p84) }
|
|
219
|
+
}
|
|
220
|
+
const limit = q.limit && flip ? (q.limit === 'upper' ? 'lower' : 'upper') : q.limit
|
|
221
|
+
return new Quantity(center, unit, uncertainty, limit)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** The square root of the sum of squares, or null if any term is unknown. */
|
|
225
|
+
function quadrature(...terms: (number | null)[]): number | null {
|
|
226
|
+
return terms.some((t) => t === null) ? null : Math.hypot(...(terms as number[]))
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* A value with a unit, and its uncertainty if known. `K` is its kind, such as "length", where
|
|
231
|
+
* the type system can tell. Make one with `q(10, "ly")`. Immutable: every operation returns a
|
|
232
|
+
* new quantity.
|
|
233
|
+
*/
|
|
234
|
+
export class Quantity<K extends string = Kind> {
|
|
235
|
+
readonly value: number
|
|
236
|
+
readonly unit: Unit<K>
|
|
237
|
+
/** Null when no uncertainty is known. */
|
|
238
|
+
readonly uncertainty: Uncertainty | null
|
|
239
|
+
/** Set when the value is an upper or lower limit rather than a measurement. */
|
|
240
|
+
readonly limit: Limit | null
|
|
241
|
+
|
|
242
|
+
constructor(value: number, unit: Unit<K>, uncertainty: Uncertainty | null = null, limit: Limit | null = null) {
|
|
243
|
+
if (!Number.isFinite(value)) throw new RangeError(`A quantity's value must be a finite number, not ${value}`)
|
|
244
|
+
checkUncertainty(uncertainty, unit)
|
|
245
|
+
if (limit !== null && limit !== 'upper' && limit !== 'lower') throw new RangeError(`Invalid limit "${limit}"`)
|
|
246
|
+
this.value = value
|
|
247
|
+
this.unit = unit
|
|
248
|
+
this.uncertainty = uncertainty
|
|
249
|
+
this.limit = limit
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** The kind of quantity, such as "length". */
|
|
253
|
+
get kind(): K {
|
|
254
|
+
return this.unit.kind
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The one-sigma error when the uncertainty is symmetric; null otherwise. */
|
|
258
|
+
get sigma(): number | null {
|
|
259
|
+
return this.uncertainty?.kind === 'symmetric' ? this.uncertainty.value : null
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Methods that take a quantity or unit of the same kind read the kind from `this`, rather
|
|
263
|
+
// than from K, so a Quantity<"length"> is still a Quantity<string> wherever any is accepted.
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* The quantity in another unit of the same kind: `q(10, "ly").to("pc")`. Exact, uncertainty
|
|
267
|
+
* included. Magnitudes and dex convert to each other, and log10 of a unit to the unit
|
|
268
|
+
* (`q(5.25, "log10(L_sun)").to("L_sun")`) and back, each end of an error converted.
|
|
269
|
+
*/
|
|
270
|
+
to<Q extends Quantity<string>, const T extends UnitTarget<KindOfQuantity<Q>>>(this: Q, target: T): Quantity<TargetKind<T>> {
|
|
271
|
+
const unit: Unit = typeof target === 'string' ? parseUnit(target) : target
|
|
272
|
+
let result: Quantity<string>
|
|
273
|
+
if (!this.unit.log !== !unit.log) {
|
|
274
|
+
result = logLinear(this, unit)
|
|
275
|
+
} else if (this.unit.log && unit.log) {
|
|
276
|
+
const { a, b } = logConversion(this.unit.log, unit.log)
|
|
277
|
+
result = transform(this, unit, (x) => a * x + b, (dx) => a * dx, a < 0)
|
|
278
|
+
} else {
|
|
279
|
+
const factor = this.unit.to(unit)
|
|
280
|
+
result = transform(this, unit, (x) => x * factor, (dx) => dx * factor, false)
|
|
281
|
+
}
|
|
282
|
+
return result as Quantity<TargetKind<T>>
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** The value in another unit: `q(10, "ly").valueIn("pc")`. */
|
|
286
|
+
valueIn<Q extends Quantity<string>>(this: Q, target: UnitTarget<KindOfQuantity<Q>>): number {
|
|
287
|
+
return (this as Quantity<string>).to(target as string | Unit).value
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** The same quantity typed as kind K2, checked when it runs: `a.div(b).as("speed")`. */
|
|
291
|
+
as<K2 extends Kind>(kind: K2): Quantity<K2> {
|
|
292
|
+
if ((this.kind as string) !== kind) throw new UnitConversionError(`${this} is a quantity of ${this.kind}, not ${kind}`)
|
|
293
|
+
return this as unknown as Quantity<K2>
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The sum, in this quantity's unit. Sigmas add in quadrature. */
|
|
297
|
+
plus<Q extends Quantity<string>>(this: Q, other: Quantity<ConvertibleKind<KindOfQuantity<Q>>>): Quantity<KindOfQuantity<Q>> {
|
|
298
|
+
return add(this, other, 1) as Quantity<KindOfQuantity<Q>>
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** The difference, in this quantity's unit. Sigmas add in quadrature. */
|
|
302
|
+
minus<Q extends Quantity<string>>(this: Q, other: Quantity<ConvertibleKind<KindOfQuantity<Q>>>): Quantity<KindOfQuantity<Q>> {
|
|
303
|
+
return add(this, other, -1) as Quantity<KindOfQuantity<Q>>
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Times a number, which is exact, or times a quantity, with first-order propagation. */
|
|
307
|
+
times(factor: number): Quantity<K>
|
|
308
|
+
times(other: Quantity<string>): Quantity
|
|
309
|
+
times(other: number | Quantity<string>): Quantity<string> {
|
|
310
|
+
if (typeof other === 'number') return this.scaled(other, (x) => x * other)
|
|
311
|
+
requireArithmetic(this, 'multiplied')
|
|
312
|
+
requireArithmetic(other, 'multiplied')
|
|
313
|
+
const unit = this.unit.times(other.unit)
|
|
314
|
+
const [a, b] = [this.value, other.value]
|
|
315
|
+
const sa = this.sigma
|
|
316
|
+
const sb = other.sigma
|
|
317
|
+
const sigma = sa === null || sb === null ? null : Math.hypot(b * sa, a * sb)
|
|
318
|
+
return new Quantity(a * b, unit, sigma === null ? null : symmetric(sigma))
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Divided by a number, which is exact, or by a quantity, with first-order propagation. */
|
|
322
|
+
div(divisor: number): Quantity<K>
|
|
323
|
+
div(other: Quantity<string>): Quantity
|
|
324
|
+
div(other: number | Quantity<string>): Quantity<string> {
|
|
325
|
+
if (typeof other === 'number') {
|
|
326
|
+
if (!Number.isFinite(other)) throw new RangeError(`A quantity can only be divided by a finite number, not ${other}`)
|
|
327
|
+
if (other === 0) throw new RangeError('Division by zero')
|
|
328
|
+
return this.scaled(1 / other, (x) => x / other)
|
|
329
|
+
}
|
|
330
|
+
requireArithmetic(this, 'divided')
|
|
331
|
+
requireArithmetic(other, 'divided')
|
|
332
|
+
const unit = this.unit.div(other.unit)
|
|
333
|
+
const [a, b] = [this.value, other.value]
|
|
334
|
+
if (b === 0) throw new RangeError('Division by zero')
|
|
335
|
+
const sa = this.sigma
|
|
336
|
+
const sb = other.sigma
|
|
337
|
+
const sigma = sa === null || sb === null ? null : Math.hypot(sa / b, (a / b) * (sb / b))
|
|
338
|
+
return new Quantity(a / b, unit, sigma === null ? null : symmetric(sigma))
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** To a power, with first-order propagation: sigma times |n a^(n-1)|. */
|
|
342
|
+
pow(n: number): Quantity {
|
|
343
|
+
requireArithmetic(this, 'raised to a power')
|
|
344
|
+
const unit = this.unit.pow(n)
|
|
345
|
+
const s = this.sigma
|
|
346
|
+
const sigma = s === null ? null : s === 0 || n === 0 ? 0 : Math.abs(n * this.value ** (n - 1)) * s
|
|
347
|
+
return new Quantity(this.value ** n, unit, sigma === null ? null : symmetric(sigma))
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** The negative of the quantity. Plus and minus swap, as do upper and lower limits. */
|
|
351
|
+
negate(): Quantity<K> {
|
|
352
|
+
return this.scaled(-1, (x) => -x)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* The quantity with a symmetric sigma in place of asymmetric errors or percentiles: the
|
|
357
|
+
* larger side (the API's rule for its derived values), or the mean of the two. Null when
|
|
358
|
+
* either side is unknown. An error ellipse is refused: its error along one component
|
|
359
|
+
* depends on which component this is, which the quantity doesn't know.
|
|
360
|
+
*/
|
|
361
|
+
symmetrized(rule: SymmetrizeRule = 'larger'): Quantity<K> {
|
|
362
|
+
const u = this.uncertainty
|
|
363
|
+
if (!u || u.kind === 'symmetric') return this
|
|
364
|
+
if (u.kind === 'error_ellipse') throw ellipseError(this, 'symmetrized')
|
|
365
|
+
const [up, down] = u.kind === 'asymmetric'
|
|
366
|
+
? [u.plus, u.minus === null ? null : -u.minus]
|
|
367
|
+
: [u.p84 === null ? null : u.p84 - this.value, u.p16 === null ? null : this.value - u.p16]
|
|
368
|
+
const sigma = up === null || down === null ? null : rule === 'larger' ? Math.max(up, down) : (up + down) / 2
|
|
369
|
+
return new Quantity(this.value, this.unit, sigma === null ? null : symmetric(sigma), this.limit)
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* -1, 0 or 1 as this quantity is less than, equal to or greater than the other, uncertainties
|
|
374
|
+
* aside. A magnitude and a dex don't compare: mag runs the other way, so neither order would
|
|
375
|
+
* be the obvious one.
|
|
376
|
+
*/
|
|
377
|
+
compare<Q extends Quantity<string>>(this: Q, other: Quantity<KindOfQuantity<Q>>): number {
|
|
378
|
+
const a = this.unit.log
|
|
379
|
+
const b = (other as Quantity<string>).unit.log
|
|
380
|
+
if (a && b && a.type !== b.type) throw new UnitConversionError('A magnitude and a dex don\'t compare: convert one first')
|
|
381
|
+
return Math.sign(this.value - (other as Quantity<string>).to(this.unit).value)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** "1.2 ± 0.1 mas", "0.5 +0.2 -0.1 M_jup", "< 3 M_earth". */
|
|
385
|
+
toString(): string {
|
|
386
|
+
const u = this.uncertainty
|
|
387
|
+
let error = ''
|
|
388
|
+
if (u?.kind === 'symmetric') error = ` ± ${u.value}`
|
|
389
|
+
else if (u?.kind === 'asymmetric') error = ` +${u.plus ?? '?'} ${u.minus === null ? '-?' : plain(u.minus) === 0 ? '-0' : u.minus}`
|
|
390
|
+
else if (u?.kind === 'percentiles') error = ` (p16 ${u.p16 ?? '?'}, p84 ${u.p84 ?? '?'})`
|
|
391
|
+
else if (u?.kind === 'error_ellipse') {
|
|
392
|
+
error = ` (error ellipse ${u.major ?? '?'} × ${u.minor ?? '?'} at ${u.angle_deg ?? '?'} deg)`
|
|
393
|
+
}
|
|
394
|
+
const limit = this.limit === 'upper' ? '< ' : this.limit === 'lower' ? '> ' : ''
|
|
395
|
+
const unit = this.unit.toString()
|
|
396
|
+
return `${limit}${this.value}${error}${unit ? ` ${unit}` : ''}`
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** The quantity in the API's shape. An error ellipse names its unit, the value's. */
|
|
400
|
+
toJSON(): QuantityJSON {
|
|
401
|
+
const text = this.unit.toString()
|
|
402
|
+
const unit = text === '' ? null : text
|
|
403
|
+
const u = this.uncertainty
|
|
404
|
+
return {
|
|
405
|
+
value: this.value,
|
|
406
|
+
unit,
|
|
407
|
+
uncertainty: u?.kind === 'error_ellipse' ? { ...u, unit } : u,
|
|
408
|
+
...(this.limit ? { limit: this.limit } : {}),
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Scaled by a number: exact, carrying every form of uncertainty but an ellipse, and the limit. */
|
|
413
|
+
private scaled(factor: number, map: (x: number) => number): Quantity<K> {
|
|
414
|
+
if (!Number.isFinite(factor)) throw new RangeError(`A quantity can only be scaled by a finite number, not ${factor}`)
|
|
415
|
+
if (this.unit.log) throw new UnitConversionError(`${this.unit} is logarithmic: scaling it by a number isn't defined`)
|
|
416
|
+
if (this.uncertainty?.kind === 'error_ellipse') throw ellipseError(this, 'scaled by a number')
|
|
417
|
+
return transform(this, this.unit, map, (dx) => map(dx), factor < 0)
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* An ellipse describes a vector: scaling or combining one of its components distorts it in a
|
|
423
|
+
* way that depends on the other, so only a change of unit keeps it.
|
|
424
|
+
*/
|
|
425
|
+
function ellipseError(q: Quantity<string>, verb: string): UncertaintyError {
|
|
426
|
+
return new UncertaintyError(
|
|
427
|
+
`${q} has an error ellipse and can't be ${verb}: the ellipse is the error of a vector (a proper motion's two `
|
|
428
|
+
+ 'components), so its error along this one depends on which it is. Make a quantity with the sigma you take for it',
|
|
429
|
+
)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** The kind of a quantity type: KindOfQuantity<Quantity<"length">> is "length". */
|
|
433
|
+
export type KindOfQuantity<Q> = Q extends Quantity<infer K> ? K : never
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Refuses limits, asymmetric errors, percentiles and error ellipses, which first-order
|
|
437
|
+
* propagation doesn't define. @internal Not part of the package's API (distance.ts uses it).
|
|
438
|
+
*/
|
|
439
|
+
export function requireArithmetic(q: Quantity<string>, verb: string): void {
|
|
440
|
+
if (q.limit) {
|
|
441
|
+
throw new UncertaintyError(
|
|
442
|
+
`${q} is ${q.limit === 'upper' ? 'an upper' : 'a lower'} limit and can't be ${verb}: `
|
|
443
|
+
+ 'only unit conversion and scaling by a number keep a limit',
|
|
444
|
+
)
|
|
445
|
+
}
|
|
446
|
+
const u = q.uncertainty
|
|
447
|
+
if (u?.kind === 'error_ellipse') throw ellipseError(q, verb)
|
|
448
|
+
if (u && u.kind !== 'symmetric') {
|
|
449
|
+
throw new UncertaintyError(
|
|
450
|
+
`${q} has ${u.kind === 'asymmetric' ? 'asymmetric errors' : 'percentiles'} and can't be ${verb}: `
|
|
451
|
+
+ 'first-order propagation needs a symmetric sigma. Call symmetrized("larger") or symmetrized("mean") first',
|
|
452
|
+
)
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** a + sign × b, in a's unit. */
|
|
457
|
+
function add(a: Quantity<string>, b: Quantity<string>, sign: 1 | -1): Quantity<string> {
|
|
458
|
+
const verb = sign > 0 ? 'added' : 'subtracted'
|
|
459
|
+
requireArithmetic(a, verb)
|
|
460
|
+
requireArithmetic(b, verb)
|
|
461
|
+
if (a.unit.log || b.unit.log) return addLogarithmic(a, b, sign)
|
|
462
|
+
const factor = b.unit.to(a.unit)
|
|
463
|
+
const sb = b.sigma
|
|
464
|
+
const sigma = quadrature(a.sigma, sb === null ? null : factor * sb)
|
|
465
|
+
return new Quantity(a.value + sign * factor * b.value, a.unit, sigma === null ? null : symmetric(sigma))
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* mag ± mag (a color) and dex ± dex, the second converted to the first's scale. log10 of a unit
|
|
470
|
+
* with a dimension isn't added yet: its sum is log10 of a product.
|
|
471
|
+
*/
|
|
472
|
+
function addLogarithmic(a: Quantity<string>, b: Quantity<string>, sign: 1 | -1): Quantity<string> {
|
|
473
|
+
const la = a.unit.log
|
|
474
|
+
const lb = b.unit.log
|
|
475
|
+
if (!la || !lb) throw new UnitConversionError(`A logarithmic and a linear quantity can't be added: ${a} and ${b}`)
|
|
476
|
+
if (la.physical.kind !== 'dimensionless' || lb.physical.kind !== 'dimensionless') {
|
|
477
|
+
throw new UnitConversionError(`Adding or subtracting ${a.unit} and ${b.unit} isn't built yet: only mag and dex`)
|
|
478
|
+
}
|
|
479
|
+
// b in plain mag or dex, as a is written, so a ratio inside b's unit (log10(R_sun/R_earth)) counts.
|
|
480
|
+
const plainB = b.to(Unit.logarithmic(la.type, DIMENSIONLESS))
|
|
481
|
+
const sigma = quadrature(a.sigma, plainB.sigma)
|
|
482
|
+
return new Quantity(a.value + sign * plainB.value, a.unit, sigma === null ? null : symmetric(sigma))
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* A quantity: `q(10, "ly")`, `q(1.2, "mas", { sigma: 0.1 })`. Typed by the unit's kind where
|
|
487
|
+
* the type system knows it.
|
|
488
|
+
*/
|
|
489
|
+
export function q<const S extends string>(value: number, unit: S, options?: QuantityOptions): Quantity<KindOf<S>>
|
|
490
|
+
export function q<K extends string>(value: number, unit: Unit<K>, options?: QuantityOptions): Quantity<K>
|
|
491
|
+
export function q(value: number, unit: string | Unit, options: QuantityOptions = {}): Quantity {
|
|
492
|
+
if (options.sigma !== undefined && options.uncertainty !== undefined) {
|
|
493
|
+
throw new TypeError('Give sigma or uncertainty, not both')
|
|
494
|
+
}
|
|
495
|
+
const uncertainty = options.sigma !== undefined ? symmetric(options.sigma) : options.uncertainty ?? null
|
|
496
|
+
return new Quantity(value, typeof unit === 'string' ? parseUnit(unit) : unit, uncertainty, options.limit ?? null)
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/** A measurement as the Arcosmos API returns it (only the fields read here). */
|
|
500
|
+
export interface MeasurementLike {
|
|
501
|
+
readonly value: number | string
|
|
502
|
+
readonly unit: string | null
|
|
503
|
+
readonly uncertainty?: Uncertainty | UncertaintyJSON | null
|
|
504
|
+
readonly limit?: Limit | null
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* A quantity from one of the API's measurements, with its uncertainty and limit. An error
|
|
509
|
+
* ellipse (SIMBAD's proper motions) is kept, its axes in the value's unit. A label (such as a
|
|
510
|
+
* spectral type) isn't a quantity, and throws.
|
|
511
|
+
*/
|
|
512
|
+
export function fromMeasurement(measurement: MeasurementLike): Quantity {
|
|
513
|
+
if (typeof measurement.value !== 'number') {
|
|
514
|
+
throw new TypeError(`"${measurement.value}" is a label, not a number`)
|
|
515
|
+
}
|
|
516
|
+
const unit = parseUnit(measurement.unit ?? '')
|
|
517
|
+
let u: Uncertainty | null = measurement.uncertainty ?? null
|
|
518
|
+
if (u?.kind === 'error_ellipse') {
|
|
519
|
+
const axes = 'unit' in u && typeof u.unit === 'string' ? parseUnit(u.unit) : unit
|
|
520
|
+
const factor = axes.to(unit)
|
|
521
|
+
const axis = (x: number | null) => (x === null ? null : x * factor)
|
|
522
|
+
u = { kind: 'error_ellipse', major: axis(u.major), minor: axis(u.minor), angle_deg: u.angle_deg }
|
|
523
|
+
}
|
|
524
|
+
return new Quantity(measurement.value, unit, u, measurement.limit ?? null)
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
const NUMBER = String.raw`(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?`
|
|
528
|
+
const QUANTITY = new RegExp(String.raw`^\s*([-+]?${NUMBER})(?:\s*(?:±|\+/-|\+-)\s*(${NUMBER}))?\s*(.*?)\s*$`)
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* A quantity from text: "10 ly", "-1.46 mag", "1.2 ± 0.1 mas" (or "+/-"). A number alone is
|
|
532
|
+
* dimensionless. Throws a QuantityParseError, or a UnitParseError for an unknown unit.
|
|
533
|
+
*/
|
|
534
|
+
export function parseQuantity(text: string): Quantity {
|
|
535
|
+
const match = QUANTITY.exec(text)
|
|
536
|
+
if (!match) throw new QuantityParseError(`"${text}" isn't a number and a unit, such as "10 ly"`)
|
|
537
|
+
const [, value, sigma, unitText] = match
|
|
538
|
+
return q(Number(value), parseUnit(unitText ?? ''), sigma === undefined ? {} : { sigma: Number(sigma) })
|
|
539
|
+
}
|
package/src/rounding.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// How a computed value is printed: rounded to what its uncertainty allows, as results are
|
|
2
|
+
// usually quoted. Published values are printed as published; these are for values computed
|
|
3
|
+
// from them, so every client rounds a derived value the same way.
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A computed value and its one-sigma error, rounded as results are usually quoted: the error
|
|
7
|
+
* to two significant digits and the value to the same place. 46.3523 ± 0.8641 becomes
|
|
8
|
+
* "46.35" and "0.86", 694.01 ± 88.20 becomes "694" and "88", 1234.5 ± 156 becomes "1230" and
|
|
9
|
+
* "160", and 2 ± 0.0996 becomes "2.00" and "0.10". Trailing zeros are kept: they say how
|
|
10
|
+
* precise the value is. Null when the error isn't a positive finite number, for the caller to
|
|
11
|
+
* print the value in full.
|
|
12
|
+
*/
|
|
13
|
+
export function roundToUncertainty(value: number, error: number): { value: string; error: string } | null {
|
|
14
|
+
if (!Number.isFinite(value) || !Number.isFinite(error) || !(error > 0)) return null
|
|
15
|
+
// The place of the error's second significant digit: 0.86 -> 2 decimals, 88 -> 0, 156 -> -1.
|
|
16
|
+
let decimals = 1 - Math.floor(Math.log10(error))
|
|
17
|
+
// An error that rounds up to a third digit (0.0996 to 0.100) has two at the next place up.
|
|
18
|
+
if (Math.round(error * 10 ** decimals) >= 100) decimals -= 1
|
|
19
|
+
const round = (x: number) => {
|
|
20
|
+
if (decimals >= 0) return x.toFixed(decimals)
|
|
21
|
+
const step = 10 ** -decimals
|
|
22
|
+
return String(Math.round(x / step) * step)
|
|
23
|
+
}
|
|
24
|
+
return { value: round(value), error: round(error) }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A computed value with no error to round to, to a few significant digits: for a value whose
|
|
29
|
+
* inputs were published without errors. 2158.38 becomes "2160". Mark it as approximate.
|
|
30
|
+
*/
|
|
31
|
+
export function roundToSignificant(value: number, digits = 3): string {
|
|
32
|
+
return String(Number(value.toPrecision(digits)))
|
|
33
|
+
}
|