@numero-uno-jpn/rstats 0.15.3 → 0.17.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 +294 -0
- package/README.ja.md +68 -35
- package/README.md +65 -30
- package/dist/chunks/chunk-2C33MXSW.js +3 -0
- package/dist/chunks/chunk-34S5SQY6.js +2 -0
- package/dist/chunks/chunk-4WE3OO62.js +2 -0
- package/dist/chunks/chunk-5AYHCITP.js +2 -0
- package/dist/chunks/chunk-6JJQL6HL.js +2 -0
- package/dist/chunks/chunk-C7V2FH6L.js +3 -0
- package/dist/chunks/chunk-CZI7KUO3.js +2 -0
- package/dist/chunks/chunk-DXI5N2ET.js +2 -0
- package/dist/chunks/chunk-FY3FVOBM.js +2 -0
- package/dist/chunks/chunk-H3WVPZDL.js +2 -0
- package/dist/chunks/chunk-LHUIJQHY.js +2 -0
- package/dist/chunks/chunk-LV3W2F7N.js +2 -0
- package/dist/chunks/chunk-M4ITG7YR.js +2 -0
- package/dist/chunks/chunk-NSYZTS26.js +2 -0
- package/dist/chunks/chunk-ONY5CISH.js +2 -0
- package/dist/chunks/chunk-RFE7MVP7.js +2 -0
- package/dist/chunks/chunk-SE7V2KLO.js +2 -0
- package/dist/chunks/chunk-THIGHOKK.js +2 -0
- package/dist/chunks/chunk-TNMJPQPV.js +2 -0
- package/dist/chunks/chunk-WM7VFXTV.js +2 -0
- package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
- package/dist/chunks/chunk-XLSFJTTK.js +2 -0
- package/dist/chunks/chunk-Z37NELOS.js +2 -0
- package/dist/chunks/chunk-ZFQWB222.js +2 -0
- package/dist/data/grouping.js +26 -7
- package/dist/descriptive/basic.js +110 -8
- package/dist/descriptive/cov.js +23 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +69 -23
- package/dist/descriptive/factanal.d.ts +2 -0
- package/dist/descriptive/factanal.js +26 -9
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +77 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +86 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +74 -10
- package/dist/descriptive/pivot.d.ts +25 -10
- package/dist/descriptive/pivot.js +182 -42
- package/dist/descriptive/quantile.js +10 -1
- package/dist/descriptive/rank.js +8 -1
- package/dist/descriptive/table.d.ts +23 -3
- package/dist/descriptive/table.js +36 -21
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +27 -2
- package/dist/distributions/beta.js +33 -4
- package/dist/distributions/binomial.js +46 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +21 -4
- package/dist/distributions/chisq.js +16 -3
- package/dist/distributions/exponential.js +14 -0
- package/dist/distributions/f.js +41 -17
- package/dist/distributions/gamma.js +35 -3
- package/dist/distributions/geometric.js +58 -13
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +101 -6
- package/dist/distributions/invgamma.js +10 -1
- package/dist/distributions/kumaraswamy.js +9 -0
- package/dist/distributions/laplace.js +36 -6
- package/dist/distributions/logistic.js +13 -1
- package/dist/distributions/lognormal.js +16 -2
- package/dist/distributions/multinomial.js +58 -11
- package/dist/distributions/nbeta.js +62 -11
- package/dist/distributions/nchisq.js +30 -6
- package/dist/distributions/negbinomial.js +102 -17
- package/dist/distributions/normal.js +17 -4
- package/dist/distributions/nt.js +392 -17
- package/dist/distributions/pareto.js +12 -1
- package/dist/distributions/poisson.js +37 -3
- package/dist/distributions/signrank.js +16 -4
- package/dist/distributions/summary.d.ts +2 -1
- package/dist/distributions/summary.js +481 -61
- package/dist/distributions/t.js +9 -0
- package/dist/distributions/triangular.js +19 -5
- package/dist/distributions/tukey.js +11 -2
- package/dist/distributions/uniform.js +8 -0
- package/dist/distributions/weibull.js +18 -0
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +164 -26
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +3 -1
- package/dist/entries/descriptive.js +1 -1
- package/dist/entries/distributions.d.ts +1 -0
- package/dist/entries/distributions.js +2 -0
- package/dist/entries/linalg.d.ts +3 -1
- package/dist/entries/mixed.d.ts +3 -0
- package/dist/entries/mixed.js +2 -0
- package/dist/entries/numerics.d.ts +2 -1
- package/dist/entries/tests.d.ts +8 -5
- package/dist/entries/tests.js +3 -1
- package/dist/htest/agreement.d.ts +16 -2
- package/dist/htest/agreement.js +122 -21
- package/dist/htest/ansariTest.d.ts +8 -2
- package/dist/htest/ansariTest.js +116 -18
- package/dist/htest/aov.d.ts +29 -23
- package/dist/htest/aov.js +90 -47
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +47 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +12 -5
- package/dist/htest/chisqTest.d.ts +5 -2
- package/dist/htest/chisqTest.js +151 -46
- package/dist/htest/cor.d.ts +9 -2
- package/dist/htest/cor.js +57 -26
- package/dist/htest/core/ansari.d.ts +9 -0
- package/dist/htest/core/ansari.js +21 -1
- package/dist/htest/core/kolmogorov.d.ts +25 -0
- package/dist/htest/core/kolmogorov.js +123 -0
- package/dist/htest/core/mantelhaen.js +6 -4
- package/dist/htest/core/shapiro.d.ts +1 -1
- package/dist/htest/core/shapiro.js +5 -1
- package/dist/htest/core/simulate.d.ts +6 -0
- package/dist/htest/core/simulate.js +20 -0
- package/dist/htest/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +5 -0
- package/dist/htest/effectSize.js +117 -35
- package/dist/htest/fisherTest.d.ts +4 -3
- package/dist/htest/fisherTest.js +88 -24
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +7 -1
- package/dist/htest/ksTest.js +36 -6
- package/dist/htest/leveneTest.d.ts +2 -0
- package/dist/htest/leveneTest.js +28 -6
- package/dist/htest/mantelhaenTest.js +132 -25
- package/dist/htest/mcnemarTest.js +40 -11
- package/dist/htest/multipleComparisons.d.ts +24 -26
- package/dist/htest/multipleComparisons.js +70 -64
- package/dist/htest/normalityTests.js +54 -14
- package/dist/htest/onewayTest.js +106 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +42 -6
- package/dist/htest/pairwise.d.ts +3 -1
- package/dist/htest/pairwise.js +46 -21
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +117 -59
- package/dist/htest/polycor.js +47 -17
- package/dist/htest/power.d.ts +15 -1
- package/dist/htest/power.js +128 -10
- package/dist/htest/propTest.d.ts +3 -0
- package/dist/htest/propTest.js +44 -6
- package/dist/htest/pwr.d.ts +38 -1
- package/dist/htest/pwr.js +159 -39
- package/dist/htest/rankTests.js +36 -6
- package/dist/htest/tTest.d.ts +2 -0
- package/dist/htest/tTest.js +53 -21
- package/dist/htest/testFormula.js +11 -11
- package/dist/htest/trendTests.d.ts +28 -4
- package/dist/htest/trendTests.js +124 -35
- package/dist/htest/types.d.ts +7 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +52 -14
- package/dist/htest/wilcoxTest.js +164 -29
- package/dist/integrate/quadpack.js +27 -5
- package/dist/internal/checkOptions.d.ts +11 -0
- package/dist/internal/checkOptions.js +31 -0
- package/dist/internal/covmat.d.ts +5 -0
- package/dist/internal/covmat.js +20 -0
- package/dist/internal/ddexp.d.ts +15 -1
- package/dist/internal/ddexp.js +59 -6
- package/dist/internal/discrete.d.ts +14 -0
- package/dist/internal/discrete.js +78 -5
- package/dist/internal/extremes.d.ts +9 -0
- package/dist/internal/extremes.js +24 -0
- package/dist/internal/fround.js +13 -4
- package/dist/internal/integer.d.ts +9 -0
- package/dist/internal/integer.js +12 -0
- package/dist/internal/invert.js +15 -2
- package/dist/internal/optionalArgs.d.ts +12 -0
- package/dist/internal/optionalArgs.js +46 -0
- package/dist/internal/scaledInverse.d.ts +10 -0
- package/dist/internal/scaledInverse.js +22 -0
- package/dist/internal/seq.js +15 -2
- package/dist/internal/summary.d.ts +90 -0
- package/dist/internal/summary.js +458 -39
- package/dist/internal/uniroot.d.ts +7 -0
- package/dist/internal/uniroot.js +28 -3
- package/dist/internal/warnings.d.ts +66 -0
- package/dist/internal/warnings.js +122 -0
- package/dist/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +58 -7
- package/dist/linalg/chol.js +10 -1
- package/dist/linalg/dot.d.ts +29 -0
- package/dist/linalg/dot.js +132 -0
- package/dist/linalg/eigen.d.ts +6 -1
- package/dist/linalg/eigen.js +75 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +113 -15
- package/dist/linalg/kappa.js +64 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +40 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/norm.js +4 -0
- package/dist/linalg/ops.d.ts +27 -2
- package/dist/linalg/ops.js +74 -26
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +105 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +156 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +33 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +32 -2
- package/dist/models/anovaSequential.js +170 -28
- package/dist/models/aovEz.js +154 -39
- package/dist/models/aovStrata.js +68 -24
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +78 -33
- package/dist/models/coxph.d.ts +6 -0
- package/dist/models/coxph.js +166 -69
- package/dist/models/estimable.d.ts +15 -0
- package/dist/models/estimable.js +68 -0
- package/dist/models/formula.d.ts +1 -1
- package/dist/models/formula.js +26 -8
- package/dist/models/glm.d.ts +57 -7
- package/dist/models/glm.js +427 -74
- package/dist/models/glmAnova.js +90 -14
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +121 -29
- package/dist/models/glmFamily.d.ts +11 -6
- package/dist/models/glmFamily.js +247 -62
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +246 -37
- package/dist/models/lmer.d.ts +31 -7
- package/dist/models/lmer.js +129 -42
- package/dist/models/lmerAnova.d.ts +3 -3
- package/dist/models/lmerAnova.js +47 -9
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +13 -6
- package/dist/models/lmerTest.js +82 -29
- package/dist/models/mauchly.d.ts +6 -1
- package/dist/models/mauchly.js +41 -15
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +10 -4
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +47 -17
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +12 -1
- package/dist/models/survival.js +75 -28
- package/dist/models/tiedTimes.d.ts +2 -0
- package/dist/models/tiedTimes.js +34 -0
- package/dist/numerics/deriv.d.ts +1 -1
- package/dist/numerics/deriv.js +72 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +111 -16
- package/dist/numerics/interp.d.ts +40 -9
- package/dist/numerics/interp.js +375 -55
- package/dist/numerics/ode.js +59 -1
- package/dist/numerics.js +2 -2
- package/dist/optim/localmin.js +4 -0
- package/dist/optim/optim.d.ts +3 -1
- package/dist/optim/optim.js +97 -10
- package/dist/random/beta.js +58 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +50 -5
- package/dist/random/extra.js +55 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +47 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +31 -3
- package/dist/random/r2dtable.d.ts +8 -1
- package/dist/random/r2dtable.js +24 -3
- package/dist/random/rank.d.ts +2 -0
- package/dist/random/rank.js +44 -4
- package/dist/random/rng.js +4 -0
- package/dist/random/sample.d.ts +12 -2
- package/dist/random/sample.js +63 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +17 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +175 -23
- package/dist/special/besselJY.d.ts +11 -1
- package/dist/special/besselJY.js +127 -19
- package/dist/special/besselSeries.d.ts +27 -0
- package/dist/special/besselSeries.js +45 -2
- package/dist/special/beta.js +4 -1
- package/dist/special/choose.js +24 -8
- package/dist/special/dd.js +122 -18
- package/dist/special/extra.js +14 -2
- package/dist/special/gamma.js +11 -2
- package/dist/special/incbet.js +30 -4
- package/dist/special/incbetTemme.d.ts +7 -0
- package/dist/special/incbetTemme.js +45 -12
- package/dist/special/loader.d.ts +1 -1
- package/dist/special/loader.js +117 -20
- package/dist/special/log1pmx.js +4 -0
- package/dist/special/psigamma.js +7 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -11
- package/llms.txt +15 -6
- package/package.json +19 -10
- package/dist/chunks/chunk-3THFTB36.js +0 -2
- package/dist/chunks/chunk-3TSWYE5L.js +0 -2
- package/dist/chunks/chunk-3WPU6LGK.js +0 -2
- package/dist/chunks/chunk-5ITR67MB.js +0 -2
- package/dist/chunks/chunk-5NRFU6F6.js +0 -2
- package/dist/chunks/chunk-E2LCSVQV.js +0 -2
- package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
- package/dist/chunks/chunk-FKAKALOZ.js +0 -2
- package/dist/chunks/chunk-HD73UKPT.js +0 -2
- package/dist/chunks/chunk-IUULP3LE.js +0 -2
- package/dist/chunks/chunk-JQG3YQOC.js +0 -2
- package/dist/chunks/chunk-KT66SB7R.js +0 -2
- package/dist/chunks/chunk-MAUAOQG3.js +0 -2
- package/dist/chunks/chunk-MDYE7QP2.js +0 -2
- package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
- package/dist/chunks/chunk-PMJI5QO6.js +0 -3
- package/dist/chunks/chunk-UF7KOTHF.js +0 -3
- package/dist/chunks/chunk-UOE57JGT.js +0 -2
- package/dist/chunks/chunk-USPEBXSR.js +0 -2
- package/dist/chunks/chunk-VLUL2HFW.js +0 -3
- package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
package/dist/models/survival.js
CHANGED
|
@@ -9,7 +9,14 @@
|
|
|
9
9
|
import { pchisq } from "../distributions/chisq.js";
|
|
10
10
|
import { qnorm } from "../distributions/normal.js";
|
|
11
11
|
import { levelText, numberLevels } from "../internal/levels.js";
|
|
12
|
+
import { eigen } from "../linalg/eigen.js";
|
|
12
13
|
import { solve } from "../linalg/solve.js";
|
|
14
|
+
import { midpoint } from "../internal/extremes.js";
|
|
15
|
+
import { mergeTiedTimes } from "./tiedTimes.js";
|
|
16
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
17
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
18
|
+
const SURVDIFF_KEYS = ["rho"];
|
|
19
|
+
const SURVFIT_KEYS = ["group", "confType", "confInt"];
|
|
13
20
|
const isMissing = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
|
|
14
21
|
/** Observations with no missing value, the sorted labels and the group index of each */
|
|
15
22
|
function prepare(time, status, group) {
|
|
@@ -24,6 +31,10 @@ function prepare(time, status, group) {
|
|
|
24
31
|
const s = status[i];
|
|
25
32
|
if (s !== 0 && s !== 1)
|
|
26
33
|
throw new RangeError("'status' must be 0 (censored) or 1 (event)");
|
|
34
|
+
// a subject censored at Infinity is at risk throughout (R stops on any infinite time); an event cannot happen at an
|
|
35
|
+
// infinite time, nor anything at -Infinity
|
|
36
|
+
if (time[i] === -Infinity || (time[i] === Infinity && s === 1))
|
|
37
|
+
throw new RangeError("event times must be finite");
|
|
27
38
|
keep.push(i);
|
|
28
39
|
}
|
|
29
40
|
if (keep.length === 0)
|
|
@@ -37,8 +48,11 @@ function prepare(time, status, group) {
|
|
|
37
48
|
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);
|
|
38
49
|
labels.forEach((l, k) => index.set(l, k));
|
|
39
50
|
}
|
|
40
|
-
|
|
41
|
-
|
|
51
|
+
// times within rounding error are one time, as R's timefix = TRUE (1 and 1 + 1e-9 were two times, so a subject
|
|
52
|
+
// censored at 1 left the risk set before the event at 1 + 1e-9)
|
|
53
|
+
const merged = mergeTiedTimes(keep.map((i) => time[i]));
|
|
54
|
+
const obs = keep.map((i, k) => ({
|
|
55
|
+
time: merged[k],
|
|
42
56
|
event: status[i] === 1,
|
|
43
57
|
group: group === undefined ? 0 : index.get(group[i]),
|
|
44
58
|
}));
|
|
@@ -66,11 +80,14 @@ function prepare(time, status, group) {
|
|
|
66
80
|
* @category Survival analysis
|
|
67
81
|
*/
|
|
68
82
|
export function survdiff(time, status, group, options = {}) {
|
|
83
|
+
checkOptions(options, SURVDIFF_KEYS, "survdiff"); // generated: option-keys.mjs
|
|
69
84
|
const { rho = 0 } = options;
|
|
70
85
|
if (!Number.isFinite(rho))
|
|
71
86
|
throw new RangeError("'rho' must be a finite number");
|
|
72
87
|
const { obs, labels } = prepare(time, status, group);
|
|
73
88
|
const k = labels.length;
|
|
89
|
+
if (k < 2)
|
|
90
|
+
throw new RangeError("there is only 1 group");
|
|
74
91
|
const n = new Array(k).fill(0);
|
|
75
92
|
for (const o of obs)
|
|
76
93
|
n[o.group]++;
|
|
@@ -120,35 +137,62 @@ export function survdiff(time, status, group, options = {}) {
|
|
|
120
137
|
// chi-squared on the groups with a positive expected count, dropping the first of them
|
|
121
138
|
const used = expected.map((e, g) => (e > 0 ? g : -1)).filter((g) => g >= 0);
|
|
122
139
|
let chisq = 0;
|
|
140
|
+
let df = Math.max(used.length - 1, 0);
|
|
123
141
|
if (used.length >= 2) {
|
|
124
142
|
const r = used.slice(1);
|
|
125
143
|
const u = r.map((g) => observed[g] - expected[g]);
|
|
126
|
-
const
|
|
127
|
-
|
|
144
|
+
const Vr = r.map((g) => r.map((h) => V[g][h]));
|
|
145
|
+
try {
|
|
146
|
+
const x = solve(Vr, u);
|
|
147
|
+
chisq = u.reduce((s, ui, a) => s + ui * x[a], 0);
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
// A singular variance matrix (all at risk failing at once, or groups that carry no information): u' V^- u with
|
|
151
|
+
// the generalized inverse, on rank(V) degrees of freedom, which is the chi-squared statistic of the contrasts
|
|
152
|
+
// the data inform (R stops: "system is exactly singular")
|
|
153
|
+
({ chisq, df } = pseudoQuadratic(Vr, u));
|
|
154
|
+
}
|
|
128
155
|
}
|
|
129
|
-
const pvalue = pchisq(chisq,
|
|
130
|
-
return { n, groups: labels, obs: observed, exp: expected, var: V, chisq, pvalue };
|
|
156
|
+
const pvalue = df === 0 ? NaN : pchisq(chisq, df, { lowerTail: false });
|
|
157
|
+
return { n, groups: labels, obs: observed, exp: expected, var: V, chisq, df, pvalue, pValue: pvalue, warnings: [] };
|
|
131
158
|
}
|
|
132
159
|
/**
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
* 0.5 + sqrt(eps).
|
|
160
|
+
* u' V^- u for a symmetric positive semi-definite V by its eigen decomposition, over the eigenvalues above 1e-10 of the
|
|
161
|
+
* largest (rank 0, chisq 0 when there are none), and that rank
|
|
136
162
|
*/
|
|
137
|
-
function
|
|
163
|
+
function pseudoQuadratic(V, u) {
|
|
164
|
+
const e = eigen(V, { symmetric: true });
|
|
165
|
+
const values = e.values;
|
|
166
|
+
const top = values.reduce((a, b) => Math.max(a, b), 0);
|
|
167
|
+
let chisq = 0;
|
|
168
|
+
let df = 0;
|
|
169
|
+
values.forEach((l, k) => {
|
|
170
|
+
if (!(top > 0 && l > 1e-10 * top))
|
|
171
|
+
return;
|
|
172
|
+
const q = u.reduce((s, ui, i) => s + ui * e.vectors[i][k], 0);
|
|
173
|
+
chisq += (q * q) / l;
|
|
174
|
+
df++;
|
|
175
|
+
});
|
|
176
|
+
return { chisq, df };
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The median of a curve over the rows of a stratum, as survival's survmean (minmin): of the points that are not NaN
|
|
180
|
+
* and lie below 0.5 + sqrt(eps), the first time, or, if the curve equals 0.5 (within sqrt(eps)) there and a later such
|
|
181
|
+
* point is lower, the midpoint between that time and the time of the first lower point. NaN if there is no such point.
|
|
182
|
+
*/
|
|
183
|
+
function curveMedian(time, curve) {
|
|
138
184
|
const tol = Math.sqrt(Number.EPSILON);
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
}
|
|
149
|
-
return time[i];
|
|
185
|
+
const first = curve.findIndex((c) => c < 0.5 + tol);
|
|
186
|
+
if (first < 0)
|
|
187
|
+
return NaN;
|
|
188
|
+
const c1 = curve[first];
|
|
189
|
+
if (Math.abs(c1 - 0.5) < tol) {
|
|
190
|
+
// a NaN point compares false and is skipped, as R drops it before looking for a lower one
|
|
191
|
+
for (let j = first + 1; j < curve.length; j++)
|
|
192
|
+
if (curve[j] < c1)
|
|
193
|
+
return midpoint(time[first], time[j]);
|
|
150
194
|
}
|
|
151
|
-
return
|
|
195
|
+
return time[first];
|
|
152
196
|
}
|
|
153
197
|
/**
|
|
154
198
|
* Kaplan-Meier estimate of the survival function with Greenwood's standard error and pointwise confidence intervals.
|
|
@@ -169,6 +213,7 @@ function curveMedian(time, nEvent, curve) {
|
|
|
169
213
|
* @category Survival analysis
|
|
170
214
|
*/
|
|
171
215
|
export function survfit(time, status, options = {}) {
|
|
216
|
+
checkOptions(options, SURVFIT_KEYS, "survfit"); // generated: option-keys.mjs
|
|
172
217
|
const { group, confType = "log", confInt = 0.95 } = options;
|
|
173
218
|
if (confType !== "log" && confType !== "plain" && confType !== "log-log") {
|
|
174
219
|
throw new RangeError(`invalid 'confType': ${String(confType)}`);
|
|
@@ -177,9 +222,12 @@ export function survfit(time, status, options = {}) {
|
|
|
177
222
|
throw new RangeError("'confInt' must be between 0 and 1");
|
|
178
223
|
const { obs, labels } = prepare(time, status, group);
|
|
179
224
|
const names = group === undefined ? ["all"] : labels;
|
|
180
|
-
|
|
225
|
+
// (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
|
|
226
|
+
const a2 = (1 - confInt) / 2;
|
|
227
|
+
const z = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - (1 - confInt) / 2);
|
|
228
|
+
const stdErr = [];
|
|
181
229
|
const out = {
|
|
182
|
-
strata: [], time: [], nRisk: [], nEvent: [], nCensor: [], surv: [], stdErr:
|
|
230
|
+
strata: [], time: [], nRisk: [], nEvent: [], nCensor: [], surv: [], stdErr, stdError: stdErr, lower: [], upper: [],
|
|
183
231
|
median: [], medianRows: names,
|
|
184
232
|
};
|
|
185
233
|
names.forEach((name, g) => {
|
|
@@ -237,11 +285,10 @@ export function survfit(time, status, options = {}) {
|
|
|
237
285
|
i = j;
|
|
238
286
|
}
|
|
239
287
|
const tt = out.time.slice(start);
|
|
240
|
-
const ev = out.nEvent.slice(start);
|
|
241
288
|
out.median.push([
|
|
242
|
-
curveMedian(tt,
|
|
243
|
-
curveMedian(tt,
|
|
244
|
-
curveMedian(tt,
|
|
289
|
+
curveMedian(tt, out.surv.slice(start)),
|
|
290
|
+
curveMedian(tt, out.lower.slice(start)),
|
|
291
|
+
curveMedian(tt, out.upper.slice(start)),
|
|
245
292
|
]);
|
|
246
293
|
});
|
|
247
294
|
return out;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Times that differ by rounding error only, merged as R's survival does by default (timefix = TRUE, aeqSurv): coxph and
|
|
2
|
+
// survfit / survdiff (survival.ts).
|
|
3
|
+
import { mean } from "../internal/summary.js";
|
|
4
|
+
/** Times within sqrt(eps) (absolutely or relative to the mean absolute distinct time) merged to the smaller one */
|
|
5
|
+
export function mergeTiedTimes(time) {
|
|
6
|
+
const tol = Math.sqrt(2 ** -52);
|
|
7
|
+
const distinct = Array.from(new Set(time.filter((t) => Number.isFinite(t)))).sort((a, b) => a - b);
|
|
8
|
+
if (distinct.length < 2)
|
|
9
|
+
return time.slice();
|
|
10
|
+
// the mean of |time| without overflow (a plain sum of times near 1e308 was Infinity, so every relative gap was 0 and
|
|
11
|
+
// distinct times were merged: coxph gave a coefficient of 0); a gap that overflows is Infinity, a distinct time
|
|
12
|
+
const meanAbs = mean(distinct.map(Math.abs));
|
|
13
|
+
const cuts = [distinct[0]];
|
|
14
|
+
for (let k = 0; k + 1 < distinct.length; k++) {
|
|
15
|
+
const gap = distinct[k + 1] - distinct[k];
|
|
16
|
+
if (!(gap <= tol || gap / meanAbs <= tol))
|
|
17
|
+
cuts.push(distinct[k + 1]);
|
|
18
|
+
}
|
|
19
|
+
return time.map((t) => {
|
|
20
|
+
if (!Number.isFinite(t))
|
|
21
|
+
return t;
|
|
22
|
+
// the largest cut point not above t
|
|
23
|
+
let lo = 0;
|
|
24
|
+
let hi = cuts.length - 1;
|
|
25
|
+
while (lo < hi) {
|
|
26
|
+
const mid = Math.floor((lo + hi + 1) / 2); // not >> 1, which wraps beyond 2^31 times (issue #352)
|
|
27
|
+
if (cuts[mid] <= t)
|
|
28
|
+
lo = mid;
|
|
29
|
+
else
|
|
30
|
+
hi = mid - 1;
|
|
31
|
+
}
|
|
32
|
+
return cuts[lo];
|
|
33
|
+
});
|
|
34
|
+
}
|
package/dist/numerics/deriv.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ export interface DerivOptions {
|
|
|
12
12
|
d?: number;
|
|
13
13
|
/** Coordinates with |x| below this get the step `eps`. Default `sqrt(2.220446e-16 / 7e-7)`. */
|
|
14
14
|
zeroTol?: number;
|
|
15
|
-
/** Number of halvings of the step (Richardson iterations). Default `4`. */
|
|
15
|
+
/** Number of halvings of the step (Richardson iterations), at most 512. Default `4`. */
|
|
16
16
|
r?: number;
|
|
17
17
|
}
|
|
18
18
|
/**
|
package/dist/numerics/deriv.js
CHANGED
|
@@ -7,14 +7,47 @@
|
|
|
7
7
|
// diagonal from second central differences, the off-diagonal entries from differences along e_i + e_j less the
|
|
8
8
|
// diagonal terms, each extrapolated the same way (with d = 0.1). "simple" is the forward difference with step eps.
|
|
9
9
|
// numDeriv's "complex" (complex-step) method needs a function of a complex argument and is not offered.
|
|
10
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
11
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
12
|
+
const GRAD_KEYS = ["method", "eps", "d", "zeroTol", "r"];
|
|
13
|
+
const HESSIAN_KEYS = ["method", "eps", "d", "zeroTol", "r"];
|
|
14
|
+
const JACOBIAN_KEYS = ["method", "eps", "d", "zeroTol", "r"];
|
|
15
|
+
function checkEps(eps) {
|
|
16
|
+
if (!(Number.isFinite(eps) && eps !== 0))
|
|
17
|
+
throw new RangeError("'eps' must be a finite nonzero number");
|
|
18
|
+
}
|
|
19
|
+
/** The step of method "simple" */
|
|
20
|
+
function simpleEps(options) {
|
|
21
|
+
const eps = options.eps ?? 1e-4;
|
|
22
|
+
checkEps(eps);
|
|
23
|
+
return eps;
|
|
24
|
+
}
|
|
10
25
|
function steps(x, options, d0) {
|
|
11
26
|
const eps = options.eps ?? 1e-4;
|
|
12
27
|
const d = options.d ?? d0;
|
|
13
28
|
const zeroTol = options.zeroTol ?? Math.sqrt(Number.EPSILON / 7e-7);
|
|
29
|
+
// a step of 0 or a non-finite step defines no difference quotient (numDeriv: an error for d = 0, NaN for eps = 0);
|
|
30
|
+
// negative steps are differences taken the other way, as in numDeriv
|
|
31
|
+
if (!(Number.isFinite(d) && d !== 0))
|
|
32
|
+
throw new RangeError("'d' must be a finite nonzero number");
|
|
33
|
+
checkEps(eps);
|
|
34
|
+
if (!(Number.isFinite(zeroTol) && zeroTol >= 0))
|
|
35
|
+
throw new RangeError("'zeroTol' must be a non-negative finite number");
|
|
14
36
|
const r = options.r ?? 4;
|
|
15
37
|
if (!(Number.isInteger(r) && r >= 1))
|
|
16
38
|
throw new RangeError("'r' must be a positive integer");
|
|
17
|
-
|
|
39
|
+
// from r = 513 on the extrapolation's 4^m overflows (m = 512) and every result is NaN, as in numDeriv; its O(r^2)
|
|
40
|
+
// steps would not end for a huge r
|
|
41
|
+
if (r > 512)
|
|
42
|
+
throw new RangeError("'r' must be at most 512");
|
|
43
|
+
const h0 = x.map((v) => Math.abs(d * v) + (Math.abs(v) < zeroTol ? eps : 0));
|
|
44
|
+
// a step of 0 or a non-finite step defines no difference quotient: d abs(x[i]) overflowing (#213), or 0 for
|
|
45
|
+
// x[i] = 0 with zeroTol 0 (#246) (numDeriv: NaN from jacobian and hessian, an error from grad's check of f)
|
|
46
|
+
h0.forEach((h, i) => {
|
|
47
|
+
if (!(Math.abs(h) > 0 && Math.abs(h) < Infinity))
|
|
48
|
+
throw new RangeError(`the step for x[${i}] is ${h}: not a nonzero finite number`);
|
|
49
|
+
});
|
|
50
|
+
return { eps, r, h0 };
|
|
18
51
|
}
|
|
19
52
|
/** Richardson extrapolation of approximations at steps h, h/2, h/4, ... (errors in even powers of h) */
|
|
20
53
|
function extrapolate(a) {
|
|
@@ -48,10 +81,11 @@ function method(options) {
|
|
|
48
81
|
* @category Numerical methods
|
|
49
82
|
*/
|
|
50
83
|
export function grad(func, x, options = {}) {
|
|
84
|
+
checkOptions(options, GRAD_KEYS, "grad"); // generated: option-keys.mjs
|
|
51
85
|
const xs = [...x];
|
|
52
86
|
const n = xs.length;
|
|
53
87
|
if (method(options) === "simple") {
|
|
54
|
-
const eps = options
|
|
88
|
+
const eps = simpleEps(options);
|
|
55
89
|
const f0 = func([...xs]);
|
|
56
90
|
return xs.map((_, i) => (func(shifted(xs, i, eps)) - f0) / eps);
|
|
57
91
|
}
|
|
@@ -86,14 +120,22 @@ export function grad(func, x, options = {}) {
|
|
|
86
120
|
* @category Numerical methods
|
|
87
121
|
*/
|
|
88
122
|
export function jacobian(func, x, options = {}) {
|
|
123
|
+
checkOptions(options, JACOBIAN_KEYS, "jacobian"); // generated: option-keys.mjs
|
|
89
124
|
const xs = [...x];
|
|
90
125
|
const n = xs.length;
|
|
91
126
|
const f0 = Array.from(func([...xs]));
|
|
92
127
|
const J = f0.map(() => new Array(n).fill(NaN));
|
|
128
|
+
// every evaluation must return as many values as f0: shorter ones gave NaN rows, longer ones were cut (issue #356)
|
|
129
|
+
const evaluate = (at) => {
|
|
130
|
+
const v = func(at);
|
|
131
|
+
if (v.length !== f0.length)
|
|
132
|
+
throw new RangeError(`jacobian: func returned ${v.length} values at a shifted x, but ${f0.length} at x`);
|
|
133
|
+
return v;
|
|
134
|
+
};
|
|
93
135
|
if (method(options) === "simple") {
|
|
94
|
-
const eps = options
|
|
136
|
+
const eps = simpleEps(options);
|
|
95
137
|
for (let j = 0; j < n; j++) {
|
|
96
|
-
const f1 =
|
|
138
|
+
const f1 = evaluate(shifted(xs, j, eps));
|
|
97
139
|
f0.forEach((v, i) => (J[i][j] = (f1[i] - v) / eps));
|
|
98
140
|
}
|
|
99
141
|
return J;
|
|
@@ -103,8 +145,8 @@ export function jacobian(func, x, options = {}) {
|
|
|
103
145
|
const a = f0.map(() => []);
|
|
104
146
|
let h = h0[j];
|
|
105
147
|
for (let k = 0; k < r; k++) {
|
|
106
|
-
const fp =
|
|
107
|
-
const fm =
|
|
148
|
+
const fp = evaluate(shifted(xs, j, h));
|
|
149
|
+
const fm = evaluate(shifted(xs, j, -h));
|
|
108
150
|
f0.forEach((_, i) => a[i].push((fp[i] - fm[i]) / (2 * h)));
|
|
109
151
|
h /= 2;
|
|
110
152
|
}
|
|
@@ -124,6 +166,7 @@ export function jacobian(func, x, options = {}) {
|
|
|
124
166
|
* @category Numerical methods
|
|
125
167
|
*/
|
|
126
168
|
export function hessian(func, x, options = {}) {
|
|
169
|
+
checkOptions(options, HESSIAN_KEYS, "hessian"); // generated: option-keys.mjs
|
|
127
170
|
if ((options.method ?? "Richardson") !== "Richardson")
|
|
128
171
|
throw new RangeError('hessian supports only method "Richardson"');
|
|
129
172
|
const xs = [...x];
|
|
@@ -135,7 +178,16 @@ export function hessian(func, x, options = {}) {
|
|
|
135
178
|
const a = [];
|
|
136
179
|
let h = h0[i];
|
|
137
180
|
for (let k = 0; k < r; k++) {
|
|
138
|
-
|
|
181
|
+
const fp = func(shifted(xs, i, h));
|
|
182
|
+
const fm = func(shifted(xs, i, -h));
|
|
183
|
+
const num = fp - 2 * f0 + fm;
|
|
184
|
+
// where h^2 overflows (h beyond 1.3e154), divided by h twice: a finite curvature was 0 or NaN (issue #214)
|
|
185
|
+
const h2 = h ** 2;
|
|
186
|
+
// where the sum of finite values overflows (f(+-1e200) near 1e308), every term divided by h first (issue #504)
|
|
187
|
+
if (!Number.isFinite(num) && Number.isFinite(fp) && Number.isFinite(fm) && Number.isFinite(f0))
|
|
188
|
+
a.push((fp / h - 2 * (f0 / h) + fm / h) / h);
|
|
189
|
+
else
|
|
190
|
+
a.push(Number.isFinite(h2) ? num / h2 : num / h / h);
|
|
139
191
|
h /= 2;
|
|
140
192
|
}
|
|
141
193
|
diag.push(extrapolate(a));
|
|
@@ -150,7 +202,19 @@ export function hessian(func, x, options = {}) {
|
|
|
150
202
|
for (let k = 0; k < r; k++) {
|
|
151
203
|
const up = shifted(shifted(xs, i, hi), j, hj);
|
|
152
204
|
const down = shifted(shifted(xs, i, -hi), j, -hj);
|
|
153
|
-
|
|
205
|
+
const fu = func(up);
|
|
206
|
+
const fd = func(down);
|
|
207
|
+
const num = fu - 2 * f0 + fd;
|
|
208
|
+
const den = 2 * hi * hj;
|
|
209
|
+
// where the sum of finite values overflows, every term divided by hi hj first (issue #504)
|
|
210
|
+
if (!Number.isFinite(num) && Number.isFinite(fu) && Number.isFinite(fd) && Number.isFinite(f0)) {
|
|
211
|
+
a.push((fu / hi / hj - 2 * (f0 / hi / hj) + fd / hi / hj - diag[i] * (hi / hj) - diag[j] * (hj / hi)) / 2);
|
|
212
|
+
}
|
|
213
|
+
else if (Number.isFinite(den) && Number.isFinite(hi ** 2) && Number.isFinite(hj ** 2))
|
|
214
|
+
a.push((num - diag[i] * hi ** 2 - diag[j] * hj ** 2) / den);
|
|
215
|
+
// where a squared step or 2 hi hj overflows, every term divided by hi hj first (issue #214)
|
|
216
|
+
else
|
|
217
|
+
a.push((num / hi / hj - diag[i] * (hi / hj) - diag[j] * (hj / hi)) / 2);
|
|
154
218
|
hi /= 2;
|
|
155
219
|
hj /= 2;
|
|
156
220
|
}
|
|
@@ -83,7 +83,7 @@ export interface UnirootOptions {
|
|
|
83
83
|
maxiter?: number;
|
|
84
84
|
/**
|
|
85
85
|
* Extend the interval when f has the same sign at both ends: `"yes"` (both ways), `"downX"` (f decreasing),
|
|
86
|
-
* `"upX"` (f increasing) or `"no"` (default).
|
|
86
|
+
* `"upX"` (f increasing) or `"no"` (default). A unique prefix is accepted and anything else is an error, as in R.
|
|
87
87
|
*/
|
|
88
88
|
extendInt?: "no" | "yes" | "downX" | "upX";
|
|
89
89
|
/** f(lower), when already known. */
|
|
@@ -119,3 +119,11 @@ export interface UnirootResult {
|
|
|
119
119
|
* @category Numerical methods
|
|
120
120
|
*/
|
|
121
121
|
export declare function uniroot(f: (x: number) => number, lower: number, upper: number, options?: UnirootOptions): UnirootResult;
|
|
122
|
+
/**
|
|
123
|
+
* {@link uniroot} without the check of tol > 0: the internal callers that run Brent's method until the bracket is as
|
|
124
|
+
* narrow as the doubles allow (tol = 0, the noncentrality roots of src/htest/effectSize.ts) or whose tolerance is
|
|
125
|
+
* scaled by a standard error (src/internal/uniroot.ts)
|
|
126
|
+
*
|
|
127
|
+
* @internal
|
|
128
|
+
*/
|
|
129
|
+
export declare function unirootCore(f: (x: number) => number, lower: number, upper: number, options?: UnirootOptions): UnirootResult;
|
|
@@ -10,6 +10,11 @@
|
|
|
10
10
|
// largest finite numbers, and the result reports the iterations and Brent's estimate of the precision.
|
|
11
11
|
import { dqagie, dqagse } from "../integrate/quadpack.js";
|
|
12
12
|
import { localMin } from "../optim/localmin.js";
|
|
13
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
14
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
15
|
+
const INTEGRATE_KEYS = ["subdivisions", "relTol", "absTol", "stopOnError"];
|
|
16
|
+
const OPTIMIZE_KEYS = ["maximum", "tol"];
|
|
17
|
+
const UNIROOT_KEYS = ["tol", "maxiter", "extendInt", "fLower", "fUpper"];
|
|
13
18
|
const MESSAGES = [
|
|
14
19
|
"OK",
|
|
15
20
|
"maximum number of subdivisions reached",
|
|
@@ -31,9 +36,17 @@ const TOL = Number.EPSILON ** 0.25;
|
|
|
31
36
|
* @category Numerical methods
|
|
32
37
|
*/
|
|
33
38
|
export function integrate(f, lower, upper, options = {}) {
|
|
34
|
-
|
|
39
|
+
checkOptions(options, INTEGRATE_KEYS, "integrate"); // generated: option-keys.mjs
|
|
40
|
+
const subdivisions = options.subdivisions ?? 100;
|
|
41
|
+
const limit = Math.trunc(subdivisions);
|
|
35
42
|
const relTol = options.relTol ?? TOL;
|
|
36
43
|
const absTol = options.absTol ?? relTol;
|
|
44
|
+
// infinite or negative tolerances are errors (R accepts an infinite one and returns the first, coarse estimate as converged);
|
|
45
|
+
// subdivisions as R's as.integer: beyond the integer range it is NA and an error in R (2^32 reached the typed-array
|
|
46
|
+
// allocation, #369)
|
|
47
|
+
if (!(Math.abs(subdivisions) <= 2147483647) || !Number.isFinite(relTol) || !Number.isFinite(absTol) || relTol < 0 || absTol < 0) {
|
|
48
|
+
throw new RangeError("invalid parameter values");
|
|
49
|
+
}
|
|
37
50
|
const stopOnError = options.stopOnError ?? true;
|
|
38
51
|
if (Number.isNaN(lower) || Number.isNaN(upper))
|
|
39
52
|
throw new RangeError("a limit is NA or NaN");
|
|
@@ -45,19 +58,42 @@ export function integrate(f, lower, upper, options = {}) {
|
|
|
45
58
|
throw new RangeError("non-finite function value");
|
|
46
59
|
return v;
|
|
47
60
|
};
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
61
|
+
// An infinite limit is taken with its sign: from a to -Inf is minus the integral over (-Inf, a), from Inf to b minus
|
|
62
|
+
// that over (b, Inf), from Inf to -Inf minus the whole line (R integrates over (a, Inf) and (-Inf, Inf) there, so
|
|
63
|
+
// integrate(f, 0, -Inf) had the sign and the side wrong), and between equal infinite limits 0
|
|
64
|
+
if (lower === upper && !Number.isFinite(lower))
|
|
65
|
+
return { value: 0, absError: 0, subdivisions: 0, ier: 0, message: MESSAGES[0] };
|
|
66
|
+
let sign = 1;
|
|
67
|
+
if (lower === Infinity || upper === -Infinity) {
|
|
68
|
+
[lower, upper] = [upper, lower];
|
|
69
|
+
sign = -1;
|
|
70
|
+
}
|
|
71
|
+
let r;
|
|
72
|
+
if (Number.isFinite(lower) && Number.isFinite(upper)) {
|
|
73
|
+
// b - a or a midpoint of the subintervals (up to 2 max(|a|, |b|)) overflows (both finite): x = 2u, the integral of
|
|
74
|
+
// f(2u) over (a/2, b/2) doubled, with the same nodes (it ended in "roundoff error" for a density spread over
|
|
75
|
+
// (-1e308, 1e308), and 1/x over (1e308, 1.1e308) was 0 with every node at Inf)
|
|
76
|
+
if (Number.isFinite(2 * Math.max(Math.abs(lower), Math.abs(upper))))
|
|
77
|
+
r = dqagse(g, lower, upper, absTol, relTol, limit);
|
|
78
|
+
else {
|
|
79
|
+
// (a positive absTol kept positive: MIN halved to 0 made the input invalid; issue #122)
|
|
80
|
+
const halfTol = absTol > 0 ? Math.max(absTol * 0.5, Number.MIN_VALUE) : absTol * 0.5;
|
|
81
|
+
const h = dqagse((u) => g(2 * u), lower * 0.5, upper * 0.5, halfTol, relTol, limit);
|
|
82
|
+
r = { ...h, result: 2 * h.result, abserr: 2 * h.abserr };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
else if (Number.isFinite(lower))
|
|
86
|
+
r = dqagie(g, lower, 1, absTol, relTol, limit);
|
|
87
|
+
else if (Number.isFinite(upper))
|
|
88
|
+
r = dqagie(g, upper, -1, absTol, relTol, limit);
|
|
89
|
+
else
|
|
90
|
+
r = dqagie(g, 0, 2, absTol, relTol, limit);
|
|
55
91
|
const message = MESSAGES[r.ier] ?? "unknown error";
|
|
56
92
|
if (r.ier === 6)
|
|
57
93
|
throw new RangeError("the input is invalid");
|
|
58
94
|
if (r.ier !== 0 && stopOnError)
|
|
59
95
|
throw new RangeError(message);
|
|
60
|
-
return { value: r.result, absError: r.abserr, subdivisions: r.last, ier: r.ier, message };
|
|
96
|
+
return { value: sign * r.result, absError: r.abserr, subdivisions: r.last, ier: r.ier, message };
|
|
61
97
|
}
|
|
62
98
|
/**
|
|
63
99
|
* Minimum (or maximum) of a function of one variable on an interval, by Brent's golden-section and parabolic
|
|
@@ -72,8 +108,12 @@ export function integrate(f, lower, upper, options = {}) {
|
|
|
72
108
|
* @category Numerical methods
|
|
73
109
|
*/
|
|
74
110
|
export function optimize(f, lower, upper, options = {}) {
|
|
111
|
+
checkOptions(options, OPTIMIZE_KEYS, "optimize"); // generated: option-keys.mjs
|
|
75
112
|
const maximum = options.maximum ?? false;
|
|
76
113
|
const tol = options.tol ?? TOL;
|
|
114
|
+
// (a positive tol, as in R: with tol = 0 the search stopped narrowing among the subnormals, see localMin)
|
|
115
|
+
if (!(tol > 0 && tol < Infinity))
|
|
116
|
+
throw new RangeError("'tol' must be a positive finite number");
|
|
77
117
|
// R checks the ends before calling f, lower first
|
|
78
118
|
if (!Number.isFinite(lower))
|
|
79
119
|
throw new RangeError("invalid 'xmin' value");
|
|
@@ -81,8 +121,36 @@ export function optimize(f, lower, upper, options = {}) {
|
|
|
81
121
|
throw new RangeError("invalid 'xmax' value");
|
|
82
122
|
if (!(lower < upper))
|
|
83
123
|
throw new RangeError("'xmin' not less than 'xmax'");
|
|
84
|
-
|
|
85
|
-
|
|
124
|
+
// as R, the search sees NaN and +Inf as the largest double and -Inf as the most negative (R warns, "NA/NaN replaced
|
|
125
|
+
// by maximum positive value"; the library does not report warnings); objective is f itself
|
|
126
|
+
const fn = (x) => {
|
|
127
|
+
const v = maximum ? -f(x) : f(x);
|
|
128
|
+
return Number.isNaN(v) || v === Infinity ? Number.MAX_VALUE : v === -Infinity ? -Number.MAX_VALUE : v;
|
|
129
|
+
};
|
|
130
|
+
// upper - lower or upper + lower overflows (both finite): search over u = x/2 on (lower/2, upper/2) with tol/2 (the
|
|
131
|
+
// search did not return: optimize((x / 1e308)^2, -1e308, 1e308), and with the midpoint 0.5 (a + b) = Infinity,
|
|
132
|
+
// optimize((x / 1e308 - 1.05)^2, 1e308, 1.1e308); R too); also where an end is beyond Number.MAX_VALUE / 2, as the
|
|
133
|
+
// midpoint of a bracket narrowed near it overflows (optimize((x / 1e308 + 1.6)^2, -1.7e308, 1e306), #212)
|
|
134
|
+
// (2 lower and 2 upper finite imply that upper - lower and upper + lower are)
|
|
135
|
+
const x = Number.isFinite(2 * lower) && Number.isFinite(2 * upper)
|
|
136
|
+
? localMin(fn, lower, upper, tol).x
|
|
137
|
+
: 2 * localMin((u) => fn(2 * u), lower * 0.5, upper * 0.5, tol * 0.5).x;
|
|
138
|
+
return { optimum: x, objective: f(x) };
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* extendInt of uniroot, as R's match.arg(extendInt) against c("no", "yes", "downX", "upX"): the full name or a
|
|
142
|
+
* unique prefix; anything else is an error before f is evaluated (it was taken as "no", #247)
|
|
143
|
+
*/
|
|
144
|
+
function extendIntArg(e) {
|
|
145
|
+
if (e === undefined)
|
|
146
|
+
return "no";
|
|
147
|
+
const choices = ["no", "yes", "downX", "upX"];
|
|
148
|
+
if (typeof e === "string" && e.length > 0) {
|
|
149
|
+
const hit = choices.filter((v) => v.startsWith(e));
|
|
150
|
+
if (hit.length === 1)
|
|
151
|
+
return hit[0];
|
|
152
|
+
}
|
|
153
|
+
throw new RangeError(`'extendInt' should be one of "no", "yes", "downX", "upX"`);
|
|
86
154
|
}
|
|
87
155
|
/**
|
|
88
156
|
* A root of a function of one variable in an interval, by Brent's zeroin. Equivalent to R's `uniroot()`.
|
|
@@ -95,9 +163,28 @@ export function optimize(f, lower, upper, options = {}) {
|
|
|
95
163
|
* @category Numerical methods
|
|
96
164
|
*/
|
|
97
165
|
export function uniroot(f, lower, upper, options = {}) {
|
|
166
|
+
checkOptions(options, UNIROOT_KEYS, "uniroot"); // generated: option-keys.mjs
|
|
167
|
+
// R's "invalid 'tol' value" for tol <= 0 (tol = 0 was accepted, Brent's method then ran to maxiter or the doubles)
|
|
168
|
+
const tol = options.tol ?? TOL;
|
|
169
|
+
if (!(tol > 0 && tol < Infinity))
|
|
170
|
+
throw new RangeError("'tol' must be a positive finite number");
|
|
171
|
+
return unirootCore(f, lower, upper, options);
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* {@link uniroot} without the check of tol > 0: the internal callers that run Brent's method until the bracket is as
|
|
175
|
+
* narrow as the doubles allow (tol = 0, the noncentrality roots of src/htest/effectSize.ts) or whose tolerance is
|
|
176
|
+
* scaled by a standard error (src/internal/uniroot.ts)
|
|
177
|
+
*
|
|
178
|
+
* @internal
|
|
179
|
+
*/
|
|
180
|
+
export function unirootCore(f, lower, upper, options = {}) {
|
|
98
181
|
const tol = options.tol ?? TOL;
|
|
99
|
-
const maxiter = options.maxiter ?? 1000;
|
|
100
|
-
|
|
182
|
+
const maxiter = Math.trunc(options.maxiter ?? 1000);
|
|
183
|
+
if (!(tol >= 0 && tol < Infinity))
|
|
184
|
+
throw new RangeError("'tol' must be a non-negative finite number");
|
|
185
|
+
if (!(maxiter >= 1 && maxiter < Infinity))
|
|
186
|
+
throw new RangeError("'maxiter' must be a positive integer");
|
|
187
|
+
const extendInt = extendIntArg(options.extendInt);
|
|
101
188
|
if (!(lower < upper))
|
|
102
189
|
throw new RangeError("lower < upper is not fulfilled");
|
|
103
190
|
let fLo = options.fLower ?? f(lower);
|
|
@@ -110,7 +197,9 @@ export function uniroot(f, lower, upper, options = {}) {
|
|
|
110
197
|
const bound = (v) => Math.max(-Number.MAX_VALUE, Math.min(Number.MAX_VALUE, v));
|
|
111
198
|
const step0 = (u) => 0.01 * Math.max(1e-4, Math.abs(u));
|
|
112
199
|
const sig = extendInt === "downX" ? -1 : extendInt === "upX" ? 1 : 0;
|
|
113
|
-
|
|
200
|
+
// same sign from the signs, not the product (1e-300 * 2e-300 underflows to 0, and the interval was not extended)
|
|
201
|
+
const sameSign = (a, b) => Math.sign(a) * Math.sign(b) > 0;
|
|
202
|
+
const extend = extendInt === "yes" ? sameSign(fLo, fUp) : sig !== 0 && (sig * bound(fLo) > 0 || sig * bound(fUp) < 0);
|
|
114
203
|
let extIter = 0;
|
|
115
204
|
const count = () => {
|
|
116
205
|
if (++extIter > maxiter)
|
|
@@ -119,7 +208,7 @@ export function uniroot(f, lower, upper, options = {}) {
|
|
|
119
208
|
if (extend && extendInt === "yes") {
|
|
120
209
|
let dLo = step0(lower);
|
|
121
210
|
let dUp = step0(upper);
|
|
122
|
-
while (fLo
|
|
211
|
+
while (sameSign(fLo, fUp) && (Number.isFinite(lower) || Number.isFinite(upper))) {
|
|
123
212
|
count();
|
|
124
213
|
if (Number.isFinite(lower)) {
|
|
125
214
|
const x = lower - dLo;
|
|
@@ -165,7 +254,13 @@ export function uniroot(f, lower, upper, options = {}) {
|
|
|
165
254
|
throw new RangeError("invalid 'xmin' value");
|
|
166
255
|
if (!Number.isFinite(upper))
|
|
167
256
|
throw new RangeError("invalid 'xmax' value");
|
|
168
|
-
|
|
257
|
+
// upper - lower overflows (both finite): the root of f(2u) on (lower/2, upper/2) with tol/2, doubled (uniroot(x,
|
|
258
|
+
// -1e308, 1e308) gave -Infinity)
|
|
259
|
+
const wide = !Number.isFinite(upper - lower);
|
|
260
|
+
const zh = wide
|
|
261
|
+
? zero((u) => finiteValue(f(2 * u)), lower * 0.5, upper * 0.5, finiteValue(fLo), finiteValue(fUp), tol * 0.5, maxiter)
|
|
262
|
+
: zero((x) => finiteValue(f(x)), lower, upper, finiteValue(fLo), finiteValue(fUp), tol, maxiter);
|
|
263
|
+
const z = wide ? { ...zh, root: 2 * zh.root, estimPrec: 2 * zh.estimPrec } : zh;
|
|
169
264
|
return {
|
|
170
265
|
root: z.root,
|
|
171
266
|
fRoot: f(z.root),
|