@numero-uno-jpn/rstats 0.16.0 → 1.0.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 +205 -0
- package/README.ja.md +57 -23
- package/README.md +60 -23
- package/dist/chunks/{chunk-5UQCRBAG.js → chunk-3W5NFFAA.js} +1 -1
- package/dist/chunks/chunk-4F2IALD4.js +3 -0
- package/dist/chunks/{chunk-QNNL7AZ3.js → chunk-4OLDGML4.js} +2 -2
- package/dist/chunks/chunk-63OPBEYO.js +2 -0
- package/dist/chunks/chunk-6XJBCRBV.js +2 -0
- package/dist/chunks/chunk-BQSIBJVX.js +2 -0
- package/dist/chunks/chunk-BWKHYRM6.js +3 -0
- package/dist/chunks/{chunk-W26LRYOJ.js → chunk-CKV4JWW2.js} +1 -1
- package/dist/chunks/chunk-DCAWMF4K.js +2 -0
- package/dist/chunks/chunk-F7YGX7PN.js +2 -0
- package/dist/chunks/chunk-H7I32ZZE.js +2 -0
- package/dist/chunks/chunk-IEOD5GWC.js +3 -0
- package/dist/chunks/chunk-KICBQGFN.js +2 -0
- package/dist/chunks/chunk-LROMWFAK.js +2 -0
- package/dist/chunks/chunk-NSWENS3S.js +2 -0
- package/dist/chunks/chunk-O2SQMGE3.js +2 -0
- package/dist/chunks/chunk-QQX46TCI.js +2 -0
- package/dist/chunks/chunk-QZK3CCBA.js +2 -0
- package/dist/chunks/chunk-UJ66VQIG.js +2 -0
- package/dist/chunks/chunk-UKNDX4BA.js +2 -0
- package/dist/chunks/chunk-WIBKS73G.js +2 -0
- package/dist/chunks/{chunk-URIO5LY5.js → chunk-WQWZ7FND.js} +2 -2
- package/dist/chunks/chunk-WWVMVZUL.js +2 -0
- package/dist/chunks/chunk-YG5S5AVP.js +2 -0
- package/dist/chunks/chunk-YHNMBYSW.js +2 -0
- package/dist/data/grouping.js +6 -2
- package/dist/descriptive/basic.js +20 -0
- package/dist/descriptive/cov.js +11 -0
- package/dist/descriptive/dataFrames.js +13 -5
- package/dist/descriptive/factanal.d.ts +2 -0
- package/dist/descriptive/factanal.js +10 -2
- package/dist/descriptive/hist.js +6 -0
- package/dist/descriptive/moments.js +14 -0
- package/dist/descriptive/omega.js +8 -3
- package/dist/descriptive/pivot.d.ts +4 -1
- package/dist/descriptive/pivot.js +27 -13
- package/dist/descriptive/quantile.js +8 -0
- package/dist/descriptive/rank.js +4 -0
- package/dist/descriptive/table.d.ts +20 -1
- package/dist/descriptive/table.js +14 -14
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +8 -0
- package/dist/distributions/beta.js +9 -0
- package/dist/distributions/binomial.js +9 -0
- package/dist/distributions/cauchy.js +9 -0
- package/dist/distributions/chisq.js +9 -0
- package/dist/distributions/exponential.js +9 -0
- package/dist/distributions/f.js +9 -0
- package/dist/distributions/gamma.js +8 -0
- package/dist/distributions/geometric.js +9 -0
- package/dist/distributions/hypergeometric.js +8 -0
- package/dist/distributions/invgamma.js +8 -0
- package/dist/distributions/kumaraswamy.js +9 -0
- package/dist/distributions/laplace.js +9 -0
- package/dist/distributions/logistic.js +9 -0
- package/dist/distributions/lognormal.js +8 -0
- package/dist/distributions/multinomial.js +4 -0
- package/dist/distributions/negbinomial.js +8 -0
- package/dist/distributions/normal.js +8 -0
- package/dist/distributions/pareto.js +8 -0
- package/dist/distributions/poisson.js +9 -0
- package/dist/distributions/signrank.js +9 -0
- package/dist/distributions/summary.d.ts +2 -1
- package/dist/distributions/summary.js +31 -1
- package/dist/distributions/t.js +9 -0
- package/dist/distributions/triangular.js +9 -0
- package/dist/distributions/tukey.js +6 -0
- package/dist/distributions/uniform.js +8 -0
- package/dist/distributions/weibull.js +8 -0
- package/dist/distributions/wilcox.js +9 -0
- 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 +9 -0
- package/dist/entries/mixed.js +8 -1
- 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 +13 -0
- package/dist/htest/agreement.js +46 -7
- package/dist/htest/ansariTest.d.ts +2 -1
- package/dist/htest/ansariTest.js +43 -12
- package/dist/htest/aov.d.ts +28 -22
- package/dist/htest/aov.js +42 -13
- package/dist/htest/binomTest.js +6 -0
- package/dist/htest/brunnerMunzelTest.js +5 -0
- package/dist/htest/chisqTest.d.ts +3 -1
- package/dist/htest/chisqTest.js +21 -3
- package/dist/htest/cor.d.ts +7 -1
- package/dist/htest/cor.js +40 -7
- package/dist/htest/core/simulate.d.ts +6 -0
- package/dist/htest/core/simulate.js +20 -0
- package/dist/htest/effectSize.d.ts +3 -0
- package/dist/htest/effectSize.js +28 -8
- package/dist/htest/fisherTest.d.ts +2 -1
- package/dist/htest/fisherTest.js +52 -6
- package/dist/htest/ksTest.d.ts +4 -0
- package/dist/htest/ksTest.js +13 -4
- package/dist/htest/leveneTest.d.ts +2 -0
- package/dist/htest/leveneTest.js +9 -3
- package/dist/htest/mantelhaenTest.js +7 -0
- package/dist/htest/mcnemarTest.js +8 -0
- package/dist/htest/multipleComparisons.d.ts +16 -25
- package/dist/htest/multipleComparisons.js +26 -43
- package/dist/htest/normalityTests.js +10 -4
- package/dist/htest/onewayTest.js +10 -0
- package/dist/htest/pAdjust.js +4 -0
- package/dist/htest/pairwise.d.ts +2 -0
- package/dist/htest/pairwise.js +29 -6
- package/dist/htest/poissonTest.js +6 -0
- package/dist/htest/polycor.js +20 -10
- package/dist/htest/power.d.ts +4 -0
- package/dist/htest/power.js +16 -2
- package/dist/htest/propTest.d.ts +3 -0
- package/dist/htest/propTest.js +23 -2
- package/dist/htest/pwr.d.ts +38 -1
- package/dist/htest/pwr.js +38 -15
- package/dist/htest/rankTests.js +7 -1
- package/dist/htest/tTest.d.ts +2 -0
- package/dist/htest/tTest.js +9 -0
- package/dist/htest/testFormula.js +11 -11
- package/dist/htest/trendTests.d.ts +21 -1
- package/dist/htest/trendTests.js +13 -18
- package/dist/htest/types.d.ts +2 -0
- package/dist/htest/varTest.js +7 -0
- package/dist/htest/wilcoxTest.js +51 -9
- package/dist/internal/checkOptions.d.ts +11 -0
- package/dist/internal/checkOptions.js +31 -0
- package/dist/internal/optionalArgs.d.ts +12 -0
- package/dist/internal/optionalArgs.js +46 -0
- package/dist/internal/warnings.d.ts +66 -0
- package/dist/internal/warnings.js +122 -0
- package/dist/linalg/basic.js +7 -0
- package/dist/linalg/chol.js +6 -0
- package/dist/linalg/eigen.js +4 -0
- package/dist/linalg/expm.js +4 -0
- package/dist/linalg/kappa.js +6 -0
- package/dist/linalg/lu.js +5 -0
- package/dist/linalg/norm.js +4 -0
- package/dist/linalg/ops.d.ts +27 -2
- package/dist/linalg/ops.js +14 -13
- package/dist/linalg/qr.js +14 -0
- package/dist/linalg/solve.js +9 -0
- package/dist/linalg/svd.js +6 -2
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +5 -4
- package/dist/models/anovaSequential.d.ts +16 -1
- package/dist/models/anovaSequential.js +50 -7
- package/dist/models/aovEz.js +16 -11
- package/dist/models/aovStrata.js +15 -4
- package/dist/models/carAnova.js +11 -17
- package/dist/models/coxph.d.ts +6 -0
- package/dist/models/coxph.js +21 -6
- package/dist/models/formula.d.ts +5 -2
- package/dist/models/formula.js +31 -8
- package/dist/models/glm.d.ts +22 -2
- package/dist/models/glm.js +32 -22
- package/dist/models/glmAnova.js +8 -3
- package/dist/models/glmConfint.js +6 -2
- package/dist/models/glmFamily.d.ts +1 -6
- package/dist/models/glmFamily.js +3 -22
- package/dist/models/glmer.d.ts +255 -0
- package/dist/models/glmer.js +635 -0
- package/dist/models/glmerAnova.d.ts +81 -0
- package/dist/models/glmerAnova.js +139 -0
- package/dist/models/glmerDeviance.d.ts +98 -0
- package/dist/models/glmerDeviance.js +576 -0
- package/dist/models/glmerFamily.d.ts +57 -0
- package/dist/models/glmerFamily.js +236 -0
- package/dist/models/glmerGradient.d.ts +46 -0
- package/dist/models/glmerGradient.js +301 -0
- package/dist/models/glmerStructure.d.ts +45 -0
- package/dist/models/glmerStructure.js +168 -0
- package/dist/models/glmerSummary.d.ts +102 -0
- package/dist/models/glmerSummary.js +94 -0
- package/dist/models/lm.js +13 -3
- package/dist/models/lmer.d.ts +27 -6
- package/dist/models/lmer.js +75 -321
- package/dist/models/lmerAnova.d.ts +52 -3
- package/dist/models/lmerAnova.js +101 -45
- package/dist/models/lmerTest.d.ts +12 -5
- package/dist/models/lmerTest.js +39 -18
- package/dist/models/mauchly.d.ts +2 -0
- package/dist/models/mauchly.js +7 -2
- package/dist/models/mixedDeviance.d.ts +28 -2
- package/dist/models/mixedDeviance.js +84 -56
- package/dist/models/mixedMinimiser.d.ts +83 -0
- package/dist/models/mixedMinimiser.js +438 -0
- package/dist/models/mixedPredict.d.ts +121 -0
- package/dist/models/mixedPredict.js +530 -0
- package/dist/models/mixedStructure.d.ts +62 -3
- package/dist/models/mixedStructure.js +74 -29
- package/dist/models/modelFrame.js +2 -2
- package/dist/models/modelMatrix.d.ts +8 -1
- package/dist/models/modelMatrix.js +56 -39
- package/dist/models/survival.d.ts +6 -0
- package/dist/models/survival.js +9 -2
- package/dist/numerics/deriv.js +8 -0
- package/dist/numerics/integrate.js +8 -0
- package/dist/numerics/interp.d.ts +32 -7
- package/dist/numerics/interp.js +27 -9
- package/dist/numerics/ode.js +4 -0
- package/dist/numerics.js +2 -2
- package/dist/optim/optim.js +17 -2
- package/dist/random/beta.js +5 -0
- package/dist/random/continuous.js +17 -0
- package/dist/random/extra.js +13 -0
- package/dist/random/gamma.js +11 -0
- package/dist/random/poisson.js +5 -0
- package/dist/random/rng.js +4 -0
- package/dist/random/sample.js +6 -0
- package/dist/rstats.js +17 -14
- package/dist/special/besselIK.js +7 -0
- package/dist/special/choose.js +7 -0
- package/dist/special/psigamma.js +7 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +14 -11
- package/llms.txt +15 -4
- package/package.json +19 -10
- package/dist/chunks/chunk-2D2IQWUQ.js +0 -2
- package/dist/chunks/chunk-6CSTWA5E.js +0 -2
- package/dist/chunks/chunk-72Y3HZID.js +0 -2
- package/dist/chunks/chunk-BG2KLEHM.js +0 -2
- package/dist/chunks/chunk-CMEKBNHQ.js +0 -2
- package/dist/chunks/chunk-FLJNSXSW.js +0 -2
- package/dist/chunks/chunk-GM53LWSR.js +0 -2
- package/dist/chunks/chunk-JBCA56ZS.js +0 -3
- package/dist/chunks/chunk-K3RJAD2T.js +0 -2
- package/dist/chunks/chunk-KAZRWIB5.js +0 -2
- package/dist/chunks/chunk-KBVVIMXX.js +0 -3
- package/dist/chunks/chunk-N3SIFCZX.js +0 -2
- package/dist/chunks/chunk-SC6CV4Z3.js +0 -2
- package/dist/chunks/chunk-SYWOBOTR.js +0 -2
- package/dist/chunks/chunk-VTUGG2SV.js +0 -2
- package/dist/chunks/chunk-XHETEYVC.js +0 -2
- package/dist/chunks/chunk-YRZWONZB.js +0 -3
- package/dist/chunks/chunk-ZGABZMWX.js +0 -2
|
@@ -13,6 +13,12 @@
|
|
|
13
13
|
// level-major within each term, and Λ_θ is block diagonal with one lower-triangular block per level of each term,
|
|
14
14
|
// whose parameters are its lower triangle in column-major order. Aliased columns of X (pivoted QR of lm, tolerance
|
|
15
15
|
// 1e-7) are dropped with a message; predictors on very different scales give a warning.
|
|
16
|
+
//
|
|
17
|
+
// The structure of a generalised linear mixed model (lme4's glmer, oracle/glmer-behaviour.md, "The structure and its
|
|
18
|
+
// checks") is the same with three differences in the checks: no row left is "Invalid grouping factor specification"
|
|
19
|
+
// with the first grouping factor's name, a grouping factor may have as many levels as there are rows, and a term may
|
|
20
|
+
// have as many random effects as there are rows. Its response may be of any type (or `cbind(a, b)`); the family
|
|
21
|
+
// reads it (src/models/glmerStructure.ts).
|
|
16
22
|
import { formatR } from "../htest/core/simulate.js";
|
|
17
23
|
import { qr } from "../linalg/qr.js";
|
|
18
24
|
import { deparseFormula, expandRhs, parseFormula, splitBarTerms, termsOf } from "./formula.js";
|
|
@@ -79,52 +85,46 @@ function asFactor(v) {
|
|
|
79
85
|
return { levels, codes: v.values.map((x) => index.get(formatR(x))) };
|
|
80
86
|
}
|
|
81
87
|
/**
|
|
82
|
-
* The
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
* @param formula A formula such as `"y ~ x + (x | g)"`, `"y ~ (1 | a/b)"` or `"y ~ (x || g)"`.
|
|
87
|
-
* @param data The data frame: an object of columns.
|
|
88
|
-
* @param options The contrasts (fixed-effects part only) and the level order of factors.
|
|
88
|
+
* The fixed-effects part of a mixed model (internal, also for prediction): the formula without the random-effects
|
|
89
|
+
* terms, `response ~ fixed part`, as lm codes it (the order of its variables names the interaction columns); its model
|
|
90
|
+
* frame has the variables of the whole formula too, so that every model matrix of the structure uses the same rows.
|
|
89
91
|
*/
|
|
90
|
-
export function
|
|
91
|
-
const parsed = parseFormula(formula, false, true);
|
|
92
|
+
export function fixedPartDesign(formula, data, options = {}, generalised = false) {
|
|
93
|
+
const parsed = parseFormula(formula, false, true, generalised);
|
|
92
94
|
if (parsed.response === undefined)
|
|
93
95
|
throw new TypeError("the formula has no response");
|
|
94
96
|
const { fixed, bars } = splitBarTerms(parsed.rhs);
|
|
95
97
|
if (typeof data !== "object" || data === null)
|
|
96
98
|
throw new TypeError("data must be an object of columns");
|
|
97
|
-
// the fixed-effects part: the formula without the random-effects terms, `response ~ fixed part`, as lm codes it (the
|
|
98
|
-
// order of its variables names the interaction columns); its model frame has the variables of the whole formula too,
|
|
99
|
-
// so that every model matrix below uses the same rows
|
|
100
99
|
const frameOptions = {
|
|
101
100
|
...(options.levels === undefined ? {} : { levels: options.levels }),
|
|
102
101
|
dropUnusedLevels: true,
|
|
103
102
|
};
|
|
104
103
|
// (if nothing is left of the right-hand side, the fixed part is `1`)
|
|
105
104
|
const fixedRhs = fixed ?? { type: "num", value: 1, text: "1" };
|
|
106
|
-
const fixedFormula = {
|
|
105
|
+
const fixedFormula = { ...parsed, rhs: fixedRhs };
|
|
107
106
|
// the variables of the whole formula (in the model frame, those of the fixed part come first, in its order)
|
|
108
107
|
const allVariables = termsOf(parsed, Object.keys(data), fixedRhs).variables;
|
|
109
108
|
// (a contrast is for a variable of the fixed-effects part: a grouping variable alone counts as absent)
|
|
110
109
|
const contrastOptions = options.contrasts === undefined ? {} : { contrasts: options.contrasts };
|
|
111
|
-
|
|
112
|
-
const {
|
|
113
|
-
const
|
|
114
|
-
if (n === 0)
|
|
115
|
-
throw new RangeError("0 (non-NA) cases");
|
|
116
|
-
// (the model frame's errors, above, come before this check)
|
|
117
|
-
if (bars.length === 0)
|
|
118
|
-
throw new Error("No random effects terms specified in formula");
|
|
110
|
+
// (a generalised model's response may be of any type: the family reads it)
|
|
111
|
+
const responseOptions = generalised ? { anyResponse: true } : {};
|
|
112
|
+
const fixedDesign = design(fixedFormula, data, { ...frameOptions, ...contrastOptions, ...responseOptions, extraVariables: allVariables }, fixedRhs);
|
|
119
113
|
const variables = [...fixedDesign.terms.variables, ...allVariables.filter((v) => !fixedDesign.terms.variables.includes(v))];
|
|
120
|
-
|
|
114
|
+
return { parsed, bars, fixedDesign, variables, frameOptions, responseOptions };
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The random-effects terms `bars` of a formula expanded (internal): `(lhs || group)` split into one term per term of
|
|
118
|
+
* lhs, then each term by the grouping factors of its expression; `noColumns` is the first bar term (in the formula's
|
|
119
|
+
* order) that `||` leaves without columns.
|
|
120
|
+
*/
|
|
121
|
+
export function expandRandomTerms(parsed, columns, bars) {
|
|
121
122
|
const expanded = [];
|
|
122
|
-
/** The first bar term (in the formula's order) without columns */
|
|
123
123
|
let noColumns;
|
|
124
124
|
bars.forEach((bar, barIndex) => {
|
|
125
125
|
let lhsList = [bar.lhs];
|
|
126
126
|
if (bar.double) {
|
|
127
|
-
const lhsTerms = termsOf(parsed,
|
|
127
|
+
const lhsTerms = termsOf(parsed, columns, bar.lhs);
|
|
128
128
|
lhsList = lhsTerms.intercept ? [{ type: "num", value: 1, text: "1" }] : [];
|
|
129
129
|
for (const t of lhsTerms.terms) {
|
|
130
130
|
const term = t.map((v) => ({ type: "var", name: lhsTerms.variables[v] })).reduce((l, r) => ({ type: "binary", op: ":", left: l, right: r }));
|
|
@@ -138,6 +138,35 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
138
138
|
for (const groupVariables of factors)
|
|
139
139
|
expanded.push({ lhs, groupVariables, bar: barIndex });
|
|
140
140
|
});
|
|
141
|
+
return { expanded, noColumns };
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The structure of a linear mixed model `response ~ fixed part + (lhs | group) + ...`: the model frame, X, Z, the
|
|
145
|
+
* layout of Λ_θ, the initial θ and its lower bounds, with lme4's checks, errors, messages and warnings
|
|
146
|
+
* (oracle/lmer-behaviour.md, stage 1a). Internal: not exported from the package.
|
|
147
|
+
*
|
|
148
|
+
* @param formula A formula such as `"y ~ x + (x | g)"`, `"y ~ (1 | a/b)"` or `"y ~ (x || g)"`.
|
|
149
|
+
* @param data The data frame: an object of columns.
|
|
150
|
+
* @param options The contrasts (fixed-effects part only) and the level order of factors.
|
|
151
|
+
* @param generalised The structure of a generalised model (glmer): its checks, a response of any type or `cbind(a, b)`.
|
|
152
|
+
*/
|
|
153
|
+
export function mixedModelStructure(formula, data, options = {}, generalised = false) {
|
|
154
|
+
const { parsed, bars, fixedDesign, variables, frameOptions, responseOptions } = fixedPartDesign(formula, data, options, generalised);
|
|
155
|
+
const { frame } = fixedDesign;
|
|
156
|
+
const n = frame.rows.length;
|
|
157
|
+
// (glmer: no row left is an error about the first grouping factor, below)
|
|
158
|
+
if (n === 0 && !generalised)
|
|
159
|
+
throw new RangeError("0 (non-NA) cases");
|
|
160
|
+
// (the model frame's errors, above, come before this check)
|
|
161
|
+
if (bars.length === 0)
|
|
162
|
+
throw new Error("No random effects terms specified in formula");
|
|
163
|
+
const { expanded, noColumns: noColumnsOfBars } = expandRandomTerms(parsed, Object.keys(data), bars);
|
|
164
|
+
/** The first bar term (in the formula's order) without columns */
|
|
165
|
+
let noColumns = noColumnsOfBars;
|
|
166
|
+
// glmer without a row left: lme4 fails on the first grouping factor in the order of the terms after expansion and
|
|
167
|
+
// before their reordering
|
|
168
|
+
if (n === 0)
|
|
169
|
+
throw new RangeError(`Invalid grouping factor specification, ${expanded[0]?.groupVariables.join(":") ?? ""}`);
|
|
141
170
|
// the grouping factors (levels present, ordered by the levels of the first variable, then the second, ...)
|
|
142
171
|
const factorCache = new Map();
|
|
143
172
|
const factorOf = (vs) => {
|
|
@@ -193,7 +222,7 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
193
222
|
groups.push({ name: t.name, levels: t.factor.levels, codes: t.factor.codes });
|
|
194
223
|
}
|
|
195
224
|
// the left-hand side: treatment contrasts whatever the options say
|
|
196
|
-
const lhsDesign = design(parsed, data, frameOptions, t.lhs);
|
|
225
|
+
const lhsDesign = design(parsed, data, { ...frameOptions, ...responseOptions }, t.lhs);
|
|
197
226
|
const nc = lhsDesign.colNames.length;
|
|
198
227
|
if (nc === 0 && (noColumns === undefined || t.bar < noColumns))
|
|
199
228
|
noColumns = t.bar;
|
|
@@ -217,13 +246,19 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
217
246
|
}
|
|
218
247
|
if (groups.some((g) => g.levels.length < 2))
|
|
219
248
|
throw new RangeError("grouping factors must have > 1 sampled level");
|
|
220
|
-
|
|
249
|
+
// (glmer: a grouping factor may have as many levels as there are rows, and a term as many random effects: there is
|
|
250
|
+
// no residual variance to identify)
|
|
251
|
+
const tooMany = generalised ? [] : groups.filter((g) => g.levels.length >= n).map((g) => g.name);
|
|
221
252
|
if (tooMany.length > 0) {
|
|
222
253
|
throw new RangeError(`number of levels of each grouping factor must be < number of observations (problems: ${tooMany.join(", ")})`);
|
|
223
254
|
}
|
|
224
255
|
for (const t of terms) {
|
|
225
256
|
const effects = t.nLevels * t.columns.length;
|
|
226
|
-
if (n
|
|
257
|
+
if (generalised && n < effects) {
|
|
258
|
+
throw new RangeError(`number of observations (=${n}) < number of random effects (=${effects}) for term (${t.label}); ` +
|
|
259
|
+
"the random-effects parameters are probably unidentifiable");
|
|
260
|
+
}
|
|
261
|
+
if (!generalised && n <= effects) {
|
|
227
262
|
throw new RangeError(`number of observations (=${n}) <= number of random effects (=${effects}) for term (${t.label}); ` +
|
|
228
263
|
"the random-effects parameters and the residual variance (or scale parameter) are probably unidentifiable");
|
|
229
264
|
}
|
|
@@ -284,6 +319,7 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
284
319
|
const messages = [];
|
|
285
320
|
let x = fixedDesign.x;
|
|
286
321
|
let xColNames = fixedDesign.colNames;
|
|
322
|
+
let xAssign = fixedDesign.assign;
|
|
287
323
|
if (xColNames.length > 0) {
|
|
288
324
|
const decomposition = qr(x);
|
|
289
325
|
const aliased = new Set(decomposition.pivot.slice(decomposition.rank));
|
|
@@ -291,6 +327,7 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
291
327
|
const keep = xColNames.map((_, j) => j).filter((j) => !aliased.has(j));
|
|
292
328
|
x = x.map((row) => keep.map((j) => row[j]));
|
|
293
329
|
xColNames = keep.map((j) => xColNames[j]);
|
|
330
|
+
xAssign = keep.map((j) => xAssign[j]);
|
|
294
331
|
messages.push(`fixed-effect model matrix is rank deficient so dropping ${aliased.size} ${aliased.size === 1 ? "column / coefficient" : "columns / coefficients"}`);
|
|
295
332
|
}
|
|
296
333
|
}
|
|
@@ -312,11 +349,13 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
312
349
|
if (badScale) {
|
|
313
350
|
warnings.push("Some predictor variables are on very different scales: consider rescaling. \nYou may also use (g)lmerControl(autoscale = TRUE) to improve numerical stability.");
|
|
314
351
|
}
|
|
315
|
-
|
|
352
|
+
const out = {
|
|
316
353
|
rows: frame.rows,
|
|
317
|
-
y: fixedDesign.y,
|
|
354
|
+
y: fixedDesign.y ?? new Array(n).fill(0),
|
|
318
355
|
xColNames,
|
|
319
356
|
x,
|
|
357
|
+
xAssign: [...xAssign],
|
|
358
|
+
xTermLabels: [...fixedDesign.terms.termLabels],
|
|
320
359
|
terms,
|
|
321
360
|
groups,
|
|
322
361
|
q: z.length,
|
|
@@ -328,4 +367,10 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
328
367
|
messages,
|
|
329
368
|
warnings,
|
|
330
369
|
};
|
|
370
|
+
if (generalised) {
|
|
371
|
+
// the response variables: the response, and the second column of cbind(a, b) (the frame's second variable)
|
|
372
|
+
const second = parsed.responseColumns !== undefined && parsed.responseColumns[1] !== parsed.responseColumns[0];
|
|
373
|
+
out.response = second ? [frame.variables[0], frame.variables[1]] : parsed.responseColumns !== undefined ? [frame.variables[0], frame.variables[0]] : [frame.variables[0]];
|
|
374
|
+
}
|
|
375
|
+
return out;
|
|
331
376
|
}
|
|
@@ -93,7 +93,7 @@ export function modelFrame(data, names, options = {}) {
|
|
|
93
93
|
const cols = names.map((v) => {
|
|
94
94
|
const c = Object.prototype.hasOwnProperty.call(data, v) ? data[v] : undefined;
|
|
95
95
|
if (c === undefined)
|
|
96
|
-
throw new
|
|
96
|
+
throw new RangeError(`object '${v}' not found`);
|
|
97
97
|
if (!Array.isArray(c) && !(c instanceof Float64Array))
|
|
98
98
|
throw new TypeError(`column '${v}' must be an array`);
|
|
99
99
|
return c;
|
|
@@ -102,7 +102,7 @@ export function modelFrame(data, names, options = {}) {
|
|
|
102
102
|
if (typeof options.weights === "string") {
|
|
103
103
|
const c = Object.prototype.hasOwnProperty.call(data, options.weights) ? data[options.weights] : undefined;
|
|
104
104
|
if (c === undefined)
|
|
105
|
-
throw new
|
|
105
|
+
throw new RangeError(`object '${options.weights}' not found`);
|
|
106
106
|
w = c;
|
|
107
107
|
}
|
|
108
108
|
else if (options.weights !== undefined)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type FormulaNode, type ParsedFormula, type Terms } from "./formula.js";
|
|
2
|
-
import { type DataFrame, type ModelFrame } from "./modelFrame.js";
|
|
2
|
+
import { type DataFrame, type FrameVariable, type ModelFrame } from "./modelFrame.js";
|
|
3
3
|
import type { Sample } from "../htest/types.js";
|
|
4
4
|
/**
|
|
5
5
|
* A contrast of a factor: R's `contr.treatment`, `contr.sum` or `contr.helmert`.
|
|
@@ -70,6 +70,13 @@ export interface Design {
|
|
|
70
70
|
/** The response's values (rows kept), if the formula has one */
|
|
71
71
|
y?: number[];
|
|
72
72
|
warnings: string[];
|
|
73
|
+
/**
|
|
74
|
+
* The rows of this model matrix for other values of the variables (prediction): one entry per variable of `frame`
|
|
75
|
+
* (`undefined` for those that no term with columns uses), a factor's codes indexing this frame's levels, a negative
|
|
76
|
+
* code (or NaN) for a missing value, which makes that row's columns of the variable NaN. The terms, codes and
|
|
77
|
+
* contrasts are this design's.
|
|
78
|
+
*/
|
|
79
|
+
rowsOf: (variables: readonly (FrameVariable | undefined)[], nRows: number) => number[][];
|
|
73
80
|
}
|
|
74
81
|
/** Options of {@link design} */
|
|
75
82
|
export interface DesignOptions extends Omit<ModelMatrixOptions, "contrasts"> {
|
|
@@ -7,6 +7,10 @@
|
|
|
7
7
|
// indicators.
|
|
8
8
|
import { parseFormula, termsOf } from "./formula.js";
|
|
9
9
|
import { modelFrame } from "./modelFrame.js";
|
|
10
|
+
import { reported } from "../internal/warnings.js";
|
|
11
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
12
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
13
|
+
const MODEL_MATRIX_KEYS = ["contrasts", "levels"];
|
|
10
14
|
/**
|
|
11
15
|
* The orthonormal polynomials of degrees 1..k-1 in the centred scores, as columns (one row per level): P_0 = 1/sqrt(k)
|
|
12
16
|
* and P_d from x P_(d-1) orthogonalised twice against every earlier P (the Stieltjes three-term recurrence spans the
|
|
@@ -141,48 +145,60 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
|
141
145
|
}
|
|
142
146
|
}
|
|
143
147
|
}
|
|
144
|
-
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
const fv = vars[v];
|
|
154
|
-
const name = terms.variables[v];
|
|
155
|
-
if (fv.kind === "numeric")
|
|
156
|
-
return [{ name, values: fv.values }];
|
|
157
|
-
// own properties only: a factor named toString has the default contrast unless one is given
|
|
158
|
-
const given = options.contrasts !== undefined && Object.hasOwn(options.contrasts, name) ? options.contrasts[name] : undefined;
|
|
159
|
-
const contrast = code === 2 ? "indicators" : (options.allContrasts ?? given ?? "contr.treatment");
|
|
160
|
-
const { m, names } = contrastMatrix(fv.levels, contrast);
|
|
161
|
-
return names.map((cn, j) => ({ name: name + cn, values: fv.codes.map((c) => m[c][j]) }));
|
|
162
|
-
};
|
|
163
|
-
terms.terms.forEach((t, j) => {
|
|
164
|
-
if (!used[j])
|
|
165
|
-
return;
|
|
166
|
-
let cur = partsOf(t[0], codes[j][0]);
|
|
167
|
-
for (let k = 1; k < t.length; k++) {
|
|
168
|
-
const next = [];
|
|
169
|
-
for (const p of partsOf(t[k], codes[j][k])) {
|
|
170
|
-
for (const c of cur)
|
|
171
|
-
next.push({ name: `${c.name}:${p.name}`, values: c.values.map((v, i) => v * p.values[i]) });
|
|
172
|
-
}
|
|
173
|
-
cur = next;
|
|
148
|
+
/** The columns, their names and terms, for the variables `vs` (the frame's or others, with this frame's levels) */
|
|
149
|
+
const columnsOf = (vs, rowCount) => {
|
|
150
|
+
const columns = [];
|
|
151
|
+
const colNames = [];
|
|
152
|
+
const assign = [];
|
|
153
|
+
if (terms.intercept) {
|
|
154
|
+
columns.push(new Array(rowCount).fill(1));
|
|
155
|
+
colNames.push("(Intercept)");
|
|
156
|
+
assign.push(0);
|
|
174
157
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
158
|
+
const partsOf = (v, code) => {
|
|
159
|
+
const fv = vars[v];
|
|
160
|
+
const values = vs[v];
|
|
161
|
+
const name = terms.variables[v];
|
|
162
|
+
if (fv.kind === "numeric")
|
|
163
|
+
return [{ name, values: values.values }];
|
|
164
|
+
// own properties only: a factor named toString has the default contrast unless one is given
|
|
165
|
+
const given = options.contrasts !== undefined && Object.hasOwn(options.contrasts, name) ? options.contrasts[name] : undefined;
|
|
166
|
+
const contrast = code === 2 ? "indicators" : (options.allContrasts ?? given ?? "contr.treatment");
|
|
167
|
+
const { m, names } = contrastMatrix(fv.levels, contrast);
|
|
168
|
+
const valueCodes = values.codes;
|
|
169
|
+
// (a missing value, in prediction only: NaN in every column of the variable)
|
|
170
|
+
return names.map((cn, j) => ({ name: name + cn, values: valueCodes.map((c) => m[c]?.[j] ?? NaN) }));
|
|
171
|
+
};
|
|
172
|
+
terms.terms.forEach((t, j) => {
|
|
173
|
+
if (!used[j])
|
|
174
|
+
return;
|
|
175
|
+
let cur = partsOf(t[0], codes[j][0]);
|
|
176
|
+
for (let k = 1; k < t.length; k++) {
|
|
177
|
+
const next = [];
|
|
178
|
+
for (const p of partsOf(t[k], codes[j][k])) {
|
|
179
|
+
for (const c of cur)
|
|
180
|
+
next.push({ name: `${c.name}:${p.name}`, values: c.values.map((v, i) => v * p.values[i]) });
|
|
181
|
+
}
|
|
182
|
+
cur = next;
|
|
183
|
+
}
|
|
184
|
+
for (const c of cur) {
|
|
185
|
+
columns.push(c.values);
|
|
186
|
+
colNames.push(c.name);
|
|
187
|
+
assign.push(j + 1);
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
return { columns, colNames, assign };
|
|
191
|
+
};
|
|
192
|
+
const { columns, colNames, assign } = columnsOf(vars, nr);
|
|
181
193
|
const x = Array.from({ length: nr }, (_, i) => columns.map((c) => c[i]));
|
|
194
|
+
const rowsOf = (vs, rowCount) => {
|
|
195
|
+
const cols = columnsOf(vs, rowCount).columns;
|
|
196
|
+
return Array.from({ length: rowCount }, (_, i) => cols.map((c) => c[i]));
|
|
197
|
+
};
|
|
182
198
|
// (the warnings of terms() come first, those of model.matrix() after: the absent contrasts, then the response's term)
|
|
183
199
|
const fromTerms = terms.warnings.filter((w) => !w.startsWith("problem with term"));
|
|
184
200
|
const warnings = [...fromTerms, ...contrastWarnings, ...terms.warnings.filter((w) => !fromTerms.includes(w))];
|
|
185
|
-
const out = { terms, frame, x, colNames, assign, warnings };
|
|
201
|
+
const out = { terms, frame, x, colNames, assign, warnings, rowsOf };
|
|
186
202
|
if (terms.response >= 0) {
|
|
187
203
|
const r = vars[terms.response];
|
|
188
204
|
if (r.kind === "numeric")
|
|
@@ -214,9 +230,10 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
|
214
230
|
* @category Linear models and ANOVA
|
|
215
231
|
*/
|
|
216
232
|
export function modelMatrix(formula, data, options = {}) {
|
|
233
|
+
checkOptions(options, MODEL_MATRIX_KEYS, "modelMatrix"); // generated: option-keys.mjs
|
|
217
234
|
// the response only drops the rows where it is missing: any type, as R's model.matrix (#453)
|
|
218
235
|
const d = design(parseFormula(formula), data, { ...options, anyResponse: true });
|
|
219
|
-
return {
|
|
236
|
+
return reported("modelMatrix", {
|
|
220
237
|
colNames: d.colNames,
|
|
221
238
|
assign: d.assign,
|
|
222
239
|
x: d.x,
|
|
@@ -228,5 +245,5 @@ export function modelMatrix(formula, data, options = {}) {
|
|
|
228
245
|
// R's factors attribute is empty for a model without terms
|
|
229
246
|
factors: d.terms.terms.length > 0 ? d.terms.factors : [],
|
|
230
247
|
warnings: d.warnings,
|
|
231
|
-
};
|
|
248
|
+
});
|
|
232
249
|
}
|
|
@@ -33,6 +33,10 @@ export interface SurvdiffResult {
|
|
|
33
33
|
df: number;
|
|
34
34
|
/** Upper chi-squared tail on `df` degrees of freedom (NaN for df = 0: the data carry no information on the groups) */
|
|
35
35
|
pvalue: number;
|
|
36
|
+
/** Alias of `pvalue`: the same value. */
|
|
37
|
+
pValue: number;
|
|
38
|
+
/** R's warnings, each once, in R's order (an empty array when there are none). */
|
|
39
|
+
warnings: string[];
|
|
36
40
|
}
|
|
37
41
|
/**
|
|
38
42
|
* Confidence interval type of {@link survfit}.
|
|
@@ -73,6 +77,8 @@ export interface SurvfitResult {
|
|
|
73
77
|
surv: number[];
|
|
74
78
|
/** Standard error of S(t) (S times the standard error of log S) */
|
|
75
79
|
stdErr: number[];
|
|
80
|
+
/** Alias of `stdErr`: the same array. */
|
|
81
|
+
stdError: number[];
|
|
76
82
|
/** Lower limit of the pointwise confidence interval of S(t) */
|
|
77
83
|
lower: number[];
|
|
78
84
|
/** Upper limit of the pointwise confidence interval of S(t) */
|
package/dist/models/survival.js
CHANGED
|
@@ -13,6 +13,10 @@ import { eigen } from "../linalg/eigen.js";
|
|
|
13
13
|
import { solve } from "../linalg/solve.js";
|
|
14
14
|
import { midpoint } from "../internal/extremes.js";
|
|
15
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"];
|
|
16
20
|
const isMissing = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
|
|
17
21
|
/** Observations with no missing value, the sorted labels and the group index of each */
|
|
18
22
|
function prepare(time, status, group) {
|
|
@@ -76,6 +80,7 @@ function prepare(time, status, group) {
|
|
|
76
80
|
* @category Survival analysis
|
|
77
81
|
*/
|
|
78
82
|
export function survdiff(time, status, group, options = {}) {
|
|
83
|
+
checkOptions(options, SURVDIFF_KEYS, "survdiff"); // generated: option-keys.mjs
|
|
79
84
|
const { rho = 0 } = options;
|
|
80
85
|
if (!Number.isFinite(rho))
|
|
81
86
|
throw new RangeError("'rho' must be a finite number");
|
|
@@ -149,7 +154,7 @@ export function survdiff(time, status, group, options = {}) {
|
|
|
149
154
|
}
|
|
150
155
|
}
|
|
151
156
|
const pvalue = df === 0 ? NaN : pchisq(chisq, df, { lowerTail: false });
|
|
152
|
-
return { n, groups: labels, obs: observed, exp: expected, var: V, chisq, df, pvalue };
|
|
157
|
+
return { n, groups: labels, obs: observed, exp: expected, var: V, chisq, df, pvalue, pValue: pvalue, warnings: [] };
|
|
153
158
|
}
|
|
154
159
|
/**
|
|
155
160
|
* u' V^- u for a symmetric positive semi-definite V by its eigen decomposition, over the eigenvalues above 1e-10 of the
|
|
@@ -208,6 +213,7 @@ function curveMedian(time, curve) {
|
|
|
208
213
|
* @category Survival analysis
|
|
209
214
|
*/
|
|
210
215
|
export function survfit(time, status, options = {}) {
|
|
216
|
+
checkOptions(options, SURVFIT_KEYS, "survfit"); // generated: option-keys.mjs
|
|
211
217
|
const { group, confType = "log", confInt = 0.95 } = options;
|
|
212
218
|
if (confType !== "log" && confType !== "plain" && confType !== "log-log") {
|
|
213
219
|
throw new RangeError(`invalid 'confType': ${String(confType)}`);
|
|
@@ -219,8 +225,9 @@ export function survfit(time, status, options = {}) {
|
|
|
219
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)
|
|
220
226
|
const a2 = (1 - confInt) / 2;
|
|
221
227
|
const z = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - (1 - confInt) / 2);
|
|
228
|
+
const stdErr = [];
|
|
222
229
|
const out = {
|
|
223
|
-
strata: [], time: [], nRisk: [], nEvent: [], nCensor: [], surv: [], stdErr:
|
|
230
|
+
strata: [], time: [], nRisk: [], nEvent: [], nCensor: [], surv: [], stdErr, stdError: stdErr, lower: [], upper: [],
|
|
224
231
|
median: [], medianRows: names,
|
|
225
232
|
};
|
|
226
233
|
names.forEach((name, g) => {
|
package/dist/numerics/deriv.js
CHANGED
|
@@ -7,6 +7,11 @@
|
|
|
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"];
|
|
10
15
|
function checkEps(eps) {
|
|
11
16
|
if (!(Number.isFinite(eps) && eps !== 0))
|
|
12
17
|
throw new RangeError("'eps' must be a finite nonzero number");
|
|
@@ -76,6 +81,7 @@ function method(options) {
|
|
|
76
81
|
* @category Numerical methods
|
|
77
82
|
*/
|
|
78
83
|
export function grad(func, x, options = {}) {
|
|
84
|
+
checkOptions(options, GRAD_KEYS, "grad"); // generated: option-keys.mjs
|
|
79
85
|
const xs = [...x];
|
|
80
86
|
const n = xs.length;
|
|
81
87
|
if (method(options) === "simple") {
|
|
@@ -114,6 +120,7 @@ export function grad(func, x, options = {}) {
|
|
|
114
120
|
* @category Numerical methods
|
|
115
121
|
*/
|
|
116
122
|
export function jacobian(func, x, options = {}) {
|
|
123
|
+
checkOptions(options, JACOBIAN_KEYS, "jacobian"); // generated: option-keys.mjs
|
|
117
124
|
const xs = [...x];
|
|
118
125
|
const n = xs.length;
|
|
119
126
|
const f0 = Array.from(func([...xs]));
|
|
@@ -159,6 +166,7 @@ export function jacobian(func, x, options = {}) {
|
|
|
159
166
|
* @category Numerical methods
|
|
160
167
|
*/
|
|
161
168
|
export function hessian(func, x, options = {}) {
|
|
169
|
+
checkOptions(options, HESSIAN_KEYS, "hessian"); // generated: option-keys.mjs
|
|
162
170
|
if ((options.method ?? "Richardson") !== "Richardson")
|
|
163
171
|
throw new RangeError('hessian supports only method "Richardson"');
|
|
164
172
|
const xs = [...x];
|
|
@@ -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,6 +36,7 @@ const TOL = Number.EPSILON ** 0.25;
|
|
|
31
36
|
* @category Numerical methods
|
|
32
37
|
*/
|
|
33
38
|
export function integrate(f, lower, upper, options = {}) {
|
|
39
|
+
checkOptions(options, INTEGRATE_KEYS, "integrate"); // generated: option-keys.mjs
|
|
34
40
|
const subdivisions = options.subdivisions ?? 100;
|
|
35
41
|
const limit = Math.trunc(subdivisions);
|
|
36
42
|
const relTol = options.relTol ?? TOL;
|
|
@@ -102,6 +108,7 @@ export function integrate(f, lower, upper, options = {}) {
|
|
|
102
108
|
* @category Numerical methods
|
|
103
109
|
*/
|
|
104
110
|
export function optimize(f, lower, upper, options = {}) {
|
|
111
|
+
checkOptions(options, OPTIMIZE_KEYS, "optimize"); // generated: option-keys.mjs
|
|
105
112
|
const maximum = options.maximum ?? false;
|
|
106
113
|
const tol = options.tol ?? TOL;
|
|
107
114
|
// (a positive tol, as in R: with tol = 0 the search stopped narrowing among the subnormals, see localMin)
|
|
@@ -156,6 +163,7 @@ function extendIntArg(e) {
|
|
|
156
163
|
* @category Numerical methods
|
|
157
164
|
*/
|
|
158
165
|
export function uniroot(f, lower, upper, options = {}) {
|
|
166
|
+
checkOptions(options, UNIROOT_KEYS, "uniroot"); // generated: option-keys.mjs
|
|
159
167
|
// R's "invalid 'tol' value" for tol <= 0 (tol = 0 was accepted, Brent's method then ran to maxiter or the doubles)
|
|
160
168
|
const tol = options.tol ?? TOL;
|
|
161
169
|
if (!(tol > 0 && tol < Infinity))
|
|
@@ -103,35 +103,60 @@ export interface SplinefunOptions {
|
|
|
103
103
|
/** How to merge equal x values. Default `"mean"`. */
|
|
104
104
|
ties?: Ties;
|
|
105
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* Options of the function that {@link splinefun} and {@link splinefunH} return.
|
|
108
|
+
*
|
|
109
|
+
* @category Numerical methods
|
|
110
|
+
*/
|
|
111
|
+
export interface SplineFunctionOptions {
|
|
112
|
+
/** Order of the derivative, 0 to 3 (a fraction is truncated, as R does). Default `0`. */
|
|
113
|
+
deriv?: number;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The function that {@link splinefun} and {@link splinefunH} return: the spline, or a derivative, at the points `xq`.
|
|
117
|
+
* The order of the derivative is the second argument or the option `deriv` (giving both is a RangeError).
|
|
118
|
+
*
|
|
119
|
+
* @category Numerical methods
|
|
120
|
+
*/
|
|
121
|
+
export interface SplineFunction {
|
|
122
|
+
/** The spline at `xq`, or its derivative of order `deriv` (0 to 3). */
|
|
123
|
+
(xq: Sample, deriv?: number): number[];
|
|
124
|
+
/** The spline at `xq`, with the order of the derivative in the options: `s(xq, { deriv: 1 })`. */
|
|
125
|
+
(xq: Sample, options: SplineFunctionOptions): number[];
|
|
126
|
+
}
|
|
106
127
|
/**
|
|
107
128
|
* The cubic spline through the points, as a function of `x` and the order of derivative (0 to 3; a fraction is
|
|
108
129
|
* truncated, as R does). Equivalent to R's `splinefun()`. Except that the third derivative of `"monoH.FC"` is the
|
|
109
|
-
* exact one (see {@link splinefunH}).
|
|
130
|
+
* exact one (see {@link splinefunH}). The order of derivative is the second argument of the function or its option
|
|
131
|
+
* `deriv` ({@link SplineFunction}).
|
|
110
132
|
*
|
|
111
133
|
* @example
|
|
112
134
|
* ```ts
|
|
113
135
|
* const s = splinefun([1, 2, 3, 4], [1, 4, 9, 16]);
|
|
114
|
-
* s([2.5]);
|
|
115
|
-
* s([2.5], 1);
|
|
136
|
+
* s([2.5]); // [6.25]
|
|
137
|
+
* s([2.5], 1); // [5]
|
|
138
|
+
* s([2.5], { deriv: 1 }); // [5]
|
|
116
139
|
* ```
|
|
117
140
|
*
|
|
118
141
|
* @category Numerical methods
|
|
119
142
|
*/
|
|
120
|
-
export declare function splinefun(x: Sample, y: Sample, options?: SplinefunOptions):
|
|
143
|
+
export declare function splinefun(x: Sample, y: Sample, options?: SplinefunOptions): SplineFunction;
|
|
121
144
|
/**
|
|
122
145
|
* The cubic Hermite spline with values `y` and slopes `m` at the points `x`, as a function of `x` and the order of
|
|
123
146
|
* derivative (0 to 3; a fraction is truncated, as R does); linear outside the data. Equivalent to R's `splinefunH()`.
|
|
124
147
|
* Except for the third derivative: on [x_i, x_{i+1}] it is the exact (6 m_i + 6 m_{i+1} - 12 delta) / h^2, with
|
|
125
|
-
* h = x_{i+1} - x_i and delta = (y_{i+1} - y_i) / h, where R divides by h only once (the two agree when h = 1).
|
|
148
|
+
* h = x_{i+1} - x_i and delta = (y_{i+1} - y_i) / h, where R divides by h only once (the two agree when h = 1). The
|
|
149
|
+
* order of derivative is the second argument of the function or its option `deriv` ({@link SplineFunction}).
|
|
126
150
|
*
|
|
127
151
|
* @example
|
|
128
152
|
* ```ts
|
|
129
|
-
* splinefunH([0, 2], [0, 0], [1, 1])([1], 3);
|
|
153
|
+
* splinefunH([0, 2], [0, 0], [1, 1])([1], 3); // [3] (R: 6)
|
|
154
|
+
* splinefunH([0, 2], [0, 0], [1, 1])([1], { deriv: 3 }); // [3]
|
|
130
155
|
* ```
|
|
131
156
|
*
|
|
132
157
|
* @category Numerical methods
|
|
133
158
|
*/
|
|
134
|
-
export declare function splinefunH(x: Sample, y: Sample, m: Sample):
|
|
159
|
+
export declare function splinefunH(x: Sample, y: Sample, m: Sample): SplineFunction;
|
|
135
160
|
/**
|
|
136
161
|
* Lagrange interpolation in barycentric form through the points (xi, yi). Equivalent to `pracma::barylag()` in R.
|
|
137
162
|
* The points must lie within the range of the nodes.
|