@numero-uno-jpn/rstats 0.12.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 +76 -0
- package/README.ja.md +26 -17
- package/README.md +25 -16
- package/THIRD_PARTY_NOTICES.md +2 -2
- package/dist/chunks/{chunk-VQHEOBTM.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-LEIH4U5X.js → chunk-7T74KLE5.js} +2 -2
- package/dist/chunks/{chunk-XJQKSR52.js → chunk-A76XBA3D.js} +1 -1
- package/dist/chunks/chunk-ACE64PMM.js +3 -0
- package/dist/chunks/chunk-DCGBYO44.js +2 -0
- package/dist/chunks/chunk-DWNGNTS6.js +2 -0
- package/dist/chunks/chunk-FBDZ6B2G.js +2 -0
- package/dist/chunks/chunk-IBJ7RI44.js +2 -0
- package/dist/chunks/chunk-IGSR4GIF.js +2 -0
- package/dist/chunks/{chunk-6BH65HGN.js → chunk-NTETWLP3.js} +1 -1
- package/dist/chunks/chunk-Q4JF4QHS.js +2 -0
- package/dist/chunks/chunk-RZIWVCHO.js +2 -0
- package/dist/chunks/chunk-SD7ML5PE.js +2 -0
- package/dist/chunks/chunk-SZ357HRC.js +3 -0
- package/dist/chunks/chunk-WM33ADZV.js +2 -0
- package/dist/chunks/{chunk-OX3SBG5X.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-ZUESNU7W.js +2 -0
- package/dist/data/grouping.js +11 -4
- package/dist/descriptive/basic.js +57 -49
- package/dist/descriptive/cov.js +7 -2
- package/dist/descriptive/factanal.d.ts +16 -0
- package/dist/descriptive/factanal.js +26 -0
- package/dist/descriptive/hist.d.ts +8 -2
- package/dist/descriptive/hist.js +10 -2
- package/dist/descriptive/quantile.d.ts +8 -3
- package/dist/descriptive/quantile.js +10 -6
- package/dist/descriptive/table.d.ts +7 -5
- package/dist/descriptive/table.js +39 -22
- package/dist/descriptive.js +2 -2
- package/dist/distributions/beta.js +17 -0
- package/dist/distributions/binomial.js +3 -0
- package/dist/distributions/gamma.js +7 -0
- package/dist/distributions.js +2 -2
- package/dist/entries/mixed.d.ts +3 -1
- package/dist/entries/mixed.js +4 -1
- package/dist/entries/tests.d.ts +1 -1
- package/dist/htest/agreement.js +7 -2
- package/dist/htest/groups.js +7 -3
- package/dist/htest/mcnemarTest.js +6 -2
- package/dist/htest/pairwise.js +6 -3
- package/dist/htest/polycor.js +5 -3
- package/dist/htest/tTest.d.ts +3 -2
- package/dist/htest/tTest.js +6 -3
- package/dist/htest/trendTests.js +10 -5
- package/dist/internal/fround.d.ts +12 -0
- package/dist/internal/fround.js +89 -0
- package/dist/internal/levels.d.ts +11 -0
- package/dist/internal/levels.js +48 -0
- package/dist/internal/summary.d.ts +19 -1
- package/dist/internal/summary.js +69 -8
- package/dist/linalg/balance.d.ts +21 -0
- package/dist/linalg/balance.js +191 -0
- package/dist/linalg/eigen.d.ts +1 -1
- package/dist/linalg/eigen.js +8 -2
- package/dist/linalg/expm.d.ts +1 -11
- package/dist/linalg/expm.js +2 -158
- package/dist/linalg/kappa.d.ts +6 -2
- package/dist/linalg/kappa.js +16 -7
- package/dist/linalg/lu.d.ts +13 -2
- package/dist/linalg/lu.js +17 -3
- package/dist/linalg/qr.d.ts +4 -1
- package/dist/linalg/qr.js +2 -2
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -3
- package/dist/models/aovEz.js +6 -4
- package/dist/models/coxph.js +5 -2
- package/dist/models/glm.d.ts +4 -1
- package/dist/models/glmFamily.d.ts +1 -1
- package/dist/models/glmFamily.js +24 -2
- 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/mauchly.js +2 -1
- 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/modelFrame.js +2 -1
- package/dist/models/modelMatrix.d.ts +10 -3
- package/dist/models/modelMatrix.js +23 -2
- package/dist/models/survival.js +5 -1
- package/dist/numerics/integrate.d.ts +1 -1
- package/dist/numerics/integrate.js +13 -3
- package/dist/numerics/interp.d.ts +1 -1
- package/dist/numerics/interp.js +3 -0
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +14 -14
- package/dist/special/beta.js +10 -20
- 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-3VMBBQLV.js +0 -3
- package/dist/chunks/chunk-4OKAZJJG.js +0 -3
- package/dist/chunks/chunk-ATC4F4BX.js +0 -2
- package/dist/chunks/chunk-EDH53DXN.js +0 -2
- package/dist/chunks/chunk-EZ2KD5NA.js +0 -2
- package/dist/chunks/chunk-GSPOO2G3.js +0 -2
- package/dist/chunks/chunk-K7AZ65H7.js +0 -2
- package/dist/chunks/chunk-SGZQDJRR.js +0 -2
- package/dist/chunks/chunk-UH2N3ZQW.js +0 -2
- package/dist/chunks/chunk-UV2MZYDQ.js +0 -2
- package/dist/chunks/chunk-WJQZZYOI.js +0 -2
- package/dist/chunks/chunk-WKEFHOFR.js +0 -2
- package/dist/chunks/chunk-WXC25OPJ.js +0 -2
|
@@ -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
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// `dropUnusedLevels` removes the levels of the columns with `levels` given that have no row left (R's
|
|
9
9
|
// drop.unused.levels = TRUE, used by lm and aov); it does not apply to boolean columns. Functions that group rows by
|
|
10
10
|
// a variable use the levels present (`presentLevels`).
|
|
11
|
+
import { levelText } from "../internal/levels.js";
|
|
11
12
|
/** Comparison of strings by code point (not by UTF-16 code unit) */
|
|
12
13
|
export function compareCodePoints(a, b) {
|
|
13
14
|
const ia = a[Symbol.iterator]();
|
|
@@ -41,7 +42,7 @@ function convert(name, col, levels) {
|
|
|
41
42
|
const values = vals.map((x) => (x === null ? NaN : x));
|
|
42
43
|
return { v: { kind: "numeric", values }, missing: values.map((x) => Number.isNaN(x)) };
|
|
43
44
|
}
|
|
44
|
-
const str = (x) => x === null || (typeof x === "number" && Number.isNaN(x)) ? null : typeof x === "boolean" ? (x ? "TRUE" : "FALSE") :
|
|
45
|
+
const str = (x) => x === null || (typeof x === "number" && Number.isNaN(x)) ? null : typeof x === "boolean" ? (x ? "TRUE" : "FALSE") : levelText(x);
|
|
45
46
|
const labels = vals.map(str);
|
|
46
47
|
let lev;
|
|
47
48
|
if (levels !== undefined)
|
|
@@ -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/models/survival.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// for the weights S(t-)^rho; Brookmeyer and Crowley (1982) for the confidence limits of the median.
|
|
9
9
|
import { pchisq } from "../distributions/chisq.js";
|
|
10
10
|
import { qnorm } from "../distributions/normal.js";
|
|
11
|
+
import { levelText, numberLevels } from "../internal/levels.js";
|
|
11
12
|
import { solve } from "../linalg/solve.js";
|
|
12
13
|
const isMissing = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
|
|
13
14
|
/** Observations with no missing value, the sorted labels and the group index of each */
|
|
@@ -29,6 +30,9 @@ function prepare(time, status, group) {
|
|
|
29
30
|
throw new RangeError("no observations without missing values");
|
|
30
31
|
let labels = [];
|
|
31
32
|
const index = new Map();
|
|
33
|
+
// numeric labels with the same 15-digit text are one group, as in R's factor()
|
|
34
|
+
if (group !== undefined)
|
|
35
|
+
group = numberLevels(group);
|
|
32
36
|
if (group !== undefined) {
|
|
33
37
|
labels = Array.from(new Set(keep.map((i) => group[i]))).sort((a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0);
|
|
34
38
|
labels.forEach((l, k) => index.set(l, k));
|
|
@@ -39,7 +43,7 @@ function prepare(time, status, group) {
|
|
|
39
43
|
group: group === undefined ? 0 : index.get(group[i]),
|
|
40
44
|
}));
|
|
41
45
|
obs.sort((a, b) => a.time - b.time);
|
|
42
|
-
return { obs, labels: labels.map((l) => `group=${
|
|
46
|
+
return { obs, labels: labels.map((l) => `group=${levelText(l)}`) };
|
|
43
47
|
}
|
|
44
48
|
/**
|
|
45
49
|
* Test of the difference between survival curves: the G-rho family of Harrington and Fleming, the log-rank test for
|
|
@@ -56,7 +56,7 @@ export interface OptimizeOptions {
|
|
|
56
56
|
/**
|
|
57
57
|
* Minimum (or maximum) of a function of one variable on an interval, by Brent's golden-section and parabolic
|
|
58
58
|
* search. Equivalent to R's `optimize()`. `optimum` is the location (R's `minimum`/`maximum`) and `objective` the
|
|
59
|
-
* function there. `lower` must be less than `upper`, as in R.
|
|
59
|
+
* function there. `lower` and `upper` must be finite and `lower` less than `upper`, as in R.
|
|
60
60
|
*
|
|
61
61
|
* @example
|
|
62
62
|
* ```ts
|
|
@@ -62,7 +62,7 @@ export function integrate(f, lower, upper, options = {}) {
|
|
|
62
62
|
/**
|
|
63
63
|
* Minimum (or maximum) of a function of one variable on an interval, by Brent's golden-section and parabolic
|
|
64
64
|
* search. Equivalent to R's `optimize()`. `optimum` is the location (R's `minimum`/`maximum`) and `objective` the
|
|
65
|
-
* function there. `lower` must be less than `upper`, as in R.
|
|
65
|
+
* function there. `lower` and `upper` must be finite and `lower` less than `upper`, as in R.
|
|
66
66
|
*
|
|
67
67
|
* @example
|
|
68
68
|
* ```ts
|
|
@@ -74,6 +74,11 @@ export function integrate(f, lower, upper, options = {}) {
|
|
|
74
74
|
export function optimize(f, lower, upper, options = {}) {
|
|
75
75
|
const maximum = options.maximum ?? false;
|
|
76
76
|
const tol = options.tol ?? TOL;
|
|
77
|
+
// R checks the ends before calling f, lower first
|
|
78
|
+
if (!Number.isFinite(lower))
|
|
79
|
+
throw new RangeError("invalid 'xmin' value");
|
|
80
|
+
if (!Number.isFinite(upper))
|
|
81
|
+
throw new RangeError("invalid 'xmax' value");
|
|
77
82
|
if (!(lower < upper))
|
|
78
83
|
throw new RangeError("'xmin' not less than 'xmax'");
|
|
79
84
|
const r = localMin(maximum ? (x) => -f(x) : f, lower, upper, tol);
|
|
@@ -138,14 +143,14 @@ export function uniroot(f, lower, upper, options = {}) {
|
|
|
138
143
|
}
|
|
139
144
|
else if (extend) {
|
|
140
145
|
let d = step0(lower);
|
|
141
|
-
while (sig * fLo > 0) {
|
|
146
|
+
while (sig * fLo > 0 && Number.isFinite(lower)) {
|
|
142
147
|
count();
|
|
143
148
|
lower -= d;
|
|
144
149
|
fLo = f(lower);
|
|
145
150
|
d *= 2;
|
|
146
151
|
}
|
|
147
152
|
d = step0(upper);
|
|
148
|
-
while (sig * fUp < 0) {
|
|
153
|
+
while (sig * fUp < 0 && Number.isFinite(upper)) {
|
|
149
154
|
count();
|
|
150
155
|
upper += d;
|
|
151
156
|
fUp = f(upper);
|
|
@@ -155,6 +160,11 @@ export function uniroot(f, lower, upper, options = {}) {
|
|
|
155
160
|
if (!(Math.sign(fLo) * Math.sign(fUp) <= 0)) {
|
|
156
161
|
throw new RangeError(extend ? "did not succeed extending the interval endpoints for f(lower) * f(upper) <= 0" : "f() values at end points not of opposite sign");
|
|
157
162
|
}
|
|
163
|
+
// An end that is not finite passes the checks above (f may be infinite there) but not the root search
|
|
164
|
+
if (!Number.isFinite(lower))
|
|
165
|
+
throw new RangeError("invalid 'xmin' value");
|
|
166
|
+
if (!Number.isFinite(upper))
|
|
167
|
+
throw new RangeError("invalid 'xmax' value");
|
|
158
168
|
const z = zero((x) => finiteValue(f(x)), lower, upper, finiteValue(fLo), finiteValue(fUp), tol, maxiter);
|
|
159
169
|
return {
|
|
160
170
|
root: z.root,
|
|
@@ -24,7 +24,7 @@ export interface ApproxOptions {
|
|
|
24
24
|
yright?: number;
|
|
25
25
|
/** Extrapolation rule (1: NaN, 2: the end value), for both sides or `[left, right]`. Default `1`. */
|
|
26
26
|
rule?: number | readonly [number, number];
|
|
27
|
-
/** For `"constant"`: the step value is (1 - f) y_left + f y_right. Default `0`. */
|
|
27
|
+
/** For `"constant"`: the step value is (1 - f) y_left + f y_right, with f in [0, 1] (else an error, as in R). Default `0`. */
|
|
28
28
|
f?: number;
|
|
29
29
|
/** How to merge equal x values. Default `"mean"`. */
|
|
30
30
|
ties?: Ties;
|
package/dist/numerics/interp.js
CHANGED
|
@@ -73,6 +73,9 @@ export function approx(x, y, options = {}) {
|
|
|
73
73
|
throw new RangeError("need at least two non-NA values to interpolate");
|
|
74
74
|
if (nx === 0)
|
|
75
75
|
throw new RangeError("zero non-NA points");
|
|
76
|
+
// As in R, f is checked only for the constant method
|
|
77
|
+
if (method === "constant" && !(f >= 0 && f <= 1))
|
|
78
|
+
throw new RangeError("approx(): invalid f value");
|
|
76
79
|
const [ruleLeft, ruleRight] = typeof rule === "number" ? [rule, rule] : rule;
|
|
77
80
|
const yleft = options.yleft ?? (ruleLeft === 1 ? NaN : pts.y[0]);
|
|
78
81
|
const yright = options.yright ?? (ruleRight === 1 ? NaN : pts.y[nx - 1]);
|