@numero-uno-jpn/rstats 0.13.0 → 0.14.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/CHANGELOG.md +20 -0
- package/README.ja.md +17 -8
- package/README.md +17 -8
- package/dist/chunks/{chunk-CQNVEA22.js → chunk-6JRESWVF.js} +2 -2
- package/dist/chunks/chunk-7CPM3M6Q.js +2 -0
- package/dist/chunks/chunk-7PSGKKOP.js +2 -0
- package/dist/chunks/{chunk-4AQNVF3Z.js → chunk-7T74KLE5.js} +2 -2
- package/dist/chunks/{chunk-F44XUHWI.js → chunk-A76XBA3D.js} +1 -1
- package/dist/chunks/{chunk-VG67L3JA.js → chunk-ACE64PMM.js} +2 -2
- package/dist/chunks/chunk-DCGBYO44.js +2 -0
- package/dist/chunks/chunk-DWNGNTS6.js +2 -0
- package/dist/chunks/{chunk-SVWU5T7C.js → chunk-FBDZ6B2G.js} +2 -2
- package/dist/chunks/chunk-IBJ7RI44.js +2 -0
- package/dist/chunks/{chunk-4GNJEYXR.js → chunk-IGSR4GIF.js} +2 -2
- package/dist/chunks/{chunk-BJHBYEEU.js → chunk-NTETWLP3.js} +1 -1
- package/dist/chunks/{chunk-2IAT6MT2.js → chunk-Q4JF4QHS.js} +2 -2
- package/dist/chunks/{chunk-JGFUZKLJ.js → chunk-RZIWVCHO.js} +2 -2
- package/dist/chunks/chunk-SD7ML5PE.js +2 -0
- package/dist/chunks/{chunk-3AKA4KEL.js → chunk-SZ357HRC.js} +1 -1
- package/dist/chunks/{chunk-SLSDFIW2.js → chunk-WM33ADZV.js} +2 -2
- package/dist/chunks/{chunk-MEMYFTYS.js → chunk-XCAMWVNO.js} +1 -1
- package/dist/chunks/chunk-YQLEXH2Y.js +3 -0
- package/dist/chunks/chunk-YTV3RFCA.js +2 -0
- package/dist/chunks/{chunk-BSOUJPDF.js → chunk-ZUESNU7W.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/mixed.d.ts +3 -1
- package/dist/entries/mixed.js +4 -1
- package/dist/internal/fround.d.ts +12 -0
- package/dist/internal/fround.js +89 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -3
- package/dist/models/lmer.d.ts +37 -4
- package/dist/models/lmer.js +18 -1
- package/dist/models/lmerAnova.d.ts +138 -0
- package/dist/models/lmerAnova.js +134 -0
- package/dist/models/lmerHypotheses.d.ts +105 -0
- package/dist/models/lmerHypotheses.js +303 -0
- package/dist/models/lmerTest.d.ts +233 -0
- package/dist/models/lmerTest.js +306 -0
- package/dist/models/mixedDerivatives.d.ts +27 -0
- package/dist/models/mixedDerivatives.js +342 -0
- package/dist/models/mixedDeviance.d.ts +112 -0
- package/dist/models/mixedDeviance.js +216 -86
- package/dist/models/mixedStructure.d.ts +5 -3
- package/dist/models/modelMatrix.d.ts +10 -3
- package/dist/models/modelMatrix.js +23 -2
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +13 -13
- package/dist/special.js +2 -2
- package/dist/tests.js +11 -12
- package/llms.txt +6 -1
- package/package.json +1 -1
- package/dist/chunks/chunk-22SXZNR6.js +0 -2
- package/dist/chunks/chunk-AGRKZXLG.js +0 -2
- package/dist/chunks/chunk-N3FV6H3C.js +0 -2
- package/dist/chunks/chunk-NRV3BH7I.js +0 -2
- package/dist/chunks/chunk-RTWLZPPG.js +0 -2
- package/dist/chunks/chunk-VWGJYRE6.js +0 -2
|
@@ -31,6 +31,63 @@ export interface ProfiledDevianceOptions {
|
|
|
31
31
|
/** Also (R_X' R_X)⁻¹. */
|
|
32
32
|
rxInverse?: boolean;
|
|
33
33
|
}
|
|
34
|
+
/** What does not depend on θ: the cross-products, Z by rows, the groups of columns and the pattern of the factor */
|
|
35
|
+
export interface SparseSystem {
|
|
36
|
+
n: number;
|
|
37
|
+
p: number;
|
|
38
|
+
q: number;
|
|
39
|
+
/** Number of groups of columns (one per level of each term) */
|
|
40
|
+
nGroups: number;
|
|
41
|
+
/** First column of each group, and q at the end (nGroups + 1) */
|
|
42
|
+
groupStart: Int32Array;
|
|
43
|
+
/** The term of each group */
|
|
44
|
+
groupTerm: Int32Array;
|
|
45
|
+
/** For each term: nc, and the index into θ of each element of T_k (nc × nc, column-major; −1 above the diagonal) */
|
|
46
|
+
termNc: number[];
|
|
47
|
+
termTheta: Int32Array[];
|
|
48
|
+
/**
|
|
49
|
+
* Z'Z by blocks, lower part: the blocks of column group h are blockStart[h] .. blockStart[h + 1] − 1, the diagonal
|
|
50
|
+
* block first, then the row groups blockRow[b] > h increasing; block b is nc(row group) × nc(h), column-major, at
|
|
51
|
+
* zz[blockValueStart[b]] (the diagonal block in full)
|
|
52
|
+
*/
|
|
53
|
+
blockStart: Int32Array;
|
|
54
|
+
blockRow: Int32Array;
|
|
55
|
+
blockValueStart: Int32Array;
|
|
56
|
+
zz: Float64Array;
|
|
57
|
+
/** Z'X, q × p, column-major */
|
|
58
|
+
zx: Float64Array;
|
|
59
|
+
/** Z'y */
|
|
60
|
+
zy: Float64Array;
|
|
61
|
+
/** X'y */
|
|
62
|
+
xy: Float64Array;
|
|
63
|
+
/** The nonzero entries of Z by rows: the columns and the values of row i are at rowStart[i] .. rowStart[i + 1] − 1 */
|
|
64
|
+
rowStart: Int32Array;
|
|
65
|
+
rowCols: Int32Array;
|
|
66
|
+
rowValues: Float64Array;
|
|
67
|
+
/** The pattern of L by columns: the rows of column j at colStart[j] .. colStart[j + 1] − 1, the diagonal first */
|
|
68
|
+
colStart: Int32Array;
|
|
69
|
+
colRows: Int32Array;
|
|
70
|
+
/** The entries L[j, k], k < j, of row j: their columns k (increasing) and positions in colRows, at rowListStart[j] .. */
|
|
71
|
+
rowListStart: Int32Array;
|
|
72
|
+
rowListCol: Int32Array;
|
|
73
|
+
rowListPos: Int32Array;
|
|
74
|
+
/**
|
|
75
|
+
* For each block b of Z'Z off the diagonal (row group g, column group h): the number of rows of L's column groups
|
|
76
|
+
* before g in the pattern of h, so that the entry (row r of g, column c of h) of L (and of the selected inverse) is
|
|
77
|
+
* at colStart[column] + (rows of the diagonal block from the column) + blockPatternOffset[b] + r (0 on the diagonal)
|
|
78
|
+
*/
|
|
79
|
+
blockPatternOffset: Int32Array;
|
|
80
|
+
}
|
|
81
|
+
/** Λ_θ w (q-vector) */
|
|
82
|
+
export declare function lambdaTimes(sys: SparseSystem, t: Float64Array[], w: Float64Array): Float64Array;
|
|
83
|
+
/** Λ_θ' M for a q × ncol column-major M */
|
|
84
|
+
export declare function lambdaTransposeTimes(sys: SparseSystem, t: Float64Array[], m: Float64Array, ncol?: number): Float64Array;
|
|
85
|
+
/** Solves L x = v in place (v of length q, at an offset) */
|
|
86
|
+
export declare function solveL(sys: SparseSystem, l: Float64Array, v: Float64Array, offset?: number): void;
|
|
87
|
+
/** Solves L' x = v in place */
|
|
88
|
+
export declare function solveLt(sys: SparseSystem, l: Float64Array, v: Float64Array, offset?: number): void;
|
|
89
|
+
/** The full symmetric inverse of R'R from an upper-triangular factor R (column-major, k × k; R is not changed) */
|
|
90
|
+
export declare function inverseFromFactor(r: Float64Array, k: number): Float64Array;
|
|
34
91
|
/**
|
|
35
92
|
* The profiled deviance of a linear mixed model at `theta`, with the penalised least-squares solution
|
|
36
93
|
* (oracle/lmer-behaviour.md, stage 1b; computed sparsely). Internal: not exported from the package.
|
|
@@ -42,3 +99,58 @@ export interface ProfiledDevianceOptions {
|
|
|
42
99
|
* @param options What to compute besides: the gradient with respect to θ, (R_X' R_X)⁻¹.
|
|
43
100
|
*/
|
|
44
101
|
export declare function profiledDeviance(structure: MixedModelStructure, theta: readonly number[], reml: boolean, options?: ProfiledDevianceOptions): ProfiledDeviance;
|
|
102
|
+
/**
|
|
103
|
+
* The state of the penalised least-squares solution at a given θ (internal): the system of the structure, the blocks
|
|
104
|
+
* T_k, the sparse factor L of A, C_X = L⁻¹ Λ'Z'X, the Cholesky factor R_X (upper triangle, column-major, p × p) of
|
|
105
|
+
* R_X'R_X = E'E + W'W, the columns of W = A⁻¹ Λ'Z'X and of E = X − ZΛW, the residual y − Xβ̂ − ZΛû, û, β̂, b = Λû,
|
|
106
|
+
* and the solver of the normal equations of the penalised least squares. {@link profiledDeviance} is computed from
|
|
107
|
+
* it, and src/models/mixedDerivatives.ts takes the second derivatives from it.
|
|
108
|
+
*/
|
|
109
|
+
export interface PlsState {
|
|
110
|
+
sys: SparseSystem;
|
|
111
|
+
t: Float64Array[];
|
|
112
|
+
l: Float64Array;
|
|
113
|
+
cx: Float64Array;
|
|
114
|
+
rx: Float64Array;
|
|
115
|
+
ws: Float64Array[];
|
|
116
|
+
xResiduals: Float64Array[];
|
|
117
|
+
res: Float64Array;
|
|
118
|
+
uv: Float64Array;
|
|
119
|
+
beta: Float64Array;
|
|
120
|
+
b: Float64Array;
|
|
121
|
+
/** Solves [A, Λ'Z'X; X'ZΛ, X'X] (u, β) = (gu, gβ) with the two factors, overwriting gu with u and gβ with β */
|
|
122
|
+
solveNormal: (gu: Float64Array, gb: Float64Array) => void;
|
|
123
|
+
}
|
|
124
|
+
/** The penalised least-squares solution at θ and the factors it was computed with (see {@link PlsState}) */
|
|
125
|
+
export declare function plsState(structure: MixedModelStructure, theta: readonly number[]): PlsState;
|
|
126
|
+
/**
|
|
127
|
+
* The selected inverse of A = L L': the entries of A⁻¹ on the pattern of L (lower part, the layout of L's values), by
|
|
128
|
+
* the recurrences of Takahashi, Fagan and Chin (1973). Since L' A⁻¹ = L⁻¹ is lower triangular with diagonal 1 / L_jj,
|
|
129
|
+
* row j of it gives, for i > j in the pattern of column j,
|
|
130
|
+
* A⁻¹[i, j] = −(1 / L_jj) Σ_k L[k, j] A⁻¹[k, i], A⁻¹[j, j] = 1 / L_jj² − (1 / L_jj) Σ_k L[k, j] A⁻¹[k, j],
|
|
131
|
+
* the sums over the rows k > j of column j. The rows of column j form a clique in the pattern of L (the closure of a
|
|
132
|
+
* Cholesky pattern), so every A⁻¹[k, i] needed is on the pattern, in column min(k, i), already computed when the
|
|
133
|
+
* columns are taken from the last to the first. The cost is that of the factorisation.
|
|
134
|
+
*/
|
|
135
|
+
export declare function selectedInverse(sys: SparseSystem, l: Float64Array): Float64Array;
|
|
136
|
+
/**
|
|
137
|
+
* The derivative ∂L of the Cholesky factor L of A along a direction in which A changes by ∂A (`da`, the layout of the
|
|
138
|
+
* blocks of A, both triangles of the diagonal blocks): {@link factorise} differentiated step by step (forward mode).
|
|
139
|
+
* In column j, after the columns k < j are subtracted, the work vector holds L_jj L[r, j] (L_jj² at r = j), so with
|
|
140
|
+
* ∂ of the same subtractions (∂L[r, k] L[j, k] + L[r, k] ∂L[j, k]),
|
|
141
|
+
* ∂L_jj = ∂work[j] / (2 L_jj), ∂L[r, j] = (∂work[r] − L[r, j] ∂L_jj) / L_jj.
|
|
142
|
+
* An entry L[j, k] that is 0 (a column of Λ_θ that is 0) is not skipped: its derivative need not be 0.
|
|
143
|
+
*/
|
|
144
|
+
export declare function factoriseSystemTangent(sys: SparseSystem, l: Float64Array, da: Float64Array): Float64Array;
|
|
145
|
+
/**
|
|
146
|
+
* The derivative of the selected inverse `inv` of A = L L' given the derivative ∂L of L (`dl`): the recurrences of
|
|
147
|
+
* {@link selectedInverse} differentiated step by step (forward mode). It is ∂(A⁻¹) = −A⁻¹ ∂A A⁻¹ on the pattern of L.
|
|
148
|
+
*/
|
|
149
|
+
export declare function selectedInverseTangent(sys: SparseSystem, l: Float64Array, dl: Float64Array, inv: Float64Array): Float64Array;
|
|
150
|
+
/**
|
|
151
|
+
* S_k = Σ over the levels G of term k of (Y Λ' Z'Z) on G's columns (nc_k × nc_k, column-major), for Y = A⁻¹ given by
|
|
152
|
+
* its selected inverse `inv` (the layout of L's values) and Λ by its blocks `t` (see {@link sparseGradient}). Linear
|
|
153
|
+
* in `inv` and in `t`, so that the derivatives of the sums (src/models/mixedDerivatives.ts) come from the derivative
|
|
154
|
+
* of the selected inverse and of the blocks.
|
|
155
|
+
*/
|
|
156
|
+
export declare function levelTraceSums(sys: SparseSystem, inv: Float64Array, t: Float64Array[]): Float64Array[];
|
|
@@ -52,6 +52,10 @@
|
|
|
52
52
|
// A⁻¹ only on the blocks of Z'Z, which lie on the pattern of L: the selected inverse (A⁻¹ on the pattern of L, by
|
|
53
53
|
// Takahashi's recurrences; K by blocks of Z'Z, never formed), so the gradient costs about one more factorisation, and
|
|
54
54
|
// memory of the order of the nonzeros of L, Z and Z'X.
|
|
55
|
+
//
|
|
56
|
+
// The second derivatives that lmerTest's tests need (src/models/mixedDerivatives.ts) are computed from the same state
|
|
57
|
+
// (plsState): the selected inverse, the sums of levelTraceSums, and the derivatives of the factor and of the selected
|
|
58
|
+
// inverse along an element of θ (factoriseSystemTangent, selectedInverseTangent).
|
|
55
59
|
import { potf2, potri } from "../linalg/chol.js";
|
|
56
60
|
/** Steps of iterative refinement of the penalised least-squares solution */
|
|
57
61
|
const REFINEMENT_STEPS = 1;
|
|
@@ -309,7 +313,7 @@ function blocksOf(sys, theta) {
|
|
|
309
313
|
return sys.termTheta.map((idx) => Float64Array.from(idx, (t) => (t < 0 ? 0 : theta[t])));
|
|
310
314
|
}
|
|
311
315
|
/** Λ_θ w (q-vector) */
|
|
312
|
-
function lambdaTimes(sys, t, w) {
|
|
316
|
+
export function lambdaTimes(sys, t, w) {
|
|
313
317
|
const out = new Float64Array(sys.q);
|
|
314
318
|
for (let g = 0; g < sys.nGroups; g++) {
|
|
315
319
|
const k = sys.groupTerm[g];
|
|
@@ -327,7 +331,7 @@ function lambdaTimes(sys, t, w) {
|
|
|
327
331
|
return out;
|
|
328
332
|
}
|
|
329
333
|
/** Λ_θ' M for a q × ncol column-major M */
|
|
330
|
-
function lambdaTransposeTimes(sys, t, m, ncol = 1) {
|
|
334
|
+
export function lambdaTransposeTimes(sys, t, m, ncol = 1) {
|
|
331
335
|
const q = sys.q;
|
|
332
336
|
const out = new Float64Array(q * ncol);
|
|
333
337
|
for (let g = 0; g < sys.nGroups; g++) {
|
|
@@ -437,7 +441,7 @@ function factorise(sys, a) {
|
|
|
437
441
|
return l;
|
|
438
442
|
}
|
|
439
443
|
/** Solves L x = v in place (v of length q, at an offset) */
|
|
440
|
-
function solveL(sys, l, v, offset = 0) {
|
|
444
|
+
export function solveL(sys, l, v, offset = 0) {
|
|
441
445
|
const { q, colStart, colRows } = sys;
|
|
442
446
|
for (let j = 0; j < q; j++) {
|
|
443
447
|
const start = colStart[j];
|
|
@@ -449,7 +453,7 @@ function solveL(sys, l, v, offset = 0) {
|
|
|
449
453
|
}
|
|
450
454
|
}
|
|
451
455
|
/** Solves L' x = v in place */
|
|
452
|
-
function solveLt(sys, l, v, offset = 0) {
|
|
456
|
+
export function solveLt(sys, l, v, offset = 0) {
|
|
453
457
|
const { q, colStart, colRows } = sys;
|
|
454
458
|
for (let j = q - 1; j >= 0; j--) {
|
|
455
459
|
const start = colStart[j];
|
|
@@ -479,7 +483,7 @@ function backSolve(r, k, v) {
|
|
|
479
483
|
}
|
|
480
484
|
}
|
|
481
485
|
/** The full symmetric inverse of R'R from an upper-triangular factor R (column-major, k × k; R is not changed) */
|
|
482
|
-
function inverseFromFactor(r, k) {
|
|
486
|
+
export function inverseFromFactor(r, k) {
|
|
483
487
|
const inv = r.slice();
|
|
484
488
|
for (let j = 0; j < k; j++)
|
|
485
489
|
for (let i = j + 1; i < k; i++)
|
|
@@ -501,6 +505,41 @@ function inverseFromFactor(r, k) {
|
|
|
501
505
|
* @param options What to compute besides: the gradient with respect to θ, (R_X' R_X)⁻¹.
|
|
502
506
|
*/
|
|
503
507
|
export function profiledDeviance(structure, theta, reml, options = {}) {
|
|
508
|
+
const state = plsState(structure, theta);
|
|
509
|
+
const { sys, t, l, rx, ws, xResiduals, res, uv } = state;
|
|
510
|
+
const { n, p, q } = sys;
|
|
511
|
+
const beta = Array.from(state.beta);
|
|
512
|
+
const u = Array.from(uv);
|
|
513
|
+
const b = Array.from(state.b);
|
|
514
|
+
let rss = 0;
|
|
515
|
+
for (const e of res)
|
|
516
|
+
rss += e * e;
|
|
517
|
+
let ussq = 0;
|
|
518
|
+
for (const v of u)
|
|
519
|
+
ussq += v * v;
|
|
520
|
+
const prss = rss + ussq;
|
|
521
|
+
let logDetL = 0;
|
|
522
|
+
for (let j = 0; j < q; j++)
|
|
523
|
+
logDetL += Math.log(l[sys.colStart[j]]);
|
|
524
|
+
logDetL *= 2;
|
|
525
|
+
let logDetRX = 0;
|
|
526
|
+
for (let k = 0; k < p; k++)
|
|
527
|
+
logDetRX += Math.log(rx[k + k * p]);
|
|
528
|
+
logDetRX *= 2;
|
|
529
|
+
const df = reml ? n - p : n;
|
|
530
|
+
const deviance = (reml ? logDetL + logDetRX : logDetL) + df * (1 + Math.log((2 * Math.PI * prss) / df));
|
|
531
|
+
const out = { deviance, beta, u, b, rss, ussq, prss, logDetL, logDetRX };
|
|
532
|
+
const sInverse = options.gradient === true || options.rxInverse === true ? inverseFromFactor(rx, p) : undefined;
|
|
533
|
+
if (options.rxInverse === true) {
|
|
534
|
+
out.rxInverse = Array.from({ length: p }, (_, i) => Array.from({ length: p }, (_, j) => sInverse[i + j * p]));
|
|
535
|
+
}
|
|
536
|
+
if (options.gradient === true) {
|
|
537
|
+
out.gradient = sparseGradient(structure, sys, t, l, theta, reml, { res, uv, prss, ws, xResiduals, sInverse: sInverse });
|
|
538
|
+
}
|
|
539
|
+
return out;
|
|
540
|
+
}
|
|
541
|
+
/** The penalised least-squares solution at θ and the factors it was computed with (see {@link PlsState}) */
|
|
542
|
+
export function plsState(structure, theta) {
|
|
504
543
|
if (theta.length !== structure.theta.length) {
|
|
505
544
|
throw new RangeError(`theta must have length ${structure.theta.length}, not ${theta.length}`);
|
|
506
545
|
}
|
|
@@ -643,35 +682,7 @@ export function profiledDeviance(structure, theta, reml, options = {}) {
|
|
|
643
682
|
bv = lambdaTimes(sys, t, uv);
|
|
644
683
|
res = residual(betav, bv);
|
|
645
684
|
}
|
|
646
|
-
|
|
647
|
-
const u = Array.from(uv);
|
|
648
|
-
const b = Array.from(bv);
|
|
649
|
-
let rss = 0;
|
|
650
|
-
for (const e of res)
|
|
651
|
-
rss += e * e;
|
|
652
|
-
let ussq = 0;
|
|
653
|
-
for (const v of u)
|
|
654
|
-
ussq += v * v;
|
|
655
|
-
const prss = rss + ussq;
|
|
656
|
-
let logDetL = 0;
|
|
657
|
-
for (let j = 0; j < q; j++)
|
|
658
|
-
logDetL += Math.log(l[sys.colStart[j]]);
|
|
659
|
-
logDetL *= 2;
|
|
660
|
-
let logDetRX = 0;
|
|
661
|
-
for (let k = 0; k < p; k++)
|
|
662
|
-
logDetRX += Math.log(rx[k + k * p]);
|
|
663
|
-
logDetRX *= 2;
|
|
664
|
-
const df = reml ? n - p : n;
|
|
665
|
-
const deviance = (reml ? logDetL + logDetRX : logDetL) + df * (1 + Math.log((2 * Math.PI * prss) / df));
|
|
666
|
-
const out = { deviance, beta, u, b, rss, ussq, prss, logDetL, logDetRX };
|
|
667
|
-
const sInverse = options.gradient === true || options.rxInverse === true ? inverseFromFactor(rx, p) : undefined;
|
|
668
|
-
if (options.rxInverse === true) {
|
|
669
|
-
out.rxInverse = Array.from({ length: p }, (_, i) => Array.from({ length: p }, (_, j) => sInverse[i + j * p]));
|
|
670
|
-
}
|
|
671
|
-
if (options.gradient === true) {
|
|
672
|
-
out.gradient = sparseGradient(structure, sys, t, l, theta, reml, { res, uv, prss, ws, xResiduals, sInverse: sInverse });
|
|
673
|
-
}
|
|
674
|
-
return out;
|
|
685
|
+
return { sys, t, l, cx, rx, ws, xResiduals, res, uv, beta: betav, b: bv, solveNormal };
|
|
675
686
|
}
|
|
676
687
|
/**
|
|
677
688
|
* The selected inverse of A = L L': the entries of A⁻¹ on the pattern of L (lower part, the layout of L's values), by
|
|
@@ -682,7 +693,7 @@ export function profiledDeviance(structure, theta, reml, options = {}) {
|
|
|
682
693
|
* Cholesky pattern), so every A⁻¹[k, i] needed is on the pattern, in column min(k, i), already computed when the
|
|
683
694
|
* columns are taken from the last to the first. The cost is that of the factorisation.
|
|
684
695
|
*/
|
|
685
|
-
function selectedInverse(sys, l) {
|
|
696
|
+
export function selectedInverse(sys, l) {
|
|
686
697
|
const { q, colStart, colRows } = sys;
|
|
687
698
|
const inv = new Float64Array(l.length);
|
|
688
699
|
const inColumn = new Int32Array(q).fill(-1);
|
|
@@ -725,6 +736,116 @@ function selectedInverse(sys, l) {
|
|
|
725
736
|
}
|
|
726
737
|
return inv;
|
|
727
738
|
}
|
|
739
|
+
/**
|
|
740
|
+
* The derivative ∂L of the Cholesky factor L of A along a direction in which A changes by ∂A (`da`, the layout of the
|
|
741
|
+
* blocks of A, both triangles of the diagonal blocks): {@link factorise} differentiated step by step (forward mode).
|
|
742
|
+
* In column j, after the columns k < j are subtracted, the work vector holds L_jj L[r, j] (L_jj² at r = j), so with
|
|
743
|
+
* ∂ of the same subtractions (∂L[r, k] L[j, k] + L[r, k] ∂L[j, k]),
|
|
744
|
+
* ∂L_jj = ∂work[j] / (2 L_jj), ∂L[r, j] = (∂work[r] − L[r, j] ∂L_jj) / L_jj.
|
|
745
|
+
* An entry L[j, k] that is 0 (a column of Λ_θ that is 0) is not skipped: its derivative need not be 0.
|
|
746
|
+
*/
|
|
747
|
+
export function factoriseSystemTangent(sys, l, da) {
|
|
748
|
+
const { q, colStart, colRows, rowListStart, rowListCol, rowListPos } = sys;
|
|
749
|
+
const dl = new Float64Array(l.length);
|
|
750
|
+
const work = new Float64Array(q);
|
|
751
|
+
for (let h = 0; h < sys.nGroups; h++) {
|
|
752
|
+
const ncc = sys.termNc[sys.groupTerm[h]];
|
|
753
|
+
const first = sys.groupStart[h];
|
|
754
|
+
for (let c = 0; c < ncc; c++) {
|
|
755
|
+
const j = first + c;
|
|
756
|
+
for (let b = sys.blockStart[h]; b < sys.blockStart[h + 1]; b++) {
|
|
757
|
+
const g = sys.blockRow[b];
|
|
758
|
+
const ncr = sys.termNc[sys.groupTerm[g]];
|
|
759
|
+
const base = sys.blockValueStart[b] + c * ncr;
|
|
760
|
+
const r0 = sys.groupStart[g];
|
|
761
|
+
for (let r = g === h ? c : 0; r < ncr; r++)
|
|
762
|
+
work[r0 + r] = da[base + r];
|
|
763
|
+
}
|
|
764
|
+
for (let e = rowListStart[j]; e < rowListStart[j + 1]; e++) {
|
|
765
|
+
const k = rowListCol[e];
|
|
766
|
+
const pos = rowListPos[e];
|
|
767
|
+
const ljk = l[pos];
|
|
768
|
+
const dljk = dl[pos];
|
|
769
|
+
if (ljk === 0 && dljk === 0)
|
|
770
|
+
continue;
|
|
771
|
+
const end = colStart[k + 1];
|
|
772
|
+
for (let t = pos; t < end; t++)
|
|
773
|
+
work[colRows[t]] -= dl[t] * ljk + l[t] * dljk;
|
|
774
|
+
}
|
|
775
|
+
const start = colStart[j];
|
|
776
|
+
const ljj = l[start];
|
|
777
|
+
const dljj = work[j] / (2 * ljj);
|
|
778
|
+
dl[start] = dljj;
|
|
779
|
+
work[j] = 0;
|
|
780
|
+
for (let t = start + 1; t < colStart[j + 1]; t++) {
|
|
781
|
+
const r = colRows[t];
|
|
782
|
+
dl[t] = (work[r] - l[t] * dljj) / ljj;
|
|
783
|
+
work[r] = 0;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
return dl;
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* The derivative of the selected inverse `inv` of A = L L' given the derivative ∂L of L (`dl`): the recurrences of
|
|
791
|
+
* {@link selectedInverse} differentiated step by step (forward mode). It is ∂(A⁻¹) = −A⁻¹ ∂A A⁻¹ on the pattern of L.
|
|
792
|
+
*/
|
|
793
|
+
export function selectedInverseTangent(sys, l, dl, inv) {
|
|
794
|
+
const { q, colStart, colRows } = sys;
|
|
795
|
+
const dinv = new Float64Array(l.length);
|
|
796
|
+
const inColumn = new Int32Array(q).fill(-1);
|
|
797
|
+
const lj = new Float64Array(q);
|
|
798
|
+
const dlj = new Float64Array(q);
|
|
799
|
+
const acc = new Float64Array(q);
|
|
800
|
+
const dacc = new Float64Array(q);
|
|
801
|
+
for (let j = q - 1; j >= 0; j--) {
|
|
802
|
+
const start = colStart[j];
|
|
803
|
+
const end = colStart[j + 1];
|
|
804
|
+
for (let t = start + 1; t < end; t++) {
|
|
805
|
+
const r = colRows[t];
|
|
806
|
+
inColumn[r] = j;
|
|
807
|
+
lj[r] = l[t];
|
|
808
|
+
dlj[r] = dl[t];
|
|
809
|
+
acc[r] = 0;
|
|
810
|
+
dacc[r] = 0;
|
|
811
|
+
}
|
|
812
|
+
for (let t = start + 1; t < end; t++) {
|
|
813
|
+
const k = colRows[t];
|
|
814
|
+
const lkj = l[t];
|
|
815
|
+
const dlkj = dl[t];
|
|
816
|
+
const kStart = colStart[k];
|
|
817
|
+
let sum = inv[kStart] * lkj;
|
|
818
|
+
let dsum = dinv[kStart] * lkj + inv[kStart] * dlkj;
|
|
819
|
+
for (let e = kStart + 1; e < colStart[k + 1]; e++) {
|
|
820
|
+
const r = colRows[e];
|
|
821
|
+
if (inColumn[r] !== j)
|
|
822
|
+
continue;
|
|
823
|
+
const v = inv[e];
|
|
824
|
+
const dv = dinv[e];
|
|
825
|
+
acc[r] += v * lkj;
|
|
826
|
+
dacc[r] += dv * lkj + v * dlkj;
|
|
827
|
+
sum += v * lj[r];
|
|
828
|
+
dsum += dv * lj[r] + v * dlj[r];
|
|
829
|
+
}
|
|
830
|
+
acc[k] += sum;
|
|
831
|
+
dacc[k] += dsum;
|
|
832
|
+
}
|
|
833
|
+
const d = l[start];
|
|
834
|
+
const dd = dl[start];
|
|
835
|
+
let diagonal = 1 / d;
|
|
836
|
+
let ddiagonal = -dd / (d * d);
|
|
837
|
+
for (let t = start + 1; t < end; t++) {
|
|
838
|
+
const r = colRows[t];
|
|
839
|
+
const v = inv[t];
|
|
840
|
+
const dv = -dacc[r] / d + (acc[r] * dd) / (d * d);
|
|
841
|
+
dinv[t] = dv;
|
|
842
|
+
diagonal -= l[t] * v;
|
|
843
|
+
ddiagonal -= dl[t] * v + l[t] * dv;
|
|
844
|
+
}
|
|
845
|
+
dinv[start] = ddiagonal / d - (diagonal * dd) / (d * d);
|
|
846
|
+
}
|
|
847
|
+
return dinv;
|
|
848
|
+
}
|
|
728
849
|
/**
|
|
729
850
|
* The gradient of the criterion with respect to θ (see the header), sparse. The log-determinant term
|
|
730
851
|
* 2 Σ_(r,c) (A⁻¹ K)[c, r] (K = Λ'Z'Z) involves, for the entries (r, c) of Λ_θ in group G,
|
|
@@ -734,9 +855,65 @@ function selectedInverse(sys, l) {
|
|
|
734
855
|
* place of T_k in every level. The other terms need Z'res (q), W S⁻¹ (q × p) and E'Z (p × q).
|
|
735
856
|
*/
|
|
736
857
|
function sparseGradient(structure, sys, t, l, theta, reml, { res, uv, prss, ws, xResiduals, sInverse }) {
|
|
737
|
-
const { n, p, q
|
|
738
|
-
const
|
|
739
|
-
|
|
858
|
+
const { n, p, q } = sys;
|
|
859
|
+
const sums = levelTraceSums(sys, selectedInverse(sys, l), t);
|
|
860
|
+
const gradient = new Array(theta.length).fill(0);
|
|
861
|
+
sys.termTheta.forEach((idx, k) => {
|
|
862
|
+
const nc = sys.termNc[k];
|
|
863
|
+
for (let cl = 0; cl < nc; cl++) {
|
|
864
|
+
for (let rl = cl; rl < nc; rl++)
|
|
865
|
+
gradient[idx[rl + cl * nc]] += 2 * sums[k][cl + rl * nc];
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
// Z' res
|
|
869
|
+
const zRes = new Float64Array(q);
|
|
870
|
+
for (let i = 0; i < n; i++) {
|
|
871
|
+
const ri = res[i];
|
|
872
|
+
for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
|
|
873
|
+
zRes[sys.rowCols[c]] += sys.rowValues[c] * ri;
|
|
874
|
+
}
|
|
875
|
+
// REML: V = W S⁻¹ (q × p) and E'Z (p × q), both column-major
|
|
876
|
+
let v;
|
|
877
|
+
let ez;
|
|
878
|
+
if (reml && p > 0) {
|
|
879
|
+
v = new Float64Array(q * p);
|
|
880
|
+
for (let m = 0; m < p; m++) {
|
|
881
|
+
for (let k = 0; k < p; k++) {
|
|
882
|
+
const skm = sInverse[k + m * p];
|
|
883
|
+
const wk = ws[k];
|
|
884
|
+
for (let c = 0; c < q; c++)
|
|
885
|
+
v[c + m * q] += wk[c] * skm;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
ez = new Float64Array(p * q);
|
|
889
|
+
for (let i = 0; i < n; i++) {
|
|
890
|
+
for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++) {
|
|
891
|
+
const zr = sys.rowCols[c];
|
|
892
|
+
const val = sys.rowValues[c];
|
|
893
|
+
for (let m = 0; m < p; m++)
|
|
894
|
+
ez[m + zr * p] += xResiduals[m][i] * val;
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
const df = reml ? n - p : n;
|
|
899
|
+
const prssFactor = (2 * df) / prss;
|
|
900
|
+
for (const { row: rr, col: c, theta: ti } of structure.lambda) {
|
|
901
|
+
let tr = 0;
|
|
902
|
+
if (v !== undefined && ez !== undefined)
|
|
903
|
+
for (let m = 0; m < p; m++)
|
|
904
|
+
tr += v[c + m * q] * ez[m + rr * p];
|
|
905
|
+
gradient[ti] -= 2 * tr + prssFactor * zRes[rr] * uv[c];
|
|
906
|
+
}
|
|
907
|
+
return gradient;
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* S_k = Σ over the levels G of term k of (Y Λ' Z'Z) on G's columns (nc_k × nc_k, column-major), for Y = A⁻¹ given by
|
|
911
|
+
* its selected inverse `inv` (the layout of L's values) and Λ by its blocks `t` (see {@link sparseGradient}). Linear
|
|
912
|
+
* in `inv` and in `t`, so that the derivatives of the sums (src/models/mixedDerivatives.ts) come from the derivative
|
|
913
|
+
* of the selected inverse and of the blocks.
|
|
914
|
+
*/
|
|
915
|
+
export function levelTraceSums(sys, inv, t) {
|
|
916
|
+
const { colStart, zz } = sys;
|
|
740
917
|
const sums = sys.termNc.map((nc) => new Float64Array(nc * nc));
|
|
741
918
|
let y = new Float64Array(16);
|
|
742
919
|
let f = new Float64Array(16);
|
|
@@ -821,52 +998,5 @@ function sparseGradient(structure, sys, t, l, theta, reml, { res, uv, prss, ws,
|
|
|
821
998
|
}
|
|
822
999
|
}
|
|
823
1000
|
}
|
|
824
|
-
|
|
825
|
-
sys.termTheta.forEach((idx, k) => {
|
|
826
|
-
const nc = sys.termNc[k];
|
|
827
|
-
for (let cl = 0; cl < nc; cl++) {
|
|
828
|
-
for (let rl = cl; rl < nc; rl++)
|
|
829
|
-
gradient[idx[rl + cl * nc]] += 2 * sums[k][cl + rl * nc];
|
|
830
|
-
}
|
|
831
|
-
});
|
|
832
|
-
// Z' res
|
|
833
|
-
const zRes = new Float64Array(q);
|
|
834
|
-
for (let i = 0; i < n; i++) {
|
|
835
|
-
const ri = res[i];
|
|
836
|
-
for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
|
|
837
|
-
zRes[sys.rowCols[c]] += sys.rowValues[c] * ri;
|
|
838
|
-
}
|
|
839
|
-
// REML: V = W S⁻¹ (q × p) and E'Z (p × q), both column-major
|
|
840
|
-
let v;
|
|
841
|
-
let ez;
|
|
842
|
-
if (reml && p > 0) {
|
|
843
|
-
v = new Float64Array(q * p);
|
|
844
|
-
for (let m = 0; m < p; m++) {
|
|
845
|
-
for (let k = 0; k < p; k++) {
|
|
846
|
-
const skm = sInverse[k + m * p];
|
|
847
|
-
const wk = ws[k];
|
|
848
|
-
for (let c = 0; c < q; c++)
|
|
849
|
-
v[c + m * q] += wk[c] * skm;
|
|
850
|
-
}
|
|
851
|
-
}
|
|
852
|
-
ez = new Float64Array(p * q);
|
|
853
|
-
for (let i = 0; i < n; i++) {
|
|
854
|
-
for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++) {
|
|
855
|
-
const zr = sys.rowCols[c];
|
|
856
|
-
const val = sys.rowValues[c];
|
|
857
|
-
for (let m = 0; m < p; m++)
|
|
858
|
-
ez[m + zr * p] += xResiduals[m][i] * val;
|
|
859
|
-
}
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
const df = reml ? n - p : n;
|
|
863
|
-
const prssFactor = (2 * df) / prss;
|
|
864
|
-
for (const { row: rr, col: c, theta: ti } of structure.lambda) {
|
|
865
|
-
let tr = 0;
|
|
866
|
-
if (v !== undefined && ez !== undefined)
|
|
867
|
-
for (let m = 0; m < p; m++)
|
|
868
|
-
tr += v[c + m * q] * ez[m + rr * p];
|
|
869
|
-
gradient[ti] -= 2 * tr + prssFactor * zRes[rr] * uv[c];
|
|
870
|
-
}
|
|
871
|
-
return gradient;
|
|
1001
|
+
return sums;
|
|
872
1002
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type DataFrame } from "./modelFrame.js";
|
|
2
|
-
import { type ModelMatrixOptions } from "./modelMatrix.js";
|
|
2
|
+
import { type DesignContrast, type ModelMatrixOptions } from "./modelMatrix.js";
|
|
3
3
|
/** A random-effects term of a mixed model, after the expansion of its grouping expression and of `||`. */
|
|
4
4
|
export interface RandomEffectsTerm {
|
|
5
5
|
/** The term as R deparses it, such as `"1 | g"`, `"0 + x | b:a"`. */
|
|
@@ -68,8 +68,10 @@ export interface MixedModelStructure {
|
|
|
68
68
|
/** R's warnings (predictors on very different scales). */
|
|
69
69
|
warnings: string[];
|
|
70
70
|
}
|
|
71
|
-
/** Options of {@link mixedModelStructure}: those of the fixed-effects model matrix. */
|
|
72
|
-
export type MixedModelStructureOptions = ModelMatrixOptions
|
|
71
|
+
/** Options of {@link mixedModelStructure}: those of the fixed-effects model matrix (contr.poly accepted too). */
|
|
72
|
+
export type MixedModelStructureOptions = Omit<ModelMatrixOptions, "contrasts"> & {
|
|
73
|
+
contrasts?: Record<string, DesignContrast>;
|
|
74
|
+
};
|
|
73
75
|
/**
|
|
74
76
|
* The structure of a linear mixed model `response ~ fixed part + (lhs | group) + ...`: the model frame, X, Z, the
|
|
75
77
|
* layout of Λ_θ, the initial θ and its lower bounds, with lme4's checks, errors, messages and warnings
|
|
@@ -49,8 +49,13 @@ export interface ModelMatrixResult {
|
|
|
49
49
|
/** R's warnings. */
|
|
50
50
|
warnings: string[];
|
|
51
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* A contrast the internal model-matrix code accepts: those of {@link ContrastName} and R's `contr.poly` (orthogonal
|
|
54
|
+
* polynomials in the level scores 1, 2, ..., columns `.L`, `.Q`, `.C`, `^4`, ...), which lmer's fixed effects may use.
|
|
55
|
+
*/
|
|
56
|
+
export type DesignContrast = ContrastName | "contr.poly";
|
|
52
57
|
/** A contrast matrix (one row per level) and its column names */
|
|
53
|
-
export declare function contrastMatrix(levels: readonly string[], contrast:
|
|
58
|
+
export declare function contrastMatrix(levels: readonly string[], contrast: DesignContrast | "indicators"): {
|
|
54
59
|
m: number[][];
|
|
55
60
|
names: string[];
|
|
56
61
|
};
|
|
@@ -67,11 +72,13 @@ export interface Design {
|
|
|
67
72
|
warnings: string[];
|
|
68
73
|
}
|
|
69
74
|
/** Options of {@link design} */
|
|
70
|
-
export interface DesignOptions extends ModelMatrixOptions {
|
|
75
|
+
export interface DesignOptions extends Omit<ModelMatrixOptions, "contrasts"> {
|
|
76
|
+
/** A contrast per factor, as {@link ModelMatrixOptions.contrasts} (`contr.poly` too) */
|
|
77
|
+
contrasts?: Record<string, DesignContrast>;
|
|
71
78
|
weights?: Sample | string;
|
|
72
79
|
dropUnusedLevels?: boolean;
|
|
73
80
|
/** Contrast used for every factor instead of `contrasts` (the error model of aov) */
|
|
74
|
-
allContrasts?:
|
|
81
|
+
allContrasts?: DesignContrast;
|
|
75
82
|
/** The intercept flag to use instead of the formula's (the error model of aov) */
|
|
76
83
|
intercept?: boolean;
|
|
77
84
|
/** More variables whose missing values drop rows (the rest of the formula, for the error model of aov) */
|
|
@@ -2,10 +2,25 @@
|
|
|
2
2
|
//
|
|
3
3
|
// Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("Coding"). Each term contributes the
|
|
4
4
|
// products of one column of each of its variables, the first variable varying fastest: a numeric variable's values,
|
|
5
|
-
// or a factor's contrast columns (contr.treatment, contr.sum or contr.helmert) or indicator
|
|
6
|
-
// codes of src/models/formula.ts. Without an intercept the first factor found is coded by
|
|
5
|
+
// or a factor's contrast columns (contr.treatment, contr.sum or contr.helmert; internally also contr.poly) or indicator
|
|
6
|
+
// columns, as chosen by the codes of src/models/formula.ts. Without an intercept the first factor found is coded by
|
|
7
|
+
// indicators.
|
|
7
8
|
import { parseFormula, termsOf } from "./formula.js";
|
|
8
9
|
import { modelFrame } from "./modelFrame.js";
|
|
10
|
+
import { qr, qrQ, qrR } from "../linalg/qr.js";
|
|
11
|
+
/**
|
|
12
|
+
* contr.poly for k levels (scores 1..k): the orthonormal polynomials of degrees 1..k-1 in the scores, the columns
|
|
13
|
+
* of Q of the QR decomposition of the powers 0..k-1 of the centred scores, each signed so that its coefficient of
|
|
14
|
+
* the highest power is positive (Q diag(R), normalised).
|
|
15
|
+
*/
|
|
16
|
+
function polyContrasts(k) {
|
|
17
|
+
const mean = (k + 1) / 2;
|
|
18
|
+
const powers = Array.from({ length: k }, (_, i) => Array.from({ length: k }, (__, j) => (i + 1 - mean) ** j));
|
|
19
|
+
const d = qr(powers);
|
|
20
|
+
const q = qrQ(d);
|
|
21
|
+
const r = qrR(d);
|
|
22
|
+
return q.map((row) => row.slice(1).map((v, j) => (r[j + 1][j + 1] < 0 ? -v : v)));
|
|
23
|
+
}
|
|
9
24
|
/** A contrast matrix (one row per level) and its column names */
|
|
10
25
|
export function contrastMatrix(levels, contrast) {
|
|
11
26
|
const k = levels.length;
|
|
@@ -37,6 +52,12 @@ export function contrastMatrix(levels, contrast) {
|
|
|
37
52
|
});
|
|
38
53
|
names = Array.from({ length: k - 1 }, (_, j) => String(j + 1));
|
|
39
54
|
break;
|
|
55
|
+
case "contr.poly": {
|
|
56
|
+
const pc = polyContrasts(k);
|
|
57
|
+
levels.forEach((_, i) => m[i].push(...pc[i]));
|
|
58
|
+
names = Array.from({ length: k - 1 }, (_, j) => [".L", ".Q", ".C"][j] ?? `^${j + 1}`);
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
40
61
|
default:
|
|
41
62
|
throw new RangeError(`unknown contrast '${String(contrast)}'`);
|
|
42
63
|
}
|
package/dist/numerics.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! rStats.js 0.
|
|
2
|
-
import{a as $,b as T,c as D,d as F,e as O}from"./chunks/chunk-VG67L3JA.js";import"./chunks/chunk-BJHBYEEU.js";import{a as k,f as j}from"./chunks/chunk-2IAT6MT2.js";import"./chunks/chunk-F44XUHWI.js";import{f as S}from"./chunks/chunk-SLSDFIW2.js";import"./chunks/chunk-MEMYFTYS.js";import"./chunks/chunk-3AKA4KEL.js";function M(o,l,t="mean"){if(o.length!==l.length)throw new RangeError("'x' and 'y' lengths differ");let n=[];for(let r=0;r<o.length;r++)!Number.isNaN(o[r])&&!Number.isNaN(l[r])&&n.push(r);n.sort((r,s)=>o[r]-o[s]);let e=typeof t=="function"?t:t==="min"?r=>Math.min(...r):t==="max"?r=>Math.max(...r):S,a=[],f=[];for(let r=0;r<n.length;){let s=o[n[r]],c=r+1;for(;c<n.length&&o[n[c]]===s;)c++;a.push(s),f.push(c-r===1?l[n[r]]:e(n.slice(r,c).map(i=>l[i]))),r=c}return{x:a,y:f}}function X(o,l,t,n){let e=(n-o[t])/(o[t+1]-o[t]);return l[t]+(l[t+1]-l[t])*e}function J(o,l,t){let n=(e,a)=>e===0?0:e*a;return n(1-t,o[l])+n(t,o[l+1])}function P(o,l,t={}){let{method:n="linear",n:e=50,f:a=0,rule:f=1,ties:r="mean"}=t,s=M(o,l,r),c=s.x.length;if(c<=1&&n==="linear")throw new RangeError("need at least two non-NA values to interpolate");if(c===0)throw new RangeError("zero non-NA points");if(n==="constant"&&!(a>=0&&a<=1))throw new RangeError("approx(): invalid f value");let[i,p]=typeof f=="number"?[f,f]:f,d=t.yleft??(i===1?NaN:s.y[0]),h=t.yright??(p===1?NaN:s.y[c-1]),m;if(t.xout!==void 0)m=Array.from(t.xout);else{if(e<=0)throw new RangeError("'approx' requires n >= 1");m=k(s.x[0],s.x[c-1],e)}let g=s.x,u=s.y,w=j(m,g),y=m.map((b,A)=>{let R=w[A];if(Number.isNaN(R))return NaN;if(R===0)return d;let E=R-1;return b===g[E]?u[E]:R===c?h:n==="linear"?X(g,u,E,b):J(u,E,a)});return{x:m,y}}function v(o,l){let t=o.length,n=new Array(t).fill(0),e=new Array(t).fill(0),a=new Array(t).fill(0);if(t<2)return{b:n,c:e,d:a};if(t<3)return n[0]=(l[1]-l[0])/(o[1]-o[0]),n[1]=n[0],{b:n,c:e,d:a};let f=t-1;a[0]=o[1]-o[0],e[1]=(l[1]-l[0])/a[0];for(let r=1;r<f;r++)a[r]=o[r+1]-o[r],n[r]=2*(a[r-1]+a[r]),e[r+1]=(l[r+1]-l[r])/a[r],e[r]=e[r+1]-e[r];n[0]=-a[0],n[f]=-a[t-2],e[0]=0,e[f]=0,t>3&&(e[0]=e[2]/(o[3]-o[1])-e[1]/(o[2]-o[0]),e[f]=e[t-2]/(o[f]-o[t-3])-e[t-3]/(o[t-2]-o[t-4]),e[0]=e[0]*a[0]*a[0]/(o[3]-o[0]),e[f]=-e[f]*a[t-2]*a[t-2]/(o[f]-o[t-4]));for(let r=1;r<t;r++){let s=a[r-1]/n[r-1];n[r]=n[r]-s*a[r-1],e[r]=e[r]-s*e[r-1]}e[f]=e[f]/n[f];for(let r=t-2;r>=0;r--)e[r]=(e[r]-a[r]*e[r+1])/n[r];n[f]=(l[f]-l[t-2])/a[t-2]+a[t-2]*(e[t-2]+2*e[f]);for(let r=0;r<f;r++)n[r]=(l[r+1]-l[r])/a[r]-a[r]*(e[r+1]+2*e[r]),a[r]=(e[r+1]-e[r])/a[r],e[r]=3*e[r];return e[f]=3*e[f],a[f]=a[t-2],{b:n,c:e,d:a}}function z(o,l,t){let n=o.length,e=new Array(n).fill(0),a=new Array(n).fill(0),f=new Array(n).fill(0);for(let r=0;r<n-1;r++){let s=o[r+1]-o[r];e[r]=(l[r+1]-l[r])/s-s*(t[r+1]+2*t[r]),a[r]=3*t[r],f[r]=(t[r+1]-t[r])/s}return{b:e,c:a,d:f}}function Y(o,l){let t=o.length;if(t<3)return v(o,l);let n=Array.from({length:t-1},(c,i)=>o[i+1]-o[i]),e=n.map((c,i)=>(l[i+1]-l[i])/c),a=new Array(t).fill(0),f=new Array(t).fill(0);for(let c=1;c<t-1;c++)a[c]=2*(n[c-1]+n[c]),f[c]=e[c]-e[c-1];for(let c=2;c<t-1;c++){let i=n[c-1]/a[c-1];a[c]=a[c]-i*n[c-1],f[c]=f[c]-i*f[c-1]}let r=new Array(t).fill(0);r[t-2]=f[t-2]/a[t-2];for(let c=t-3;c>=1;c--)r[c]=(f[c]-n[c]*r[c+1])/a[c];let s=z(o,l,r);return s.b[t-1]=e[t-2]+n[t-2]*r[t-2],s}function B(o,l){let t=o.length;if(l[0]!==l[t-1])throw new RangeError("periodic spline needs y[1] == y[n]");if(t<3)return{b:new Array(t).fill(0),c:new Array(t).fill(0),d:new Array(t).fill(0)};let n=t-1,e=Array.from({length:n},(u,w)=>o[w+1]-o[w]),a=e.map((u,w)=>(l[w+1]-l[w])/u),f=u=>u===0?n-1:u-1,r=Array.from({length:n},(u,w)=>2*(e[f(w)]+e[w])),s=Array.from({length:n},(u,w)=>a[w]-a[f(w)]),c=e.slice(),i=new Array(n).fill(0);i[0]=e[n-1],i[n-2]=i[n-2]+e[n-2];let p=i[0],d=r[n-1],h=s[n-1];for(let u=0;u<n-1;u++){if(u+1<n-1){let y=e[u]/r[u];r[u+1]=r[u+1]-y*c[u],i[u+1]=i[u+1]-y*i[u],s[u+1]=s[u+1]-y*s[u]}let w=p/r[u];d-=w*i[u],h-=w*s[u],u+1<n-1&&(p=(u+1===n-2?e[n-2]:0)-w*c[u])}let m=new Array(t).fill(0);m[n-1]=h/d;for(let u=n-2;u>=0;u--){let w=s[u]-i[u]*m[n-1]-(u<n-2?c[u]*m[u+1]:0);m[u]=w/r[u]}m[t-1]=m[0];let g=z(o,l,m);return g.b[t-1]=g.b[0],g.c[t-1]=g.c[0],g.d[t-1]=g.d[0],g}function G(o,l){let t=o.length,{b:n,c:e,d:a}=v(o,l);if(t<2)return{b:n,c:e,d:a};let f=Array.from({length:t-1},(s,c)=>(l[c+1]-l[c])/(o[c+1]-o[c]));for(let s=0;s<t;s++){let c=f[s===0?0:s-1],i=f[s===t-1?t-2:s],p=Math.min(Math.abs(c),Math.abs(i)),d=c*i>0?i>0:n[s]>=0;n[s]=d?Math.min(Math.max(0,n[s]),3*p):Math.max(Math.min(0,n[s]),-3*p)}for(let s=0;s<t-1;s++){let c=o[s+1]-o[s],i=(l[s+1]-l[s])/c;e[s]=(3*i-2*n[s]-n[s+1])/c,a[s]=(n[s]+n[s+1]-2*i)/(c*c)}let r=o[t-1]-o[t-2];return e[t-1]=(n[t-2]+2*n[t-1]-3*(l[t-1]-l[t-2])/r)/r,a[t-1]=a[t-2],{b:n,c:e,d:a}}function q(o,l,t,n){let e=M(o,l,n),a=e.x.length;if(a===0)throw new RangeError("zero non-NA points");t==="periodic"&&e.y[a-1]!==e.y[0]&&(e.y[a-1]=e.y[0]),t==="hyman"&&K(e.y);let f=t==="fmm"?v(e.x,e.y):t==="natural"?Y(e.x,e.y):t==="periodic"?B(e.x,e.y):t==="hyman"?G(e.x,e.y):(()=>{throw new RangeError(`invalid spline method '${String(t)}'`)})();return{method:t,...e,...f}}function K(o){let l=!0,t=!0;for(let n=1;n<o.length;n++){let e=o[n]-o[n-1];e>=0||(l=!1),e<=0||(t=!1)}if(!l&&!t)throw new RangeError("'y' must be increasing or decreasing")}function C(o){let l=Math.trunc(o);if(!(l>=0&&l<=3))throw new RangeError("'deriv' must be between 0 and 3");return l}function H(o,l,t){let n=C(t),{x:e,y:a,b:f,c:r,d:s,method:c}=o,i=e.length,p=c==="natural",d=e[i-1]-e[0],h=0;return Array.from(l,m=>{let g=m;if(c==="periodic"&&i>1){let y=(g-e[0])%d;y<0&&(y+=d),g=e[0]+y}if(p&&n>0&&g<=e[0])return n===1?f[0]:0;if(!(e[h]<=g&&(h===i-1||g<=e[h+1]))){let y=0,b=i;for(;b-y>1;){let A=y+b>>1;e[A]<=g?y=A:b=A}h=y}let u=g-e[h],w=p&&g<e[0]?0:s[h];switch(n){case 0:return a[h]+u*(f[h]+u*(r[h]+u*w));case 1:return f[h]+u*(2*r[h]+u*(3*w));case 2:return 2*r[h]+u*(6*w);default:return 6*w}})}function Q(o,l,t={}){let{method:n="fmm",ties:e="mean"}=t,a=q(o,l,n,e),f;if(t.xout!==void 0)f=Array.from(t.xout);else{let r=a.x.length,s=t.n??3*r;if(s<=0)throw new RangeError("'spline' requires n >= 1");f=k(t.xmin??a.x[0],t.xmax??a.x[r-1],s)}return{x:f,y:H(a,f,0)}}function U(o,l,t={}){let{method:n="fmm",ties:e="mean"}=t;if(n==="monoH.FC"){let f=M(o,l,e);if(f.x.length===0)throw new RangeError("zero non-NA points");let r=V(f.x,f.y);return(s,c=0)=>I(f.x,f.y,r,s,c)}let a=q(o,l,n,e);return(f,r=0)=>H(a,f,r)}function V(o,l){let t=o.length;if(t<2)throw new RangeError("length(m) must be at least two");let n=Array.from({length:t-1},(a,f)=>(l[f+1]-l[f])/(o[f+1]-o[f])),e=Array.from({length:t},(a,f)=>f===0?n[0]:f===t-1?n[t-2]:(n[f-1]+n[f])/2);for(let a=0;a<t-1;a++){let f=n[a];if(f===0){e[a]=0,e[a+1]=0;continue}let r=e[a]/f,s=e[a+1]/f,c=2*r+s-3,i=r+2*s-3;if(c>0&&i>0&&r*(c+i)<c*c){let p=3*f/Math.sqrt(r*r+s*s);e[a]=p*r,e[a+1]=p*s}}return e}function I(o,l,t,n,e){let a=C(e),f=o.length;return Array.from(n,r=>{if(Number.isNaN(r))return NaN;let s=0,c=f;for(;s<c;){let A=s+c>>1;o[A]<=r?s=A+1:c=A}let i=s;if(i===0||i===f){let A=i===0?0:f-1;return a===0?l[A]+t[A]*(r-o[A]):a===1?t[A]:0}let p=o[i-1],d=o[i]-p,h=(r-p)/d,m=h-1,g=l[i-1],u=l[i],w=t[i-1],y=t[i],b=(u-g)/d;switch(a){case 0:{let A=h*h*(3-2*h);return g*(1-A)+d*w*(h*m*m)+u*A+d*y*(h*h*m)}case 1:return b*(-6*h*m)+w*(m*(3*h-1))+y*(h*(3*h-2));case 2:return(b*(6-12*h)+w*(6*h-4)+y*(6*h-2))/d;default:return(-12*b+6*w+6*y)/(d*d)}})}function W(o,l,t){let n=o.length;if(l.length!==n||t.length!==n)throw new RangeError("'x', 'y' and 'm' must have the same length");let e=Array.from({length:n},(s,c)=>c).sort((s,c)=>o[s]-o[c]),a=e.map(s=>o[s]),f=e.map(s=>l[s]),r=e.map(s=>t[s]);for(let s=1;s<n;s++)if(!(a[s]-a[s-1]>0))throw new RangeError("'x' must be *strictly* increasing (non - NA)");return(s,c=0)=>I(a,f,r,s,c)}function Z(o,l,t){let n=Array.from(o),e=Array.from(l),a=n.length;if(e.length!==a)throw new RangeError("'xi' and 'yi' must have the same length");let f=Array.from(t),r=Math.min(...n),s=Math.max(...n);if(f.some(i=>i<r||i>s))throw new RangeError("Some interpolation points outside the nodes.");let c=n.map((i,p)=>{let d=1;for(let h=0;h<a;h++)h!==p&&(d*=i-n[h]);return 1/d});return f.map(i=>{let p=0,d=0,h=n.lastIndexOf(i);if(h>=0)return e[h];for(let m=0;m<a;m++){let g=i-n[m],u=c[m]/g;p+=u*e[m],d+=u}return p/d})}function tt(o,l,t,n){let e=Array.from(o),a=Array.from(l),f=Array.from(t),r=e.length;if(a.length!==r||f.length!==r)throw new RangeError("'xi', 'yi' and 'di' must have the same length");let s=e.flatMap(h=>[h,h]),c=2*r,i=a.flatMap(h=>[h,h]),p=[i[0]],d=i.slice();for(let h=1;h<c;h++){let m=[];for(let g=0;g<c-h;g++)h===1&&s[g+1]===s[g]?m.push(f[g>>1]):m.push((d[g+1]-d[g])/(s[g+h]-s[g]));p.push(m[0]),d=m}return Array.from(n,h=>{let m=p[c-1];for(let g=c-2;g>=0;g--)m=m*(h-s[g])+p[g];return m})}function nt(o,l,t,n=[],e={}){let a=e.method??"rk4";if(a!=="euler"&&a!=="rk2"&&a!=="rk4")throw new RangeError(`unknown method '${String(a)}'`);let f=[...n],r=o.length,s=(d,h)=>{let m=Array.from(t(d,h,f));if(m.length!==r)throw new RangeError(`The number of derivatives returned by func() (${m.length}) must equal the length of the initial conditions vector (${r})`);return m},c=(d,h,m)=>d.map((g,u)=>g+h*m[u]),i=[...o],p=[];if(l.length===0)return p;p.push([l[0],...i]);for(let d=1;d<l.length;d++){let h=l[d-1],m=l[d]-h,g=s(h,i);if(a==="euler")i=c(i,m,g);else if(a==="rk2"){let u=s(h+m,c(i,m,g));i=i.map((w,y)=>w+m*(.5*g[y]+.5*u[y]))}else{let u=s(h+m/2,c(i,m/2,g)),w=s(h+m/2,c(i,m/2,u)),y=s(h+m,c(i,m,w));i=i.map((b,A)=>b+m/6*(g[A]+2*u[A]+2*w[A]+y[A]))}p.push([l[d],...i])}return p}function _(o,l,t){let n=l.eps??1e-4,e=l.d??t,a=l.zeroTol??Math.sqrt(Number.EPSILON/7e-7),f=l.r??4;if(!(Number.isInteger(f)&&f>=1))throw new RangeError("'r' must be a positive integer");return{eps:n,r:f,h0:o.map(r=>Math.abs(e*r)+(Math.abs(r)<a?n:0))}}function x(o){let l=[...o];for(let t=1;t<l.length;t++){let n=4**t;for(let e=0;e<l.length-t;e++)l[e]=(l[e+1]*n-l[e])/(n-1)}return l[0]}function N(o,l,t){let n=[...o];return n[l]=n[l]+t,n}function L(o){let l=o.method??"Richardson";if(l!=="Richardson"&&l!=="simple")throw new RangeError(`unknown method "${String(l)}" (expected "Richardson" or "simple")`);return l}function rt(o,l,t={}){let n=[...l],e=n.length;if(L(t)==="simple"){let s=t.eps??1e-4,c=o([...n]);return n.map((i,p)=>(o(N(n,p,s))-c)/s)}let{r:a,h0:f}=_(n,t,1e-4),r=[];for(let s=0;s<e;s++){let c=[],i=f[s];for(let p=0;p<a;p++){if(p>0&&Math.abs(c[p-1])<1e-20?c.push(0):c.push((o(N(n,s,i))-o(N(n,s,-i)))/(2*i)),Number.isNaN(c[p]))throw new RangeError(`func returned NaN at step ${i} from x`);i/=2}r.push(x(c))}return r}function et(o,l,t={}){let n=[...l],e=n.length,a=Array.from(o([...n])),f=a.map(()=>new Array(e).fill(NaN));if(L(t)==="simple"){let c=t.eps??1e-4;for(let i=0;i<e;i++){let p=o(N(n,i,c));a.forEach((d,h)=>f[h][i]=(p[h]-d)/c)}return f}let{r,h0:s}=_(n,t,1e-4);for(let c=0;c<e;c++){let i=a.map(()=>[]),p=s[c];for(let d=0;d<r;d++){let h=o(N(n,c,p)),m=o(N(n,c,-p));a.forEach((g,u)=>i[u].push((h[u]-m[u])/(2*p))),p/=2}a.forEach((d,h)=>f[h][c]=x(i[h]))}return f}function ot(o,l,t={}){if((t.method??"Richardson")!=="Richardson")throw new RangeError('hessian supports only method "Richardson"');let n=[...l],e=n.length,{r:a,h0:f}=_(n,t,.1),r=o([...n]),s=[];for(let i=0;i<e;i++){let p=[],d=f[i];for(let h=0;h<a;h++)p.push((o(N(n,i,d))-2*r+o(N(n,i,-d)))/d**2),d/=2;s.push(x(p))}let c=n.map(()=>new Array(e).fill(NaN));for(let i=0;i<e;i++){c[i][i]=s[i];for(let p=0;p<i;p++){let d=[],h=f[i],m=f[p];for(let g=0;g<a;g++){let u=N(N(n,i,h),p,m),w=N(N(n,i,-h),p,-m);d.push((o(u)-2*r+o(w)-s[i]*h**2-s[p]*m**2)/(2*h*m)),h/=2,m/=2}c[i][p]=c[p][i]=x(d)}}return c}export{P as approx,Z as barylag,rt as grad,tt as hermiteInterp,ot as hessian,$ as integrate,et as jacobian,nt as ode,O as optim,F as optimHess,T as optimize,Q as spline,U as splinefun,W as splinefunH,D as uniroot};
|
|
1
|
+
/*! rStats.js 0.14.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
|
|
2
|
+
import{a as $,b as T,c as D,d as F,e as O}from"./chunks/chunk-ACE64PMM.js";import"./chunks/chunk-NTETWLP3.js";import{a as k,f as j}from"./chunks/chunk-Q4JF4QHS.js";import"./chunks/chunk-A76XBA3D.js";import{f as S}from"./chunks/chunk-WM33ADZV.js";import"./chunks/chunk-SZ357HRC.js";import"./chunks/chunk-XCAMWVNO.js";function M(o,l,t="mean"){if(o.length!==l.length)throw new RangeError("'x' and 'y' lengths differ");let n=[];for(let r=0;r<o.length;r++)!Number.isNaN(o[r])&&!Number.isNaN(l[r])&&n.push(r);n.sort((r,s)=>o[r]-o[s]);let e=typeof t=="function"?t:t==="min"?r=>Math.min(...r):t==="max"?r=>Math.max(...r):S,a=[],f=[];for(let r=0;r<n.length;){let s=o[n[r]],c=r+1;for(;c<n.length&&o[n[c]]===s;)c++;a.push(s),f.push(c-r===1?l[n[r]]:e(n.slice(r,c).map(i=>l[i]))),r=c}return{x:a,y:f}}function X(o,l,t,n){let e=(n-o[t])/(o[t+1]-o[t]);return l[t]+(l[t+1]-l[t])*e}function J(o,l,t){let n=(e,a)=>e===0?0:e*a;return n(1-t,o[l])+n(t,o[l+1])}function P(o,l,t={}){let{method:n="linear",n:e=50,f:a=0,rule:f=1,ties:r="mean"}=t,s=M(o,l,r),c=s.x.length;if(c<=1&&n==="linear")throw new RangeError("need at least two non-NA values to interpolate");if(c===0)throw new RangeError("zero non-NA points");if(n==="constant"&&!(a>=0&&a<=1))throw new RangeError("approx(): invalid f value");let[i,p]=typeof f=="number"?[f,f]:f,d=t.yleft??(i===1?NaN:s.y[0]),h=t.yright??(p===1?NaN:s.y[c-1]),m;if(t.xout!==void 0)m=Array.from(t.xout);else{if(e<=0)throw new RangeError("'approx' requires n >= 1");m=k(s.x[0],s.x[c-1],e)}let g=s.x,u=s.y,w=j(m,g),y=m.map((b,A)=>{let R=w[A];if(Number.isNaN(R))return NaN;if(R===0)return d;let E=R-1;return b===g[E]?u[E]:R===c?h:n==="linear"?X(g,u,E,b):J(u,E,a)});return{x:m,y}}function v(o,l){let t=o.length,n=new Array(t).fill(0),e=new Array(t).fill(0),a=new Array(t).fill(0);if(t<2)return{b:n,c:e,d:a};if(t<3)return n[0]=(l[1]-l[0])/(o[1]-o[0]),n[1]=n[0],{b:n,c:e,d:a};let f=t-1;a[0]=o[1]-o[0],e[1]=(l[1]-l[0])/a[0];for(let r=1;r<f;r++)a[r]=o[r+1]-o[r],n[r]=2*(a[r-1]+a[r]),e[r+1]=(l[r+1]-l[r])/a[r],e[r]=e[r+1]-e[r];n[0]=-a[0],n[f]=-a[t-2],e[0]=0,e[f]=0,t>3&&(e[0]=e[2]/(o[3]-o[1])-e[1]/(o[2]-o[0]),e[f]=e[t-2]/(o[f]-o[t-3])-e[t-3]/(o[t-2]-o[t-4]),e[0]=e[0]*a[0]*a[0]/(o[3]-o[0]),e[f]=-e[f]*a[t-2]*a[t-2]/(o[f]-o[t-4]));for(let r=1;r<t;r++){let s=a[r-1]/n[r-1];n[r]=n[r]-s*a[r-1],e[r]=e[r]-s*e[r-1]}e[f]=e[f]/n[f];for(let r=t-2;r>=0;r--)e[r]=(e[r]-a[r]*e[r+1])/n[r];n[f]=(l[f]-l[t-2])/a[t-2]+a[t-2]*(e[t-2]+2*e[f]);for(let r=0;r<f;r++)n[r]=(l[r+1]-l[r])/a[r]-a[r]*(e[r+1]+2*e[r]),a[r]=(e[r+1]-e[r])/a[r],e[r]=3*e[r];return e[f]=3*e[f],a[f]=a[t-2],{b:n,c:e,d:a}}function z(o,l,t){let n=o.length,e=new Array(n).fill(0),a=new Array(n).fill(0),f=new Array(n).fill(0);for(let r=0;r<n-1;r++){let s=o[r+1]-o[r];e[r]=(l[r+1]-l[r])/s-s*(t[r+1]+2*t[r]),a[r]=3*t[r],f[r]=(t[r+1]-t[r])/s}return{b:e,c:a,d:f}}function Y(o,l){let t=o.length;if(t<3)return v(o,l);let n=Array.from({length:t-1},(c,i)=>o[i+1]-o[i]),e=n.map((c,i)=>(l[i+1]-l[i])/c),a=new Array(t).fill(0),f=new Array(t).fill(0);for(let c=1;c<t-1;c++)a[c]=2*(n[c-1]+n[c]),f[c]=e[c]-e[c-1];for(let c=2;c<t-1;c++){let i=n[c-1]/a[c-1];a[c]=a[c]-i*n[c-1],f[c]=f[c]-i*f[c-1]}let r=new Array(t).fill(0);r[t-2]=f[t-2]/a[t-2];for(let c=t-3;c>=1;c--)r[c]=(f[c]-n[c]*r[c+1])/a[c];let s=z(o,l,r);return s.b[t-1]=e[t-2]+n[t-2]*r[t-2],s}function B(o,l){let t=o.length;if(l[0]!==l[t-1])throw new RangeError("periodic spline needs y[1] == y[n]");if(t<3)return{b:new Array(t).fill(0),c:new Array(t).fill(0),d:new Array(t).fill(0)};let n=t-1,e=Array.from({length:n},(u,w)=>o[w+1]-o[w]),a=e.map((u,w)=>(l[w+1]-l[w])/u),f=u=>u===0?n-1:u-1,r=Array.from({length:n},(u,w)=>2*(e[f(w)]+e[w])),s=Array.from({length:n},(u,w)=>a[w]-a[f(w)]),c=e.slice(),i=new Array(n).fill(0);i[0]=e[n-1],i[n-2]=i[n-2]+e[n-2];let p=i[0],d=r[n-1],h=s[n-1];for(let u=0;u<n-1;u++){if(u+1<n-1){let y=e[u]/r[u];r[u+1]=r[u+1]-y*c[u],i[u+1]=i[u+1]-y*i[u],s[u+1]=s[u+1]-y*s[u]}let w=p/r[u];d-=w*i[u],h-=w*s[u],u+1<n-1&&(p=(u+1===n-2?e[n-2]:0)-w*c[u])}let m=new Array(t).fill(0);m[n-1]=h/d;for(let u=n-2;u>=0;u--){let w=s[u]-i[u]*m[n-1]-(u<n-2?c[u]*m[u+1]:0);m[u]=w/r[u]}m[t-1]=m[0];let g=z(o,l,m);return g.b[t-1]=g.b[0],g.c[t-1]=g.c[0],g.d[t-1]=g.d[0],g}function G(o,l){let t=o.length,{b:n,c:e,d:a}=v(o,l);if(t<2)return{b:n,c:e,d:a};let f=Array.from({length:t-1},(s,c)=>(l[c+1]-l[c])/(o[c+1]-o[c]));for(let s=0;s<t;s++){let c=f[s===0?0:s-1],i=f[s===t-1?t-2:s],p=Math.min(Math.abs(c),Math.abs(i)),d=c*i>0?i>0:n[s]>=0;n[s]=d?Math.min(Math.max(0,n[s]),3*p):Math.max(Math.min(0,n[s]),-3*p)}for(let s=0;s<t-1;s++){let c=o[s+1]-o[s],i=(l[s+1]-l[s])/c;e[s]=(3*i-2*n[s]-n[s+1])/c,a[s]=(n[s]+n[s+1]-2*i)/(c*c)}let r=o[t-1]-o[t-2];return e[t-1]=(n[t-2]+2*n[t-1]-3*(l[t-1]-l[t-2])/r)/r,a[t-1]=a[t-2],{b:n,c:e,d:a}}function q(o,l,t,n){let e=M(o,l,n),a=e.x.length;if(a===0)throw new RangeError("zero non-NA points");t==="periodic"&&e.y[a-1]!==e.y[0]&&(e.y[a-1]=e.y[0]),t==="hyman"&&K(e.y);let f=t==="fmm"?v(e.x,e.y):t==="natural"?Y(e.x,e.y):t==="periodic"?B(e.x,e.y):t==="hyman"?G(e.x,e.y):(()=>{throw new RangeError(`invalid spline method '${String(t)}'`)})();return{method:t,...e,...f}}function K(o){let l=!0,t=!0;for(let n=1;n<o.length;n++){let e=o[n]-o[n-1];e>=0||(l=!1),e<=0||(t=!1)}if(!l&&!t)throw new RangeError("'y' must be increasing or decreasing")}function C(o){let l=Math.trunc(o);if(!(l>=0&&l<=3))throw new RangeError("'deriv' must be between 0 and 3");return l}function H(o,l,t){let n=C(t),{x:e,y:a,b:f,c:r,d:s,method:c}=o,i=e.length,p=c==="natural",d=e[i-1]-e[0],h=0;return Array.from(l,m=>{let g=m;if(c==="periodic"&&i>1){let y=(g-e[0])%d;y<0&&(y+=d),g=e[0]+y}if(p&&n>0&&g<=e[0])return n===1?f[0]:0;if(!(e[h]<=g&&(h===i-1||g<=e[h+1]))){let y=0,b=i;for(;b-y>1;){let A=y+b>>1;e[A]<=g?y=A:b=A}h=y}let u=g-e[h],w=p&&g<e[0]?0:s[h];switch(n){case 0:return a[h]+u*(f[h]+u*(r[h]+u*w));case 1:return f[h]+u*(2*r[h]+u*(3*w));case 2:return 2*r[h]+u*(6*w);default:return 6*w}})}function Q(o,l,t={}){let{method:n="fmm",ties:e="mean"}=t,a=q(o,l,n,e),f;if(t.xout!==void 0)f=Array.from(t.xout);else{let r=a.x.length,s=t.n??3*r;if(s<=0)throw new RangeError("'spline' requires n >= 1");f=k(t.xmin??a.x[0],t.xmax??a.x[r-1],s)}return{x:f,y:H(a,f,0)}}function U(o,l,t={}){let{method:n="fmm",ties:e="mean"}=t;if(n==="monoH.FC"){let f=M(o,l,e);if(f.x.length===0)throw new RangeError("zero non-NA points");let r=V(f.x,f.y);return(s,c=0)=>I(f.x,f.y,r,s,c)}let a=q(o,l,n,e);return(f,r=0)=>H(a,f,r)}function V(o,l){let t=o.length;if(t<2)throw new RangeError("length(m) must be at least two");let n=Array.from({length:t-1},(a,f)=>(l[f+1]-l[f])/(o[f+1]-o[f])),e=Array.from({length:t},(a,f)=>f===0?n[0]:f===t-1?n[t-2]:(n[f-1]+n[f])/2);for(let a=0;a<t-1;a++){let f=n[a];if(f===0){e[a]=0,e[a+1]=0;continue}let r=e[a]/f,s=e[a+1]/f,c=2*r+s-3,i=r+2*s-3;if(c>0&&i>0&&r*(c+i)<c*c){let p=3*f/Math.sqrt(r*r+s*s);e[a]=p*r,e[a+1]=p*s}}return e}function I(o,l,t,n,e){let a=C(e),f=o.length;return Array.from(n,r=>{if(Number.isNaN(r))return NaN;let s=0,c=f;for(;s<c;){let A=s+c>>1;o[A]<=r?s=A+1:c=A}let i=s;if(i===0||i===f){let A=i===0?0:f-1;return a===0?l[A]+t[A]*(r-o[A]):a===1?t[A]:0}let p=o[i-1],d=o[i]-p,h=(r-p)/d,m=h-1,g=l[i-1],u=l[i],w=t[i-1],y=t[i],b=(u-g)/d;switch(a){case 0:{let A=h*h*(3-2*h);return g*(1-A)+d*w*(h*m*m)+u*A+d*y*(h*h*m)}case 1:return b*(-6*h*m)+w*(m*(3*h-1))+y*(h*(3*h-2));case 2:return(b*(6-12*h)+w*(6*h-4)+y*(6*h-2))/d;default:return(-12*b+6*w+6*y)/(d*d)}})}function W(o,l,t){let n=o.length;if(l.length!==n||t.length!==n)throw new RangeError("'x', 'y' and 'm' must have the same length");let e=Array.from({length:n},(s,c)=>c).sort((s,c)=>o[s]-o[c]),a=e.map(s=>o[s]),f=e.map(s=>l[s]),r=e.map(s=>t[s]);for(let s=1;s<n;s++)if(!(a[s]-a[s-1]>0))throw new RangeError("'x' must be *strictly* increasing (non - NA)");return(s,c=0)=>I(a,f,r,s,c)}function Z(o,l,t){let n=Array.from(o),e=Array.from(l),a=n.length;if(e.length!==a)throw new RangeError("'xi' and 'yi' must have the same length");let f=Array.from(t),r=Math.min(...n),s=Math.max(...n);if(f.some(i=>i<r||i>s))throw new RangeError("Some interpolation points outside the nodes.");let c=n.map((i,p)=>{let d=1;for(let h=0;h<a;h++)h!==p&&(d*=i-n[h]);return 1/d});return f.map(i=>{let p=0,d=0,h=n.lastIndexOf(i);if(h>=0)return e[h];for(let m=0;m<a;m++){let g=i-n[m],u=c[m]/g;p+=u*e[m],d+=u}return p/d})}function tt(o,l,t,n){let e=Array.from(o),a=Array.from(l),f=Array.from(t),r=e.length;if(a.length!==r||f.length!==r)throw new RangeError("'xi', 'yi' and 'di' must have the same length");let s=e.flatMap(h=>[h,h]),c=2*r,i=a.flatMap(h=>[h,h]),p=[i[0]],d=i.slice();for(let h=1;h<c;h++){let m=[];for(let g=0;g<c-h;g++)h===1&&s[g+1]===s[g]?m.push(f[g>>1]):m.push((d[g+1]-d[g])/(s[g+h]-s[g]));p.push(m[0]),d=m}return Array.from(n,h=>{let m=p[c-1];for(let g=c-2;g>=0;g--)m=m*(h-s[g])+p[g];return m})}function nt(o,l,t,n=[],e={}){let a=e.method??"rk4";if(a!=="euler"&&a!=="rk2"&&a!=="rk4")throw new RangeError(`unknown method '${String(a)}'`);let f=[...n],r=o.length,s=(d,h)=>{let m=Array.from(t(d,h,f));if(m.length!==r)throw new RangeError(`The number of derivatives returned by func() (${m.length}) must equal the length of the initial conditions vector (${r})`);return m},c=(d,h,m)=>d.map((g,u)=>g+h*m[u]),i=[...o],p=[];if(l.length===0)return p;p.push([l[0],...i]);for(let d=1;d<l.length;d++){let h=l[d-1],m=l[d]-h,g=s(h,i);if(a==="euler")i=c(i,m,g);else if(a==="rk2"){let u=s(h+m,c(i,m,g));i=i.map((w,y)=>w+m*(.5*g[y]+.5*u[y]))}else{let u=s(h+m/2,c(i,m/2,g)),w=s(h+m/2,c(i,m/2,u)),y=s(h+m,c(i,m,w));i=i.map((b,A)=>b+m/6*(g[A]+2*u[A]+2*w[A]+y[A]))}p.push([l[d],...i])}return p}function _(o,l,t){let n=l.eps??1e-4,e=l.d??t,a=l.zeroTol??Math.sqrt(Number.EPSILON/7e-7),f=l.r??4;if(!(Number.isInteger(f)&&f>=1))throw new RangeError("'r' must be a positive integer");return{eps:n,r:f,h0:o.map(r=>Math.abs(e*r)+(Math.abs(r)<a?n:0))}}function x(o){let l=[...o];for(let t=1;t<l.length;t++){let n=4**t;for(let e=0;e<l.length-t;e++)l[e]=(l[e+1]*n-l[e])/(n-1)}return l[0]}function N(o,l,t){let n=[...o];return n[l]=n[l]+t,n}function L(o){let l=o.method??"Richardson";if(l!=="Richardson"&&l!=="simple")throw new RangeError(`unknown method "${String(l)}" (expected "Richardson" or "simple")`);return l}function rt(o,l,t={}){let n=[...l],e=n.length;if(L(t)==="simple"){let s=t.eps??1e-4,c=o([...n]);return n.map((i,p)=>(o(N(n,p,s))-c)/s)}let{r:a,h0:f}=_(n,t,1e-4),r=[];for(let s=0;s<e;s++){let c=[],i=f[s];for(let p=0;p<a;p++){if(p>0&&Math.abs(c[p-1])<1e-20?c.push(0):c.push((o(N(n,s,i))-o(N(n,s,-i)))/(2*i)),Number.isNaN(c[p]))throw new RangeError(`func returned NaN at step ${i} from x`);i/=2}r.push(x(c))}return r}function et(o,l,t={}){let n=[...l],e=n.length,a=Array.from(o([...n])),f=a.map(()=>new Array(e).fill(NaN));if(L(t)==="simple"){let c=t.eps??1e-4;for(let i=0;i<e;i++){let p=o(N(n,i,c));a.forEach((d,h)=>f[h][i]=(p[h]-d)/c)}return f}let{r,h0:s}=_(n,t,1e-4);for(let c=0;c<e;c++){let i=a.map(()=>[]),p=s[c];for(let d=0;d<r;d++){let h=o(N(n,c,p)),m=o(N(n,c,-p));a.forEach((g,u)=>i[u].push((h[u]-m[u])/(2*p))),p/=2}a.forEach((d,h)=>f[h][c]=x(i[h]))}return f}function ot(o,l,t={}){if((t.method??"Richardson")!=="Richardson")throw new RangeError('hessian supports only method "Richardson"');let n=[...l],e=n.length,{r:a,h0:f}=_(n,t,.1),r=o([...n]),s=[];for(let i=0;i<e;i++){let p=[],d=f[i];for(let h=0;h<a;h++)p.push((o(N(n,i,d))-2*r+o(N(n,i,-d)))/d**2),d/=2;s.push(x(p))}let c=n.map(()=>new Array(e).fill(NaN));for(let i=0;i<e;i++){c[i][i]=s[i];for(let p=0;p<i;p++){let d=[],h=f[i],m=f[p];for(let g=0;g<a;g++){let u=N(N(n,i,h),p,m),w=N(N(n,i,-h),p,-m);d.push((o(u)-2*r+o(w)-s[i]*h**2-s[p]*m**2)/(2*h*m)),h/=2,m/=2}c[i][p]=c[p][i]=x(d)}}return c}export{P as approx,Z as barylag,rt as grad,tt as hermiteInterp,ot as hessian,$ as integrate,et as jacobian,nt as ode,O as optim,F as optimHess,T as optimize,Q as spline,U as splinefun,W as splinefunH,D as uniroot};
|