@ac-kit/math-linear 0.4.0 → 0.5.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 (39) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +57 -4
  3. package/dist/_euclidean-norm.d.ts +18 -0
  4. package/dist/_euclidean-norm.d.ts.map +1 -0
  5. package/dist/_euclidean-norm.js +73 -0
  6. package/dist/_euclidean-norm.js.map +1 -0
  7. package/dist/_matrix-shape.d.ts +4 -0
  8. package/dist/_matrix-shape.d.ts.map +1 -0
  9. package/dist/_matrix-shape.js +7 -0
  10. package/dist/_matrix-shape.js.map +1 -0
  11. package/dist/index.d.ts +5 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +5 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/lu-decomposition.d.ts +142 -0
  16. package/dist/lu-decomposition.d.ts.map +1 -0
  17. package/dist/lu-decomposition.js +416 -0
  18. package/dist/lu-decomposition.js.map +1 -0
  19. package/dist/matrix.d.ts +136 -0
  20. package/dist/matrix.d.ts.map +1 -0
  21. package/dist/matrix.js +308 -0
  22. package/dist/matrix.js.map +1 -0
  23. package/dist/qr-decomposition.d.ts +283 -0
  24. package/dist/qr-decomposition.d.ts.map +1 -0
  25. package/dist/qr-decomposition.js +1071 -0
  26. package/dist/qr-decomposition.js.map +1 -0
  27. package/dist/singular-value-decomposition.d.ts +154 -0
  28. package/dist/singular-value-decomposition.d.ts.map +1 -0
  29. package/dist/singular-value-decomposition.js +474 -0
  30. package/dist/singular-value-decomposition.js.map +1 -0
  31. package/dist/symmetric-eigen-decomposition.d.ts +92 -0
  32. package/dist/symmetric-eigen-decomposition.d.ts.map +1 -0
  33. package/dist/symmetric-eigen-decomposition.js +289 -0
  34. package/dist/symmetric-eigen-decomposition.js.map +1 -0
  35. package/dist/vec2-array.d.ts +16 -0
  36. package/dist/vec2-array.d.ts.map +1 -1
  37. package/dist/vec2-array.js +42 -0
  38. package/dist/vec2-array.js.map +1 -1
  39. package/package.json +11 -10
@@ -0,0 +1,1071 @@
1
+ import { assertInteger, describeValue, scaleByPowerOfTwoInPlace, } from "@ac-kit/core";
2
+ import { euclideanNorm_, pairNorm_ } from "./_euclidean-norm.js";
3
+ import { assertMatrixShape_ } from "./_matrix-shape.js";
4
+ /**
5
+ * Below this a reflector's `β` is subnormal and loses bits: the column is
6
+ * scaled up by `1 / SAFE_MINIMUM_` first, as LAPACK `xLARFG` does.
7
+ */
8
+ const SAFE_MINIMUM_ = 2 ** -1022 / Number.EPSILON;
9
+ /**
10
+ * A partial column norm downdated below `√ε` of its reference has lost its
11
+ * digits and is recomputed (LAPACK 3.x `xLAQP2`, Drmač and Bujanović 2008).
12
+ */
13
+ const DOWNDATE_LIMIT_ = Math.sqrt(Number.EPSILON);
14
+ /** The norm `householder_` reads back, never a returned double. */
15
+ const NORM_ = new Float64Array(1);
16
+ /** Where `scalars_` keeps the rank tolerance between `decompose` and its steps. */
17
+ const TOLERANCE_SLOT_ = 8;
18
+ /** Where `scalars_` keeps the covariance scale, read without boxing. */
19
+ const SCALE_SLOT_ = 9;
20
+ /**
21
+ * Writes the reflector `H = I − τ·v·vᵀ`, `v = (1, x / (α − β))`, that maps `(α,
22
+ * x)` to `(β, 0)` with `|β| = ‖(α, x)‖`: `β` replaces `α`, `v` (without its
23
+ * leading 1) replaces `x`, `τ` goes to `tau[tauIndex]` (`0`, so `H = I`, when
24
+ * `x = 0`). LAPACK `xLARFG`.
25
+ */
26
+ function householder_(data, alphaIndex, start, count, stride, tau, tauIndex) {
27
+ euclideanNorm_(NORM_, 0, data, start, count, stride);
28
+ let norm = NORM_[0];
29
+ if (norm === 0) {
30
+ tau[tauIndex] = 0;
31
+ return;
32
+ }
33
+ let alpha = data[alphaIndex];
34
+ let magnitude = pairNorm_(alpha, norm);
35
+ let rescales = 0;
36
+ while (magnitude < SAFE_MINIMUM_ && rescales < 20) {
37
+ rescales++;
38
+ let index = start;
39
+ for (let step = 0; step < count; step++) {
40
+ data[index] = data[index] / SAFE_MINIMUM_;
41
+ index += stride;
42
+ }
43
+ alpha /= SAFE_MINIMUM_;
44
+ euclideanNorm_(NORM_, 0, data, start, count, stride);
45
+ norm = NORM_[0];
46
+ magnitude = pairNorm_(alpha, norm);
47
+ }
48
+ let beta = alpha >= 0 ? -magnitude : magnitude;
49
+ tau[tauIndex] = (beta - alpha) / beta;
50
+ // |α − β| = |α| + |β| ≥ ‖x‖: no cancellation, and every quotient within 1.
51
+ const denominator = alpha - beta;
52
+ let index = start;
53
+ for (let step = 0; step < count; step++) {
54
+ data[index] = data[index] / denominator;
55
+ index += stride;
56
+ }
57
+ for (let step = 0; step < rescales; step++) {
58
+ beta *= SAFE_MINIMUM_;
59
+ }
60
+ data[alphaIndex] = beta;
61
+ }
62
+ /**
63
+ * One step of incremental condition estimation (Bischof 1990; LAPACK `xLAIC1`):
64
+ * given `‖xᵀR‖ = estimate` for a unit `x`, the largest (or smallest) of `‖(s·x,
65
+ * c)ᵀ · [[R, w], [0, γ]]‖` over `s² + c² = 1`, with `α = xᵀw`. That is the
66
+ * square root of an eigenvalue of `[[e² + α², αγ], [αγ, γ²]]`, solved here
67
+ * directly: `λmax` without cancellation and `λmin = e²γ² / λmax` from the
68
+ * determinant. Reads the old estimate, `α` and `γ` from `values[offset…offset +
69
+ * 2]` and writes the new estimate, `s` and `c` over them: no double crosses the
70
+ * call.
71
+ */
72
+ function incrementalEstimate_(values, offset, largest) {
73
+ const estimate = values[offset];
74
+ const alpha = values[offset + 1];
75
+ const gamma = values[offset + 2];
76
+ const absAlpha = Math.abs(alpha);
77
+ const absGamma = Math.abs(gamma);
78
+ let scale = estimate;
79
+ if (absAlpha > scale) {
80
+ scale = absAlpha;
81
+ }
82
+ if (absGamma > scale) {
83
+ scale = absGamma;
84
+ }
85
+ const e = estimate / scale;
86
+ const a = alpha / scale;
87
+ const g = gamma / scale;
88
+ const p = e * e + a * a;
89
+ const q = a * g;
90
+ const r = g * g;
91
+ const larger = (p + r) / 2 + pairNorm_((p - r) / 2, q);
92
+ const lambda = largest ? larger : (e * g * (e * g)) / larger;
93
+ // The eigenvector of λ, from whichever row of [[p − λ, q], [q, r − λ]] is
94
+ // larger, so a near-diagonal matrix keeps its digits.
95
+ let s = q;
96
+ let c = lambda - p;
97
+ const otherS = lambda - r;
98
+ const otherC = q;
99
+ if (pairNorm_(otherS, otherC) > pairNorm_(s, c)) {
100
+ s = otherS;
101
+ c = otherC;
102
+ }
103
+ const length = pairNorm_(s, c);
104
+ if (length === 0) {
105
+ s = 1;
106
+ c = 0;
107
+ }
108
+ else {
109
+ s /= length;
110
+ c /= length;
111
+ }
112
+ values[offset] = scale * Math.sqrt(lambda);
113
+ values[offset + 1] = s;
114
+ values[offset + 2] = c;
115
+ }
116
+ /**
117
+ * A Householder QR decomposition with column pivoting, `A·P = Q·R`, reused
118
+ * across matrices of one shape: the rank-revealing factorisation behind least
119
+ * squares, weighted least squares (IRLS), regression covariances and
120
+ * leverages.
121
+ *
122
+ * Construct one per shape (`rows × columns`, any of the two larger), then call
123
+ * {@link decompose} as often as needed: every method after the constructor
124
+ * allocates nothing. The factors are LAPACK's (`xGEQP3`, Businger and Golub
125
+ * 1965): `R` upper trapezoidal with `|R₀₀| ≥ |R₁₁| ≥ …` in practice, `Q` held
126
+ * as `min(rows, columns)` reflectors, `P` the pivot order.
127
+ *
128
+ * **Rank.** The leading triangle `R₁₁` grows pivot by pivot while its
129
+ * reciprocal condition, estimated incrementally (Bischof's ICE, as LAPACK
130
+ * `xGELSY`), stays above `rankTolerance`; {@link rank} is its size and
131
+ * {@link pivots}`[0…rank)` the independent columns, the rest aliased.
132
+ * {@link reciprocalCondition} is that estimate of `σmin(R₁₁) / σmax(R₁₁)`, the
133
+ * reciprocal 2-norm condition of the independent columns of `√W·A`: an upper
134
+ * bound on the true value, usually within a factor of ten. A least-squares
135
+ * answer loses about `log₁₀(1 / reciprocalCondition²)` digits when the residual
136
+ * is large, `log₁₀(1 / reciprocalCondition)` when it is small.
137
+ *
138
+ * **Values.** A non-finite entry makes {@link decompose} return `false`: the
139
+ * rank is then `0`, the condition `NaN`, and every method writes `NaN`. Any
140
+ * finite entries and weights factorise: norms are scaled, and a matrix whose
141
+ * largest weighted entry lies outside `[2⁻⁵⁰⁰, 2⁵⁰⁰]` is first brought near `1`
142
+ * by a power of two (exact), its results scaled back — only entries below
143
+ * `2⁻¹⁰²²` times the largest lose digits, as negligible as they are, and
144
+ * results that are themselves out of range (a covariance of `1e−400`) underflow
145
+ * or overflow. Backward stable: the computed factors are exact for `A + E` with
146
+ * `‖E‖ ≤ c · rows · columns · ε · ‖A‖` (Higham, _Accuracy and Stability_, §19).
147
+ * {@link solve} brings `√W·b` near `1` the same way, so any finite right-hand
148
+ * side is solved.
149
+ *
150
+ * **Complexity.** {@link decompose}: O(rows · columns · min(rows, columns))
151
+ * time. {@link solve}: O(rows · min(rows, columns) + rank²), and once per
152
+ * decomposition O(rank² · (columns − rank)) for the first minimum-norm call.
153
+ * {@link covariance}: O(rank³), O(rank · columns²) for the minimum-norm one.
154
+ * {@link leverages}: O(rows · rank · min(rows, columns)). Memory: O(rows ·
155
+ * columns + columns²) numbers, allocated by the constructor.
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * // Fit y ≈ β₀ + β₁·t through (0, 1), (1, 3), (2, 5), (3, 7).
160
+ * const design = matrixOfRows([[1, 0], [1, 1], [1, 2], [1, 3]]);
161
+ * const qr = new QrDecomposition(4, 2);
162
+ * qr.decompose(design);
163
+ * const beta = qr.solve(new Float64Array(2), Float64Array.of(1, 3, 5, 7));
164
+ * // beta ≈ [1, 2], qr.rank === 2, qr.residualSumOfSquares ≈ 0
165
+ * ```;
166
+ */
167
+ export class QrDecomposition {
168
+ /** Rows of the matrices this decomposition takes. */
169
+ rows;
170
+ /** Columns of the matrices this decomposition takes. */
171
+ columns;
172
+ /**
173
+ * The incremental estimate of `σmin(R₁₁) / σmax(R₁₁)` for the independent
174
+ * columns of `√W·A` (see the class): `1` for one column, `0` at rank `0`,
175
+ * `NaN` after a non-finite matrix. Read-only for callers (a field, not a
176
+ * getter, so reading it never boxes a number).
177
+ */
178
+ reciprocalCondition = 0.5;
179
+ /**
180
+ * `Σ wᵢ (bᵢ − (A·x)ᵢ)²` at the last {@link solve}'s answer, from the part of
181
+ * `Qᵀ·√W·b` outside the span of `R₁₁`, so it costs nothing extra; `0` before
182
+ * any solve. For the minimum-norm answer it neglects the dropped `R₂₂`, whose
183
+ * size `rankTolerance` bounds. Read-only for callers.
184
+ */
185
+ residualSumOfSquares = 0.5;
186
+ reflectors_;
187
+ factors_;
188
+ tau_;
189
+ pivots_;
190
+ norms_;
191
+ sqrtWeights_;
192
+ work_;
193
+ vector_;
194
+ estimates_;
195
+ trapezoid_;
196
+ trapezoidTau_;
197
+ square_;
198
+ /**
199
+ * `[residual sum of squares, reciprocal condition, ICE scratch × 6, rank
200
+ * tolerance, covariance scale]`: numbers passed between methods through an
201
+ * array, as a double crossing a call the engine does not inline is boxed.
202
+ */
203
+ scalars_;
204
+ rank_ = 0;
205
+ /** `A'` = `2^scaleExponent_ · √W·A` is what `factors_` decomposes. */
206
+ scaleExponent_ = 0;
207
+ /** About `log₂ max √wᵢ`, `0` without weights: `solve` scales `√W·b` by it. */
208
+ weightExponent_ = 0;
209
+ valid_ = true;
210
+ weighted_ = false;
211
+ completed_ = false;
212
+ /**
213
+ * Allocates the factors and every working array; until the first
214
+ * {@link decompose}, the decomposition is that of the zero matrix.
215
+ *
216
+ * @throws {RangeError} When `rows` or `columns` is not a non-negative safe
217
+ * integer, or `rows · columns` or `columns²` is not a safe integer.
218
+ */
219
+ constructor(rows, columns) {
220
+ assertInteger(rows, "rows", 0);
221
+ assertInteger(columns, "columns", 0);
222
+ if (!Number.isSafeInteger(rows * columns) ||
223
+ !Number.isSafeInteger(columns * columns)) {
224
+ throw new RangeError(`QrDecomposition: ${rows} × ${columns} is too large to allocate`);
225
+ }
226
+ const reflectors = rows < columns ? rows : columns;
227
+ this.rows = rows;
228
+ this.columns = columns;
229
+ this.reflectors_ = reflectors;
230
+ this.factors_ = new Float64Array(rows * columns);
231
+ this.tau_ = new Float64Array(reflectors);
232
+ this.pivots_ = new Int32Array(columns);
233
+ this.norms_ = new Float64Array(2 * columns);
234
+ this.sqrtWeights_ = new Float64Array(rows);
235
+ this.work_ = new Float64Array(rows);
236
+ this.vector_ = new Float64Array(columns);
237
+ this.estimates_ = new Float64Array(2 * reflectors);
238
+ this.trapezoid_ = new Float64Array(reflectors * columns);
239
+ this.trapezoidTau_ = new Float64Array(reflectors);
240
+ this.square_ = new Float64Array(columns * columns);
241
+ this.scalars_ = new Float64Array(10);
242
+ for (let column = 0; column < columns; column++) {
243
+ this.pivots_[column] = column;
244
+ }
245
+ this.reciprocalCondition = 0;
246
+ this.residualSumOfSquares = 0;
247
+ }
248
+ /**
249
+ * The numerical rank: the size of the well-conditioned leading triangle
250
+ * `R₁₁`, at most `min(rows, columns)`; `0` for a zero or non-finite matrix.
251
+ */
252
+ get rank() {
253
+ return this.rank_;
254
+ }
255
+ /**
256
+ * The column order `P`: `pivots[k]` is the column of `A` in position `k` of
257
+ * `R`. The first {@link rank} are the independent columns, the others aliased.
258
+ * The array is the decomposition's own: read it, never write it.
259
+ */
260
+ get pivots() {
261
+ return this.pivots_;
262
+ }
263
+ /**
264
+ * Factorises `√W · matrix` (`matrix` itself without weights) and decides its
265
+ * rank. `matrix` is only read; the previous decomposition is replaced.
266
+ *
267
+ * @returns `false`, with rank `0` and `NaN` from every method, when an entry
268
+ * of `matrix` is not finite; `true` otherwise.
269
+ * @throws {RangeError} When `matrix` is not `rows × columns` or breaks the
270
+ * {@link Matrix} invariant, `weights` does not hold `rows` finite
271
+ * non-negative numbers, or `rankTolerance` is not in `[0, 1)`. Nothing is
272
+ * changed then.
273
+ */
274
+ decompose(matrix, options) {
275
+ assertMatrixShape_(matrix, "QrDecomposition.decompose");
276
+ const rows = this.rows;
277
+ const columns = this.columns;
278
+ if (matrix.rows !== rows || matrix.columns !== columns) {
279
+ throw new RangeError(`QrDecomposition.decompose: a ${rows} × ${columns} decomposition got a ${matrix.rows} × ${matrix.columns} matrix`);
280
+ }
281
+ const weights = options?.weights ?? null;
282
+ const scalars = this.scalars_;
283
+ // Read straight into the array, never through `?.` or a comparison with
284
+ // `undefined`, which box a number field: only a missing (or `NaN`)
285
+ // value takes the comparison.
286
+ scalars[TOLERANCE_SLOT_] =
287
+ options === undefined ? Number.NaN : Number(options.rankTolerance);
288
+ if (scalars[TOLERANCE_SLOT_] !== scalars[TOLERANCE_SLOT_] &&
289
+ options?.rankTolerance === undefined) {
290
+ scalars[TOLERANCE_SLOT_] =
291
+ (rows > columns ? rows : columns) * Number.EPSILON;
292
+ }
293
+ const rankTolerance = scalars[TOLERANCE_SLOT_];
294
+ if (!(rankTolerance >= 0 && rankTolerance < 1)) {
295
+ throw new RangeError(`QrDecomposition.decompose: rankTolerance must be in [0, 1), got ${describeValue(rankTolerance)}`);
296
+ }
297
+ if (weights !== null) {
298
+ if (weights.length !== rows) {
299
+ throw new RangeError(`QrDecomposition.decompose: weights needs ${rows} numbers, got ${weights.length}`);
300
+ }
301
+ for (let row = 0; row < rows; row++) {
302
+ const weight = weights[row];
303
+ if (!(weight >= 0 && weight < Number.POSITIVE_INFINITY)) {
304
+ throw new RangeError(`QrDecomposition.decompose: weights must be finite and non-negative, got ${describeValue(weight)} at ${row}`);
305
+ }
306
+ }
307
+ }
308
+ const factors = this.factors_;
309
+ const source = matrix.data;
310
+ const sqrtWeights = this.sqrtWeights_;
311
+ let largestEntry = 0;
312
+ let largestWeight = 0;
313
+ this.completed_ = false;
314
+ this.weighted_ = weights !== null;
315
+ this.residualSumOfSquares = 0;
316
+ for (let index = 0; index < factors.length; index++) {
317
+ const magnitude = Math.abs(source[index]);
318
+ if (!(magnitude <= largestEntry)) {
319
+ largestEntry = magnitude;
320
+ if (magnitude !== magnitude) {
321
+ break;
322
+ }
323
+ }
324
+ }
325
+ if (!(largestEntry < Number.POSITIVE_INFINITY)) {
326
+ this.valid_ = false;
327
+ this.rank_ = 0;
328
+ this.scaleExponent_ = 0;
329
+ this.reciprocalCondition = Number.NaN;
330
+ return false;
331
+ }
332
+ if (weights !== null) {
333
+ for (let row = 0; row < rows; row++) {
334
+ const root = Math.sqrt(weights[row]);
335
+ sqrtWeights[row] = root;
336
+ if (root > largestWeight) {
337
+ largestWeight = root;
338
+ }
339
+ }
340
+ }
341
+ // A product of the largest entry and weight outside [2⁻⁵⁰⁰, 2⁵⁰⁰] is
342
+ // brought to about [1, 4) by powers of two, exact but for entries
343
+ // negligible against the largest (LAPACK `xGELSY` scales the same way);
344
+ // the covariance and `R` would otherwise leave the range before the
345
+ // answer. `floor(log2)`, inlined, rather than a call taking a double
346
+ // (any nearby power of two serves), and `| 0` keeps every exponent a
347
+ // small integer, never a boxed double in a field.
348
+ const entryExponent = largestEntry === 0 ? 0 : Math.floor(Math.log2(largestEntry)) | 0;
349
+ const weightExponent = largestWeight === 0 ? 0 : Math.floor(Math.log2(largestWeight)) | 0;
350
+ const productExponent = entryExponent + weightExponent;
351
+ const scaled = productExponent < -500 || productExponent > 500;
352
+ const entryHalf = scaled ? (entryExponent >> 1) | 0 : 0;
353
+ const entryFactor = 2 ** -entryHalf;
354
+ const entryRest = 2 ** (scaled ? entryHalf - entryExponent : 0);
355
+ const weightFactor = 2 ** (scaled ? -weightExponent : 0);
356
+ this.scaleExponent_ = scaled ? -productExponent | 0 : 0;
357
+ this.weightExponent_ = weightExponent;
358
+ if (weights === null) {
359
+ for (let index = 0; index < factors.length; index++) {
360
+ factors[index] = source[index] * entryFactor * entryRest;
361
+ }
362
+ }
363
+ else {
364
+ for (let column = 0; column < columns; column++) {
365
+ const offset = rows * column;
366
+ for (let row = 0; row < rows; row++) {
367
+ factors[offset + row] =
368
+ source[offset + row] *
369
+ entryFactor *
370
+ entryRest *
371
+ (sqrtWeights[row] * weightFactor);
372
+ }
373
+ }
374
+ }
375
+ this.valid_ = true;
376
+ this.factorize_();
377
+ this.estimateRank_();
378
+ return true;
379
+ }
380
+ /**
381
+ * Solves the least-squares problem `min ‖√W·(b − A·x)‖` for the last
382
+ * decomposed `A`, and leaves its {@link residualSumOfSquares}.
383
+ *
384
+ * @param out - The solution `x`, `columns` numbers, in the columns' own
385
+ * order. May be `right` when the lengths agree.
386
+ * @param right - The right-hand side `b`, `rows` numbers (unweighted: the
387
+ * weights of {@link decompose} apply). Non-finite values propagate.
388
+ * @param solution - Which answer a rank-deficient matrix gives; see
389
+ * {@link QrSolution}. `"basic"` by default.
390
+ * @returns `out`; all `NaN` after a non-finite matrix.
391
+ * @throws {RangeError} When the lengths are wrong or `solution` is not a
392
+ * {@link QrSolution}.
393
+ */
394
+ solve(out, right, solution = "basic") {
395
+ const rows = this.rows;
396
+ const columns = this.columns;
397
+ if (out.length !== columns || right.length !== rows) {
398
+ throw new RangeError(`QrDecomposition.solve: out needs ${columns} numbers and right ${rows}, got ${out.length} and ${right.length}`);
399
+ }
400
+ const minimumNorm = solutionIsMinimumNorm_(solution, "solve");
401
+ if (!this.valid_) {
402
+ out.fill(Number.NaN);
403
+ this.residualSumOfSquares = Number.NaN;
404
+ return out;
405
+ }
406
+ const work = this.work_;
407
+ const sqrtWeights = this.sqrtWeights_;
408
+ const rank = this.rank_;
409
+ const weighted = this.weighted_;
410
+ let largestRight = 0;
411
+ for (let row = 0; row < rows; row++) {
412
+ const magnitude = Math.abs(right[row]);
413
+ if (magnitude > largestRight) {
414
+ largestRight = magnitude;
415
+ }
416
+ }
417
+ // √W·b brought near 1 by powers of two when it would leave [2⁻⁵⁰⁰, 2⁵⁰⁰],
418
+ // as `decompose` brings `√W·A`: reflecting subnormals loses digits.
419
+ const rightExponent = largestRight === 0 || largestRight === Number.POSITIVE_INFINITY
420
+ ? 0
421
+ : Math.floor(Math.log2(largestRight)) | 0;
422
+ const weightExponent = this.weightExponent_;
423
+ const productExponent = rightExponent + weightExponent;
424
+ const scaled = productExponent < -500 || productExponent > 500;
425
+ const rightHalf = scaled ? (rightExponent >> 1) | 0 : 0;
426
+ const rightFactor = 2 ** -rightHalf;
427
+ const rightRest = 2 ** (scaled ? rightHalf - rightExponent : 0);
428
+ const weightFactor = 2 ** (scaled ? -weightExponent : 0);
429
+ const rightShift = scaled ? -productExponent | 0 : 0;
430
+ for (let row = 0; row < rows; row++) {
431
+ const value = right[row] * rightFactor * rightRest;
432
+ work[row] = weighted ? value * (sqrtWeights[row] * weightFactor) : value;
433
+ }
434
+ this.reflectTranspose_(work);
435
+ let residual = 0;
436
+ for (let row = rank; row < rows; row++) {
437
+ const value = work[row];
438
+ residual += value * value;
439
+ }
440
+ this.scalars_[0] = residual;
441
+ if (rightShift !== 0) {
442
+ scaleByPowerOfTwoInPlace(this.scalars_, 0, -2 * rightShift);
443
+ }
444
+ this.residualSumOfSquares = this.scalars_[0];
445
+ const y = this.vector_;
446
+ y.fill(0);
447
+ for (let index = 0; index < rank; index++) {
448
+ y[index] = work[index];
449
+ }
450
+ if (minimumNorm && rank < columns) {
451
+ this.complete_();
452
+ backSubstitute_(this.trapezoid_, this.reflectors_, rank, y);
453
+ this.applyZTranspose_(y);
454
+ }
455
+ else {
456
+ backSubstitute_(this.factors_, rows, rank, y);
457
+ }
458
+ const pivots = this.pivots_;
459
+ const shift = this.scaleExponent_ - rightShift;
460
+ for (let index = 0; index < columns; index++) {
461
+ out[pivots[index]] = y[index];
462
+ }
463
+ if (shift !== 0) {
464
+ for (let index = 0; index < columns; index++) {
465
+ scaleByPowerOfTwoInPlace(out, index, shift);
466
+ }
467
+ }
468
+ return out;
469
+ }
470
+ /**
471
+ * Writes `scale · (AᵀWA)⁻¹` for the independent columns into `out` (`columns
472
+ * × columns`, the columns' own order): the covariance of the least-squares
473
+ * coefficients. `"basic"`: `scale · P·(R₁₁ᵀR₁₁)⁻¹·Pᵀ` on the independent
474
+ * columns and `NaN` on every row and column of an aliased one (their
475
+ * coefficient is not estimable). `"minimum-norm"`: `scale · (AᵀWA)⁺`, the
476
+ * pseudo-inverse of the rank-`rank` truncation, defined everywhere. They
477
+ * agree at full rank.
478
+ *
479
+ * @returns `out`; all `NaN` after a non-finite matrix.
480
+ * @throws {RangeError} When `out` is not `columns × columns` or breaks the
481
+ * {@link Matrix} invariant, `scale` is not finite and non-negative, or
482
+ * `solution` is not a {@link QrSolution}.
483
+ */
484
+ covariance(out, options) {
485
+ assertMatrixShape_(out, "QrDecomposition.covariance");
486
+ const columns = this.columns;
487
+ if (out.rows !== columns || out.columns !== columns) {
488
+ throw new RangeError(`QrDecomposition.covariance: out must be ${columns} × ${columns}, got ${out.rows} × ${out.columns}`);
489
+ }
490
+ const scalars = this.scalars_;
491
+ scalars[SCALE_SLOT_] =
492
+ options === undefined ? Number.NaN : Number(options.scale);
493
+ if (scalars[SCALE_SLOT_] !== scalars[SCALE_SLOT_] &&
494
+ options?.scale === undefined) {
495
+ scalars[SCALE_SLOT_] = 1;
496
+ }
497
+ const scale = scalars[SCALE_SLOT_];
498
+ if (!(scale >= 0 && scale < Number.POSITIVE_INFINITY)) {
499
+ throw new RangeError(`QrDecomposition.covariance: scale must be finite and non-negative, got ${describeValue(scale)}`);
500
+ }
501
+ const minimumNorm = solutionIsMinimumNorm_(options?.solution ?? "basic", "covariance");
502
+ const target = out.data;
503
+ if (!this.valid_) {
504
+ target.fill(Number.NaN);
505
+ return out;
506
+ }
507
+ const rank = this.rank_;
508
+ const square = this.square_;
509
+ const full = !minimumNorm || rank === columns;
510
+ square.fill(0);
511
+ if (full) {
512
+ invertTriangle_(this.factors_, this.rows, rank, square, columns);
513
+ }
514
+ else {
515
+ this.complete_();
516
+ invertTriangle_(this.trapezoid_, this.reflectors_, rank, square, columns);
517
+ }
518
+ multiplyByTranspose_(square, columns, rank);
519
+ if (!full) {
520
+ this.conjugateByZ_();
521
+ }
522
+ const pivots = this.pivots_;
523
+ const shift = 2 * this.scaleExponent_;
524
+ for (let b = 0; b < columns; b++) {
525
+ const column = columns * pivots[b];
526
+ for (let a = 0; a < columns; a++) {
527
+ const index = column + pivots[a];
528
+ target[index] =
529
+ full && (a >= rank || b >= rank)
530
+ ? Number.NaN
531
+ : scale * square[columns * b + a];
532
+ if (shift !== 0) {
533
+ scaleByPowerOfTwoInPlace(target, index, shift);
534
+ }
535
+ }
536
+ }
537
+ return out;
538
+ }
539
+ /**
540
+ * Writes the leverages — the diagonal of the hat matrix
541
+ * `√W·A·(AᵀWA)⁻¹·AᵀW·√W` on the independent columns, `hᵢ = Σₖ₍ₖ₌₀…ᵣₐₙₖ₋₁₎
542
+ * Q[i, k]²` — into `out` (`rows` numbers), each in `[0, 1]` and summing to
543
+ * the rank; `0` for a row of weight zero. The input of studentised residuals,
544
+ * Cook's distance and robust-regression weight adjustments.
545
+ *
546
+ * @returns `out`; all `NaN` after a non-finite matrix.
547
+ * @throws {RangeError} When `out` does not hold `rows` numbers.
548
+ */
549
+ leverages(out) {
550
+ const rows = this.rows;
551
+ if (out.length !== rows) {
552
+ throw new RangeError(`QrDecomposition.leverages: out needs ${rows} numbers, got ${out.length}`);
553
+ }
554
+ if (!this.valid_) {
555
+ out.fill(Number.NaN);
556
+ return out;
557
+ }
558
+ const work = this.work_;
559
+ out.fill(0);
560
+ for (let column = 0; column < this.rank_; column++) {
561
+ this.basisColumn_(column);
562
+ for (let row = 0; row < rows; row++) {
563
+ const value = work[row];
564
+ out[row] = out[row] + value * value;
565
+ }
566
+ }
567
+ return out;
568
+ }
569
+ /**
570
+ * Writes `Qᵀ · vector` into `out` (`rows` numbers each; `out` may be
571
+ * `vector`). `Q` is the full orthogonal factor of `√W·A`: weight `vector`
572
+ * first to stay in the weighted problem.
573
+ *
574
+ * @returns `out`; all `NaN` after a non-finite matrix.
575
+ * @throws {RangeError} When a length is not `rows`.
576
+ */
577
+ applyQTranspose(out, vector) {
578
+ this.prepareReflection_(out, vector, "applyQTranspose");
579
+ if (this.valid_) {
580
+ this.reflectTranspose_(out);
581
+ }
582
+ return out;
583
+ }
584
+ /**
585
+ * Writes `Q · vector` into `out` (`rows` numbers each; `out` may be
586
+ * `vector`), the inverse of {@link applyQTranspose}.
587
+ *
588
+ * @returns `out`; all `NaN` after a non-finite matrix.
589
+ * @throws {RangeError} When a length is not `rows`.
590
+ */
591
+ applyQ(out, vector) {
592
+ this.prepareReflection_(out, vector, "applyQ");
593
+ if (this.valid_) {
594
+ this.reflect_(out, this.reflectors_ - 1);
595
+ }
596
+ return out;
597
+ }
598
+ /**
599
+ * Writes the thin orthogonal factor — the first `min(rows, columns)` columns
600
+ * of `Q` — into `out` (`rows × min(rows, columns)`).
601
+ *
602
+ * @returns `out`; all `NaN` after a non-finite matrix.
603
+ * @throws {RangeError} When `out` has the wrong shape or breaks the
604
+ * {@link Matrix} invariant.
605
+ */
606
+ q(out) {
607
+ assertMatrixShape_(out, "QrDecomposition.q");
608
+ const rows = this.rows;
609
+ const reflectors = this.reflectors_;
610
+ if (out.rows !== rows || out.columns !== reflectors) {
611
+ throw new RangeError(`QrDecomposition.q: out must be ${rows} × ${reflectors}, got ${out.rows} × ${out.columns}`);
612
+ }
613
+ const target = out.data;
614
+ if (!this.valid_) {
615
+ target.fill(Number.NaN);
616
+ return out;
617
+ }
618
+ for (let column = 0; column < reflectors; column++) {
619
+ this.basisColumn_(column);
620
+ target.set(this.work_, rows * column);
621
+ }
622
+ return out;
623
+ }
624
+ /**
625
+ * Writes the triangular factor `R` (`min(rows, columns) × columns`, upper
626
+ * trapezoidal, columns in pivot order) into `out`, zeros below the diagonal.
627
+ *
628
+ * @returns `out`; all `NaN` after a non-finite matrix.
629
+ * @throws {RangeError} When `out` has the wrong shape or breaks the
630
+ * {@link Matrix} invariant.
631
+ */
632
+ r(out) {
633
+ assertMatrixShape_(out, "QrDecomposition.r");
634
+ const rows = this.rows;
635
+ const columns = this.columns;
636
+ const reflectors = this.reflectors_;
637
+ if (out.rows !== reflectors || out.columns !== columns) {
638
+ throw new RangeError(`QrDecomposition.r: out must be ${reflectors} × ${columns}, got ${out.rows} × ${out.columns}`);
639
+ }
640
+ const target = out.data;
641
+ if (!this.valid_) {
642
+ target.fill(Number.NaN);
643
+ return out;
644
+ }
645
+ const factors = this.factors_;
646
+ const shift = -this.scaleExponent_;
647
+ for (let column = 0; column < columns; column++) {
648
+ for (let row = 0; row < reflectors; row++) {
649
+ const index = reflectors * column + row;
650
+ target[index] = row <= column ? factors[rows * column + row] : 0;
651
+ if (shift !== 0) {
652
+ scaleByPowerOfTwoInPlace(target, index, shift);
653
+ }
654
+ }
655
+ }
656
+ return out;
657
+ }
658
+ prepareReflection_(out, vector, name) {
659
+ const rows = this.rows;
660
+ if (out.length !== rows || vector.length !== rows) {
661
+ throw new RangeError(`QrDecomposition.${name}: out and vector need ${rows} numbers, got ${out.length} and ${vector.length}`);
662
+ }
663
+ if (!this.valid_) {
664
+ out.fill(Number.NaN);
665
+ }
666
+ else if (out !== vector) {
667
+ out.set(vector);
668
+ }
669
+ }
670
+ /** `xGEQP3`'s unblocked loop (`xLAQP2`) over `factors_`. */
671
+ factorize_() {
672
+ const rows = this.rows;
673
+ const columns = this.columns;
674
+ const reflectors = this.reflectors_;
675
+ const factors = this.factors_;
676
+ const pivots = this.pivots_;
677
+ const norms = this.norms_;
678
+ const tau = this.tau_;
679
+ for (let column = 0; column < columns; column++) {
680
+ euclideanNorm_(norms, column, factors, rows * column, rows, 1);
681
+ pivots[column] = column;
682
+ norms[columns + column] = norms[column];
683
+ }
684
+ for (let step = 0; step < reflectors; step++) {
685
+ let pivot = step;
686
+ let largest = norms[step];
687
+ for (let column = step + 1; column < columns; column++) {
688
+ if (norms[column] > largest) {
689
+ largest = norms[column];
690
+ pivot = column;
691
+ }
692
+ }
693
+ if (pivot !== step) {
694
+ this.swapColumns_(step, pivot);
695
+ }
696
+ const offset = rows * step;
697
+ const diagonal = offset + step;
698
+ householder_(factors, diagonal, diagonal + 1, rows - step - 1, 1, tau, step);
699
+ const t = tau[step];
700
+ if (t !== 0) {
701
+ for (let column = step + 1; column < columns; column++) {
702
+ const target = rows * column;
703
+ let dot = factors[target + step];
704
+ for (let row = step + 1; row < rows; row++) {
705
+ dot += factors[offset + row] * factors[target + row];
706
+ }
707
+ const factor = t * dot;
708
+ factors[target + step] = factors[target + step] - factor;
709
+ for (let row = step + 1; row < rows; row++) {
710
+ factors[target + row] =
711
+ factors[target + row] - factor * factors[offset + row];
712
+ }
713
+ }
714
+ }
715
+ for (let column = step + 1; column < columns; column++) {
716
+ const partial = norms[column];
717
+ if (partial === 0) {
718
+ continue;
719
+ }
720
+ const ratio = Math.abs(factors[rows * column + step]) / partial;
721
+ let remaining = 1 - ratio * ratio;
722
+ if (remaining < 0) {
723
+ remaining = 0;
724
+ }
725
+ const drift = partial / norms[columns + column];
726
+ if (remaining * drift * drift <= DOWNDATE_LIMIT_) {
727
+ if (step + 1 < rows) {
728
+ euclideanNorm_(norms, column, factors, rows * column + step + 1, rows - step - 1, 1);
729
+ }
730
+ else {
731
+ norms[column] = 0;
732
+ }
733
+ norms[columns + column] = norms[column];
734
+ }
735
+ else {
736
+ norms[column] = partial * Math.sqrt(remaining);
737
+ }
738
+ }
739
+ }
740
+ }
741
+ /**
742
+ * Swaps columns `step` and `pivot` of `factors_`, with their pivots and
743
+ * norms.
744
+ */
745
+ swapColumns_(step, pivot) {
746
+ const rows = this.rows;
747
+ const columns = this.columns;
748
+ const factors = this.factors_;
749
+ const pivots = this.pivots_;
750
+ const norms = this.norms_;
751
+ const from = rows * pivot;
752
+ const to = rows * step;
753
+ for (let row = 0; row < rows; row++) {
754
+ const value = factors[from + row];
755
+ factors[from + row] = factors[to + row];
756
+ factors[to + row] = value;
757
+ }
758
+ const index = pivots[pivot];
759
+ pivots[pivot] = pivots[step];
760
+ pivots[step] = index;
761
+ norms[pivot] = norms[step];
762
+ norms[columns + pivot] = norms[columns + step];
763
+ }
764
+ /** Incremental condition estimation over the pivoted diagonal (`xGELSY`). */
765
+ estimateRank_() {
766
+ const rows = this.rows;
767
+ const reflectors = this.reflectors_;
768
+ const factors = this.factors_;
769
+ const scalars = this.scalars_;
770
+ const tolerance = scalars[TOLERANCE_SLOT_];
771
+ this.rank_ = 0;
772
+ if (reflectors === 0 || factors[0] === 0) {
773
+ this.reciprocalCondition = 0;
774
+ return;
775
+ }
776
+ const estimates = this.estimates_;
777
+ let smallest = Math.abs(factors[0]);
778
+ let largest = smallest;
779
+ let rank = 1;
780
+ estimates[0] = 1;
781
+ estimates[reflectors] = 1;
782
+ while (rank < reflectors) {
783
+ const offset = rows * rank;
784
+ const gamma = factors[offset + rank];
785
+ let alphaSmallest = 0;
786
+ let alphaLargest = 0;
787
+ for (let row = 0; row < rank; row++) {
788
+ const value = factors[offset + row];
789
+ alphaSmallest += estimates[row] * value;
790
+ alphaLargest += estimates[reflectors + row] * value;
791
+ }
792
+ scalars[2] = smallest;
793
+ scalars[3] = alphaSmallest;
794
+ scalars[4] = gamma;
795
+ incrementalEstimate_(scalars, 2, false);
796
+ scalars[5] = largest;
797
+ scalars[6] = alphaLargest;
798
+ scalars[7] = gamma;
799
+ incrementalEstimate_(scalars, 5, true);
800
+ const nextSmallest = scalars[2];
801
+ const nextLargest = scalars[5];
802
+ if (!(nextSmallest > tolerance * nextLargest)) {
803
+ break;
804
+ }
805
+ const sineSmallest = scalars[3];
806
+ const sineLargest = scalars[6];
807
+ for (let row = 0; row < rank; row++) {
808
+ estimates[row] = estimates[row] * sineSmallest;
809
+ estimates[reflectors + row] =
810
+ estimates[reflectors + row] * sineLargest;
811
+ }
812
+ estimates[rank] = scalars[4];
813
+ estimates[reflectors + rank] = scalars[7];
814
+ smallest = nextSmallest;
815
+ largest = nextLargest;
816
+ rank++;
817
+ }
818
+ this.rank_ = rank;
819
+ this.reciprocalCondition = smallest / largest;
820
+ }
821
+ /** `vector ← Qᵀ·vector`: the reflectors `H₀, H₁, …` in turn. */
822
+ reflectTranspose_(vector) {
823
+ const rows = this.rows;
824
+ const factors = this.factors_;
825
+ const tau = this.tau_;
826
+ for (let step = 0; step < this.reflectors_; step++) {
827
+ const t = tau[step];
828
+ if (t === 0) {
829
+ continue;
830
+ }
831
+ const offset = rows * step;
832
+ let dot = vector[step];
833
+ for (let row = step + 1; row < rows; row++) {
834
+ dot += factors[offset + row] * vector[row];
835
+ }
836
+ const factor = t * dot;
837
+ vector[step] = vector[step] - factor;
838
+ for (let row = step + 1; row < rows; row++) {
839
+ vector[row] = vector[row] - factor * factors[offset + row];
840
+ }
841
+ }
842
+ }
843
+ /** `vector ← H₀·H₁·…·H_last·vector`. */
844
+ reflect_(vector, last) {
845
+ const rows = this.rows;
846
+ const factors = this.factors_;
847
+ const tau = this.tau_;
848
+ for (let step = last; step >= 0; step--) {
849
+ const t = tau[step];
850
+ if (t === 0) {
851
+ continue;
852
+ }
853
+ const offset = rows * step;
854
+ let dot = vector[step];
855
+ for (let row = step + 1; row < rows; row++) {
856
+ dot += factors[offset + row] * vector[row];
857
+ }
858
+ const factor = t * dot;
859
+ vector[step] = vector[step] - factor;
860
+ for (let row = step + 1; row < rows; row++) {
861
+ vector[row] = vector[row] - factor * factors[offset + row];
862
+ }
863
+ }
864
+ }
865
+ /**
866
+ * Column `column` of `Q` into `work_`: `Q·e_column`, where only the
867
+ * reflectors up to `column` act (the later ones are zero above their row).
868
+ */
869
+ basisColumn_(column) {
870
+ const work = this.work_;
871
+ work.fill(0);
872
+ work[column] = 1;
873
+ this.reflect_(work, column);
874
+ }
875
+ /**
876
+ * The complete orthogonal decomposition `[R₁₁ R₁₂] = [T 0]·Z` of the leading
877
+ * `rank` rows (LAPACK `xTZRZF`), once per decomposition: `Z = G₀·G₁·…`, `Gᵢ`
878
+ * reflecting entry `i` against entries `rank…columns − 1` of row `i`.
879
+ */
880
+ complete_() {
881
+ if (this.completed_) {
882
+ return;
883
+ }
884
+ this.completed_ = true;
885
+ const rows = this.rows;
886
+ const columns = this.columns;
887
+ const lead = this.reflectors_;
888
+ const rank = this.rank_;
889
+ const factors = this.factors_;
890
+ const trapezoid = this.trapezoid_;
891
+ const tau = this.trapezoidTau_;
892
+ const tail = columns - rank;
893
+ for (let column = 0; column < columns; column++) {
894
+ for (let row = 0; row < rank; row++) {
895
+ trapezoid[lead * column + row] =
896
+ row <= column ? factors[rows * column + row] : 0;
897
+ }
898
+ }
899
+ for (let row = rank - 1; row >= 0; row--) {
900
+ const tailStart = lead * rank + row;
901
+ householder_(trapezoid, lead * row + row, tailStart, tail, lead, tau, row);
902
+ const t = tau[row];
903
+ if (t === 0) {
904
+ continue;
905
+ }
906
+ for (let above = 0; above < row; above++) {
907
+ const aboveTail = lead * rank + above;
908
+ let dot = trapezoid[lead * row + above];
909
+ for (let step = 0; step < tail; step++) {
910
+ dot +=
911
+ trapezoid[aboveTail + lead * step] *
912
+ trapezoid[tailStart + lead * step];
913
+ }
914
+ const factor = t * dot;
915
+ trapezoid[lead * row + above] = trapezoid[lead * row + above] - factor;
916
+ for (let step = 0; step < tail; step++) {
917
+ trapezoid[aboveTail + lead * step] =
918
+ trapezoid[aboveTail + lead * step] -
919
+ factor * trapezoid[tailStart + lead * step];
920
+ }
921
+ }
922
+ }
923
+ }
924
+ /** `y ← Zᵀ·y = G_{rank−1}·…·G₀·y` (each `Gᵢ` symmetric). */
925
+ applyZTranspose_(y) {
926
+ const lead = this.reflectors_;
927
+ const rank = this.rank_;
928
+ const tail = this.columns - rank;
929
+ const trapezoid = this.trapezoid_;
930
+ const tau = this.trapezoidTau_;
931
+ for (let row = 0; row < rank; row++) {
932
+ const t = tau[row];
933
+ if (t === 0) {
934
+ continue;
935
+ }
936
+ const tailStart = lead * rank + row;
937
+ let dot = y[row];
938
+ for (let step = 0; step < tail; step++) {
939
+ dot += trapezoid[tailStart + lead * step] * y[rank + step];
940
+ }
941
+ const factor = t * dot;
942
+ y[row] = y[row] - factor;
943
+ for (let step = 0; step < tail; step++) {
944
+ y[rank + step] =
945
+ y[rank + step] - factor * trapezoid[tailStart + lead * step];
946
+ }
947
+ }
948
+ }
949
+ /**
950
+ * `square_ ← Zᵀ·square_·Z`, the symmetric `columns × columns` matrix
951
+ * conjugated by each `Gᵢ` in turn: with `p = τ·M·u` and `w = p −
952
+ * (τ/2)(uᵀp)·u`, `G·M·G = M − w·uᵀ − u·wᵀ` (LAPACK `xSYR2` form). `u` is `1`
953
+ * at `i` and the reflector's tail at `rank…columns − 1`.
954
+ */
955
+ conjugateByZ_() {
956
+ const columns = this.columns;
957
+ const lead = this.reflectors_;
958
+ const rank = this.rank_;
959
+ const tail = columns - rank;
960
+ const trapezoid = this.trapezoid_;
961
+ const tau = this.trapezoidTau_;
962
+ const square = this.square_;
963
+ const p = this.vector_;
964
+ for (let row = 0; row < rank; row++) {
965
+ const t = tau[row];
966
+ if (t === 0) {
967
+ continue;
968
+ }
969
+ const tailStart = lead * rank + row;
970
+ for (let index = 0; index < columns; index++) {
971
+ let sum = square[columns * row + index];
972
+ for (let step = 0; step < tail; step++) {
973
+ sum +=
974
+ square[columns * (rank + step) + index] *
975
+ trapezoid[tailStart + lead * step];
976
+ }
977
+ p[index] = t * sum;
978
+ }
979
+ let projection = p[row];
980
+ for (let step = 0; step < tail; step++) {
981
+ projection += p[rank + step] * trapezoid[tailStart + lead * step];
982
+ }
983
+ const half = (t / 2) * projection;
984
+ p[row] = p[row] - half;
985
+ for (let step = 0; step < tail; step++) {
986
+ p[rank + step] =
987
+ p[rank + step] - half * trapezoid[tailStart + lead * step];
988
+ }
989
+ // M ← M − p·uᵀ − u·pᵀ, u nonzero at `row` and the tail only.
990
+ for (let index = 0; index < columns; index++) {
991
+ const value = p[index];
992
+ square[columns * row + index] = square[columns * row + index] - value;
993
+ square[columns * index + row] = square[columns * index + row] - value;
994
+ for (let step = 0; step < tail; step++) {
995
+ const u = trapezoid[tailStart + lead * step];
996
+ const column = rank + step;
997
+ square[columns * column + index] =
998
+ square[columns * column + index] - value * u;
999
+ square[columns * index + column] =
1000
+ square[columns * index + column] - value * u;
1001
+ }
1002
+ }
1003
+ }
1004
+ }
1005
+ }
1006
+ function solutionIsMinimumNorm_(solution, name) {
1007
+ if (solution === "minimum-norm") {
1008
+ return true;
1009
+ }
1010
+ if (solution !== "basic") {
1011
+ throw new RangeError(`QrDecomposition.${name}: solution must be "basic" or "minimum-norm", got ${describeValue(solution)}`);
1012
+ }
1013
+ return false;
1014
+ }
1015
+ /**
1016
+ * `y[0…size) ← U⁻¹·y[0…size)` for the upper triangle `U` of `data` (leading
1017
+ * dimension `lead`), column by column.
1018
+ */
1019
+ function backSubstitute_(data, lead, size, y) {
1020
+ for (let column = size - 1; column >= 0; column--) {
1021
+ const offset = lead * column;
1022
+ const value = y[column] / data[offset + column];
1023
+ y[column] = value;
1024
+ for (let row = 0; row < column; row++) {
1025
+ y[row] = y[row] - data[offset + row] * value;
1026
+ }
1027
+ }
1028
+ }
1029
+ /**
1030
+ * The inverse of the upper triangle `U` of order `size` in `data` (leading
1031
+ * dimension `lead`) into the upper triangle of `out` (leading dimension
1032
+ * `outLead`), column by column: `X[j][j] = 1 / U[j][j]` and, upwards, `X[i][j]
1033
+ * = −(Σₗ₌ᵢ₊₁…ⱼ U[i][l]·X[l][j]) / U[i][i]` (LAPACK `xTRTI2`).
1034
+ */
1035
+ function invertTriangle_(data, lead, size, out, outLead) {
1036
+ for (let column = 0; column < size; column++) {
1037
+ const target = outLead * column;
1038
+ out[target + column] = 1 / data[lead * column + column];
1039
+ for (let row = column - 1; row >= 0; row--) {
1040
+ let sum = 0;
1041
+ for (let inner = row + 1; inner <= column; inner++) {
1042
+ sum += data[lead * inner + row] * out[target + inner];
1043
+ }
1044
+ out[target + row] = -sum / data[lead * row + row];
1045
+ }
1046
+ }
1047
+ }
1048
+ /**
1049
+ * `X ← X·Xᵀ` in place for the upper triangle `X` of order `size` in `data`
1050
+ * (leading dimension `lead`), the result symmetric over the whole `size × size`
1051
+ * block (LAPACK `xLAUUM`). Entry `(a, b)`, `a ≤ b`, needs rows `a` and `b` from
1052
+ * column `b` on, so rows in ascending order and columns ascending within each
1053
+ * overwrite nothing still needed.
1054
+ */
1055
+ function multiplyByTranspose_(data, lead, size) {
1056
+ for (let a = 0; a < size; a++) {
1057
+ for (let b = a; b < size; b++) {
1058
+ let sum = 0;
1059
+ for (let inner = b; inner < size; inner++) {
1060
+ sum += data[lead * inner + a] * data[lead * inner + b];
1061
+ }
1062
+ data[lead * b + a] = sum;
1063
+ }
1064
+ }
1065
+ for (let b = 0; b < size; b++) {
1066
+ for (let a = b + 1; a < size; a++) {
1067
+ data[lead * b + a] = data[lead * a + b];
1068
+ }
1069
+ }
1070
+ }
1071
+ //# sourceMappingURL=qr-decomposition.js.map