@numero-uno-jpn/rstats 0.17.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 +77 -0
- package/README.ja.md +18 -10
- package/README.md +20 -10
- package/dist/chunks/{chunk-Z37NELOS.js → chunk-3W5NFFAA.js} +1 -1
- package/dist/chunks/{chunk-2C33MXSW.js → chunk-4F2IALD4.js} +2 -2
- package/dist/chunks/{chunk-H3WVPZDL.js → chunk-4OLDGML4.js} +2 -2
- package/dist/chunks/{chunk-WM7VFXTV.js → chunk-63OPBEYO.js} +1 -1
- package/dist/chunks/{chunk-TNMJPQPV.js → chunk-6XJBCRBV.js} +2 -2
- package/dist/chunks/{chunk-RFE7MVP7.js → chunk-BQSIBJVX.js} +2 -2
- package/dist/chunks/{chunk-C7V2FH6L.js → chunk-BWKHYRM6.js} +1 -1
- package/dist/chunks/{chunk-SE7V2KLO.js → chunk-CKV4JWW2.js} +1 -1
- package/dist/chunks/{chunk-CZI7KUO3.js → chunk-DCAWMF4K.js} +2 -2
- package/dist/chunks/{chunk-5AYHCITP.js → chunk-F7YGX7PN.js} +2 -2
- package/dist/chunks/chunk-H7I32ZZE.js +2 -0
- package/dist/chunks/chunk-IEOD5GWC.js +3 -0
- package/dist/chunks/{chunk-XLSFJTTK.js → chunk-KICBQGFN.js} +2 -2
- package/dist/chunks/chunk-LROMWFAK.js +2 -0
- package/dist/chunks/{chunk-DXI5N2ET.js → chunk-NSWENS3S.js} +1 -1
- package/dist/chunks/chunk-O2SQMGE3.js +2 -0
- package/dist/chunks/{chunk-FY3FVOBM.js → chunk-QQX46TCI.js} +2 -2
- package/dist/chunks/{chunk-ZFQWB222.js → chunk-QZK3CCBA.js} +2 -2
- package/dist/chunks/{chunk-6JJQL6HL.js → chunk-UJ66VQIG.js} +2 -2
- package/dist/chunks/{chunk-ONY5CISH.js → chunk-UKNDX4BA.js} +2 -2
- package/dist/chunks/chunk-WIBKS73G.js +2 -0
- package/dist/chunks/{chunk-4WE3OO62.js → chunk-WQWZ7FND.js} +2 -2
- package/dist/chunks/{chunk-LHUIJQHY.js → chunk-WWVMVZUL.js} +2 -2
- package/dist/chunks/{chunk-LV3W2F7N.js → chunk-YG5S5AVP.js} +2 -2
- package/dist/chunks/{chunk-34S5SQY6.js → chunk-YHNMBYSW.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/mixed.d.ts +6 -0
- package/dist/entries/mixed.js +6 -1
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +5 -4
- package/dist/models/formula.d.ts +5 -2
- package/dist/models/formula.js +31 -8
- 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/lmer.d.ts +16 -0
- package/dist/models/lmer.js +55 -306
- package/dist/models/lmerAnova.d.ts +49 -0
- package/dist/models/lmerAnova.js +91 -40
- package/dist/models/lmerTest.d.ts +8 -1
- package/dist/models/lmerTest.js +21 -8
- 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/modelMatrix.d.ts +8 -1
- package/dist/models/modelMatrix.js +49 -37
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +11 -11
- package/dist/special.js +2 -2
- package/dist/tests.js +13 -14
- package/llms.txt +10 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-M4ITG7YR.js +0 -2
- package/dist/chunks/chunk-NSYZTS26.js +0 -2
- package/dist/chunks/chunk-THIGHOKK.js +0 -2
- package/dist/chunks/chunk-WMDYDTVQ.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
|
}
|
|
@@ -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"> {
|
|
@@ -145,48 +145,60 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
|
-
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
const fv = vars[v];
|
|
158
|
-
const name = terms.variables[v];
|
|
159
|
-
if (fv.kind === "numeric")
|
|
160
|
-
return [{ name, values: fv.values }];
|
|
161
|
-
// own properties only: a factor named toString has the default contrast unless one is given
|
|
162
|
-
const given = options.contrasts !== undefined && Object.hasOwn(options.contrasts, name) ? options.contrasts[name] : undefined;
|
|
163
|
-
const contrast = code === 2 ? "indicators" : (options.allContrasts ?? given ?? "contr.treatment");
|
|
164
|
-
const { m, names } = contrastMatrix(fv.levels, contrast);
|
|
165
|
-
return names.map((cn, j) => ({ name: name + cn, values: fv.codes.map((c) => m[c][j]) }));
|
|
166
|
-
};
|
|
167
|
-
terms.terms.forEach((t, j) => {
|
|
168
|
-
if (!used[j])
|
|
169
|
-
return;
|
|
170
|
-
let cur = partsOf(t[0], codes[j][0]);
|
|
171
|
-
for (let k = 1; k < t.length; k++) {
|
|
172
|
-
const next = [];
|
|
173
|
-
for (const p of partsOf(t[k], codes[j][k])) {
|
|
174
|
-
for (const c of cur)
|
|
175
|
-
next.push({ name: `${c.name}:${p.name}`, values: c.values.map((v, i) => v * p.values[i]) });
|
|
176
|
-
}
|
|
177
|
-
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);
|
|
178
157
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
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);
|
|
185
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
|
+
};
|
|
186
198
|
// (the warnings of terms() come first, those of model.matrix() after: the absent contrasts, then the response's term)
|
|
187
199
|
const fromTerms = terms.warnings.filter((w) => !w.startsWith("problem with term"));
|
|
188
200
|
const warnings = [...fromTerms, ...contrastWarnings, ...terms.warnings.filter((w) => !fromTerms.includes(w))];
|
|
189
|
-
const out = { terms, frame, x, colNames, assign, warnings };
|
|
201
|
+
const out = { terms, frame, x, colNames, assign, warnings, rowsOf };
|
|
190
202
|
if (terms.response >= 0) {
|
|
191
203
|
const r = vars[terms.response];
|
|
192
204
|
if (r.kind === "numeric")
|
package/dist/numerics.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! rStats.js 0.
|
|
2
|
-
import{a as st,b as it,c as ct,e as at,f as ft}from"./chunks/chunk-2C33MXSW.js";import"./chunks/chunk-Z37NELOS.js";import{a as D,f as Z}from"./chunks/chunk-ZFQWB222.js";import"./chunks/chunk-ONY5CISH.js";import{b as P}from"./chunks/chunk-RFE7MVP7.js";import"./chunks/chunk-DXI5N2ET.js";import"./chunks/chunk-C7V2FH6L.js";import{a as $,b as V,c as K}from"./chunks/chunk-SE7V2KLO.js";import{l as j,u as y,v as C,x as Q}from"./chunks/chunk-WM7VFXTV.js";var ut=["xout","method","n","yleft","yright","rule","f","ties"],lt=["n","method","xmin","xmax","xout","ties"],ht=["method","ties"];function H(o,i,t="mean"){if(o.length!==i.length)throw new RangeError("'x' and 'y' lengths differ");let n=[];for(let r=0;r<o.length;r++)!Number.isNaN(o[r])&&!Number.isNaN(i[r])&&n.push(r);n.sort((r,a)=>o[r]-o[a]);let e=typeof t=="function"?t:t==="min"?r=>K(r):t==="max"?r=>$(r):Q,s=[],u=[];for(let r=0;r<n.length;){let a=o[n[r]],f=r+1;for(;f<n.length&&o[n[f]]===a;)f++;s.push(a),u.push(f-r===1?i[n[r]]:e(n.slice(r,f).map(c=>i[c]))),r=f}return{x:s,y:u}}function mt(o,i,t,n){let e=(n-o[t])/(o[t+1]-o[t]);(!Number.isFinite(o[t+1]-o[t])||!Number.isFinite(n-o[t]))&&(e=(n/2-o[t]/2)/(o[t+1]/2-o[t]/2));let s=i[t+1]-i[t];return!Number.isFinite(s)&&Number.isFinite(i[t])&&Number.isFinite(i[t+1])?2*(i[t]/2+(i[t+1]/2-i[t]/2)*e):i[t]+s*e}function J(o,i,t){let n=i-o;return!Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)?2*((i/2-o/2)/t):n/t}function O(o,i,t){let n=1,e=t;for(let s of o){if(s===0)return 0*n;let u=Math.floor(Math.log2(Math.abs(s)));n*=y(s,-u),e+=u}for(let s of i){let u=Math.floor(Math.log2(Math.abs(s)));n/=y(s,-u),e-=u}return C(n,e)}function pt(o,i,t){let n=(e,s)=>e===0?0:e*s;return n(1-t,o[i])+n(t,o[i+1])}function bt(o){if(o===void 0)return"linear";if(typeof o=="string"&&o.length>0){let i=["linear","constant"].filter(t=>t.startsWith(o));if(i.length===1)return i[0]}throw new RangeError("invalid interpolation method")}function dt(o){let i=typeof o=="number"?[o]:Array.isArray(o)?o:[],t=n=>n===1||n===2;if(i.length<1||i.length>2||!i.every(t))throw new RangeError("'rule' must be 1 or 2, or a pair of them");return[i[0],i[i.length-1]]}function gt(o,i,t={}){j(t,ut,"approx");let{n=50,f:e=0,rule:s=1,ties:u="mean"}=t,r=bt(t.method),[a,f]=dt(s),c=H(o,i,u),p=c.x.length;if(p<=1&&r==="linear")throw new RangeError("need at least two non-NA values to interpolate");if(p===0)throw new RangeError("zero non-NA points");if(r==="constant"&&!(e>=0&&e<=1))throw new RangeError("approx(): invalid f value");let d=t.yleft??(a===1?NaN:c.y[0]),h=t.yright??(f===1?NaN:c.y[p-1]),m;if(t.xout!==void 0)m=Array.from(t.xout);else{if(!Number.isFinite(n)&&!Number.isNaN(n))throw new RangeError("'length.out' must be a finite number");if(!(n>0))throw new RangeError("'approx' requires n >= 1");m=D(c.x[0],c.x[p-1],n)}let g=c.x,l=c.y,b=Z(m,g),N=m.map((M,A)=>{let E=b[A];if(Number.isNaN(E))return NaN;if(E===0)return d;let R=E-1;return M===g[R]?l[R]:E===p?h:r==="linear"?mt(g,l,R,M):pt(l,R,e)});return{x:m,y:N}}function W(o,i){let t=o.length,n=new Array(t).fill(0),e=new Array(t).fill(0),s=new Array(t).fill(0);if(t<2)return{b:n,c:e,d:s};if(t<3)return n[0]=J(i[0],i[1],o[1]-o[0]),n[1]=n[0],{b:n,c:e,d:s};let u=t-1;s[0]=o[1]-o[0],e[1]=(i[1]-i[0])/s[0];for(let r=1;r<u;r++)s[r]=o[r+1]-o[r],n[r]=2*(s[r-1]+s[r]),e[r+1]=(i[r+1]-i[r])/s[r],e[r]=e[r+1]-e[r];n[0]=-s[0],n[u]=-s[t-2],e[0]=0,e[u]=0,t>3&&(e[0]=e[2]/(o[3]-o[1])-e[1]/(o[2]-o[0]),e[u]=e[t-2]/(o[u]-o[t-3])-e[t-3]/(o[t-2]-o[t-4]),e[0]=e[0]*s[0]*s[0]/(o[3]-o[0]),e[u]=-e[u]*s[t-2]*s[t-2]/(o[u]-o[t-4]));for(let r=1;r<t;r++){let a=s[r-1]/n[r-1];n[r]=n[r]-a*s[r-1],e[r]=e[r]-a*e[r-1]}e[u]=e[u]/n[u];for(let r=t-2;r>=0;r--)e[r]=(e[r]-s[r]*e[r+1])/n[r];n[u]=(i[u]-i[t-2])/s[t-2]+s[t-2]*(e[t-2]+2*e[u]);for(let r=0;r<u;r++)n[r]=(i[r+1]-i[r])/s[r]-s[r]*(e[r+1]+2*e[r]),s[r]=(e[r+1]-e[r])/s[r],e[r]=3*e[r];return e[u]=3*e[u],s[u]=s[t-2],{b:n,c:e,d:s}}function tt(o,i,t){let n=o.length,e=new Array(n).fill(0),s=new Array(n).fill(0),u=new Array(n).fill(0);for(let r=0;r<n-1;r++){let a=o[r+1]-o[r];e[r]=(i[r+1]-i[r])/a-a*(t[r+1]+2*t[r]),s[r]=3*t[r],u[r]=(t[r+1]-t[r])/a}return{b:e,c:s,d:u}}function Nt(o,i){let t=o.length;if(t<3)return W(o,i);let n=Array.from({length:t-1},(f,c)=>o[c+1]-o[c]),e=n.map((f,c)=>(i[c+1]-i[c])/f),s=new Array(t).fill(0),u=new Array(t).fill(0);for(let f=1;f<t-1;f++)s[f]=2*(n[f-1]+n[f]),u[f]=e[f]-e[f-1];for(let f=2;f<t-1;f++){let c=n[f-1]/s[f-1];s[f]=s[f]-c*n[f-1],u[f]=u[f]-c*u[f-1]}let r=new Array(t).fill(0);r[t-2]=u[t-2]/s[t-2];for(let f=t-3;f>=1;f--)r[f]=(u[f]-n[f]*r[f+1])/s[f];let a=tt(o,i,r);return a.b[t-1]=e[t-2]+n[t-2]*r[t-2],a}function wt(o,i){let t=o.length;if(i[0]!==i[t-1])throw new RangeError("periodic spline needs y[1] == y[n]");if(t<3)return{b:new Array(t).fill(0),c:new Array(t).fill(0),d:new Array(t).fill(0)};let n=t-1,e=Array.from({length:n},(l,b)=>o[b+1]-o[b]),s=e.map((l,b)=>(i[b+1]-i[b])/l),u=l=>l===0?n-1:l-1,r=Array.from({length:n},(l,b)=>2*(e[u(b)]+e[b])),a=Array.from({length:n},(l,b)=>s[b]-s[u(b)]),f=e.slice(),c=new Array(n).fill(0);c[0]=e[n-1],c[n-2]=c[n-2]+e[n-2];let p=c[0],d=r[n-1],h=a[n-1];for(let l=0;l<n-1;l++){if(l+1<n-1){let N=e[l]/r[l];r[l+1]=r[l+1]-N*f[l],c[l+1]=c[l+1]-N*c[l],a[l+1]=a[l+1]-N*a[l]}let b=p/r[l];d-=b*c[l],h-=b*a[l],l+1<n-1&&(p=(l+1===n-2?e[n-2]:0)-b*f[l])}let m=new Array(t).fill(0);m[n-1]=h/d;for(let l=n-2;l>=0;l--){let b=a[l]-c[l]*m[n-1]-(l<n-2?f[l]*m[l+1]:0);m[l]=b/r[l]}m[t-1]=m[0];let g=tt(o,i,m);return g.b[t-1]=g.b[0],g.c[t-1]=g.c[0],g.d[t-1]=g.d[0],g}function Mt(o,i){let t=o.length,{b:n,c:e,d:s}=W(o,i);if(t<2)return{b:n,c:e,d:s};let u=Array.from({length:t-1},(a,f)=>(i[f+1]-i[f])/(o[f+1]-o[f]));for(let a=0;a<t;a++){let f=u[a===0?0:a-1],c=u[a===t-1?t-2:a],p=Math.min(Math.abs(f),Math.abs(c)),d=f>0&&c>0||f<0&&c<0?c>0:n[a]>=0;n[a]=d?Math.min(Math.max(0,n[a]),3*p):Math.max(Math.min(0,n[a]),-3*p)}for(let a=0;a<t-1;a++){let f=o[a+1]-o[a],c=(i[a+1]-i[a])/f;e[a]=(3*c-2*n[a]-n[a+1])/f,s[a]=(n[a]+n[a+1]-2*c)/(f*f)}let r=o[t-1]-o[t-2];return e[t-1]=(n[t-2]+2*n[t-1]-3*(i[t-1]-i[t-2])/r)/r,s[t-1]=s[t-2],{b:n,c:e,d:s}}function T(o){let i=o.length;return i<2||!o.every(Number.isFinite)||Number.isFinite(o[i-1]-o[0])?0:Math.floor(Math.log2($(o.map(Math.abs))))}function L(o,i,t,n){let e=H(o,i,n),s=e.x.length;if(s===0)throw new RangeError("zero non-NA points");t==="periodic"&&e.y[s-1]!==e.y[0]&&(e.y[s-1]=e.y[0]),t==="hyman"&&yt(e.y);let u=t==="fmm"?W(e.x,e.y):t==="natural"?Nt(e.x,e.y):t==="periodic"?wt(e.x,e.y):t==="hyman"?Mt(e.x,e.y):(()=>{throw new RangeError(`invalid spline method '${String(t)}'`)})();return{method:t,...e,...u}}function yt(o){let i=!0,t=!0;for(let n=1;n<o.length;n++){let e=o[n]-o[n-1];e>=0||(i=!1),e<=0||(t=!1)}if(!i&&!t)throw new RangeError("'y' must be increasing or decreasing")}function B(o){let i=Math.trunc(o);if(!(i>=0&&i<=3))throw new RangeError("'deriv' must be between 0 and 3");return i}function Y(o,i,t){let n=B(t),{x:e,y:s,b:u,c:r,d:a,method:f}=o,c=e.length,p=f==="natural",d=e[c-1]-e[0],h=0;return Array.from(i,m=>{let g=m;if(f==="periodic"&&c>1){let N=(g-e[0])%d;N<0&&(N+=d),g=e[0]+N}if(p&&n>0&&g<=e[0])return n===1?u[0]:0;if(!(e[h]<=g&&(h===c-1||g<=e[h+1]))){let N=0,M=c;for(;M-N>1;){let A=N+M>>1;e[A]<=g?N=A:M=A}h=N}let l=g-e[h],b=p&&g<e[0]?0:a[h];switch(n){case 0:return s[h]+l*(u[h]+l*(r[h]+l*b));case 1:return u[h]+l*(2*r[h]+l*(3*b));case 2:return 2*r[h]+l*(6*b);default:return 6*b}})}function Ft(o,i,t={}){j(t,lt,"spline");let{method:n="fmm",ties:e="mean"}=t,s=L(o,i,n,e),u=T(s.x);u!==0&&(s=L(Array.from(o,a=>y(a,-u)),i,n,e));let r;if(t.xout!==void 0)r=Array.from(t.xout);else{let a=s.x.length,f=t.n??3*a;if(!Number.isFinite(f))throw new RangeError("'length.out' must be a finite number");if(!(f>0))throw new RangeError("'spline' requires n >= 1");r=D(t.xmin??y(s.x[0],u),t.xmax??y(s.x[a-1],u),f)}return{x:r,y:Y(s,u===0?r:r.map(a=>y(a,-u)),0)}}function At(o,i,t={}){j(t,ht,"splinefun");let n=Et(o,i,t);return(e,...s)=>n(e,P(["deriv"],s,"the function from splinefun").deriv??0)}function Et(o,i,t){let{method:n="fmm",ties:e="mean"}=t;if(n==="monoH.FC"){let r=H(o,i,e);if(r.x.length===0)throw new RangeError("zero non-NA points");let a=T(r.x);a!==0&&(r=H(Array.from(o,c=>y(c,-a)),i,e));let f=Rt(r.x,r.y);return(c,p)=>nt(r.x,r.y,f,a,a,c,p)}let s=L(o,i,n,e),u=T(s.x);return u===0?(r,a)=>Y(s,r,a):(s=L(Array.from(o,r=>y(r,-u)),i,n,e),(r,a)=>{let f=B(a);return Y(s,Array.from(r,c=>y(c,-u)),f).map(c=>y(c,-f*u))})}function Rt(o,i){let t=o.length;if(t<2)throw new RangeError("length(m) must be at least two");let n=Array.from({length:t-1},(s,u)=>(i[u+1]-i[u])/(o[u+1]-o[u])),e=Array.from({length:t},(s,u)=>u===0?n[0]:u===t-1?n[t-2]:V(n[u-1],n[u]));for(let s=0;s<t-1;s++){let u=n[s];if(u===0){e[s]=0,e[s+1]=0;continue}let r=e[s]/u,a=e[s+1]/u,f=2*r+a-3,c=r+2*a-3;if(!(Number.isFinite(r*(f+c))&&Number.isFinite(f*f)&&Number.isFinite(r*r+a*a))&&Number.isFinite(e[s])&&Number.isFinite(e[s+1])&&Number.isFinite(u)){let d=M=>M===0?-1/0:Math.floor(Math.log2(Math.abs(M))),h=Math.max(d(e[s]),d(e[s+1]))-d(u),m=O([e[s]],[u],-h),g=O([e[s+1]],[u],-h),l=C(3,-h),b=2*m+g-l,N=m+2*g-l;if(b>0&&N>0&&m*(b+N)<b*b){let M=3*u/Math.sqrt(m*m+g*g);e[s]=M*m,e[s+1]=M*g}continue}if(f>0&&c>0&&r*(f+c)<f*f){let d=3*u/Math.sqrt(r*r+a*a);e[s]=d*r,e[s+1]=d*a}}return e}function nt(o,i,t,n,e,s,u){let r=B(u),a=o.length;return Array.from(s,f=>{if(Number.isNaN(f))return NaN;let c=n===0?f:y(f,-n),p=0,d=a;for(;p<d;){let w=p+d>>1;o[w]<=c?p=w+1:d=w}let h=p;if(h===0||h===a){let w=h===0?0:a-1;return r===0?i[w]+y(t[w]*(c-o[w]),n-e):r===1?y(t[w],-e):0}let m=o[h-1],g=o[h]-m,l=(c-m)/g,b=l-1,N=i[h-1],M=i[h],A=t[h-1],E=t[h],R=y(J(N,M,g),e-n);switch(r){case 0:{let w=l*l*(3-2*l),F=(k,S)=>{let _=y(g*k,n-e)*S;return Number.isFinite(_)||!Number.isFinite(k)||!Number.isFinite(S)?_:O([g,k,S],[],n-e)};return N*(1-w)+F(A,l*b*b)+M*w+F(E,l*l*b)}case 1:{if(Number.isFinite(R)||!Number.isFinite(N)||!Number.isFinite(M))return y(R*(-6*l*b)+A*(b*(3*l-1))+E*(l*(3*l-2)),-e);let w=M-N;return(Number.isFinite(w)?O([w,-6*l*b],[g],-n):O([M/2-N/2,-6*l*b],[g],1-n))+y(A*(b*(3*l-1))+E*(l*(3*l-2)),-e)}case 2:{if(Number.isFinite(R)||!Number.isFinite(N)||!Number.isFinite(M))return y((R*(6-12*l)+A*(6*l-4)+E*(6*l-2))/g,-e-n);let w=M-N;return(Number.isFinite(w)?O([w,6-12*l],[g,g],-2*n):O([M/2-N/2,6-12*l],[g,g],1-2*n))+y((A*(6*l-4)+E*(6*l-2))/g,-e-n)}default:{let w=-12*R+6*A+6*E,F=g*g;return F>=2**-1022&&F<1/0?y(w/F,-e-2*n):y(w/g/g,-e-2*n)}}})}function xt(o,i,t){let n=o.length;if(i.length!==n||t.length!==n)throw new RangeError("'x', 'y' and 'm' must have the same length");let e=Array.from({length:n},(c,p)=>p).sort((c,p)=>o[c]-o[p]),s=e.map(c=>o[c]),u=e.map(c=>i[c]),r=e.map(c=>t[c]);for(let c=1;c<n;c++)if(!(s[c]-s[c-1]>0))throw new RangeError("'x' must be *strictly* increasing (non - NA)");let a=T(s),f=a===0?s:s.map(c=>y(c,-a));return(c,...p)=>nt(f,u,r,a,0,c,P(["deriv"],p,"the function from splinefunH").deriv??0)}function kt(o,i,t){let n=Array.from(o),e=Array.from(i),s=n.length;if(e.length!==s)throw new RangeError("'xi' and 'yi' must have the same length");let u=Array.from(t),r=K(n),a=$(n);if(u.some(b=>b<r||b>a))throw new RangeError("Some interpolation points outside the nodes.");let f=Number.isFinite(r)&&Number.isFinite(a)&&!Number.isFinite(a-r),c=f?n.map(b=>b/2):n,p=c.map((b,N)=>{let M=1,A=0;for(let E=0;E<s;E++){if(E===N)continue;let R=b-c[E],w=M*R;if(M!==0&&R!==0&&Number.isFinite(R)&&!(Math.abs(w)>=2**-1022&&Math.abs(w)<1/0)){let k=Math.floor(Math.log2(Math.abs(M))),S=Math.floor(Math.log2(Math.abs(R)));M=y(M,-k)*y(R,-S),A+=k+S;continue}M=w;let F=Math.abs(M);if(F>2**500||F<2**-500&&F>0){let k=Math.floor(Math.log2(F));M=y(M,-k),A+=k}}return{p:M,e:A}}),d=p.reduce((b,N)=>Math.max(b,-N.e),-1/0),h=p.map(b=>y(1/b.p,-b.e-d)),m=n.every(Number.isFinite)&&e.every(Number.isFinite),g=m?e.reduce((b,N)=>N===0?b:Math.max(b,Math.floor(Math.log2(Math.abs(N)))),-1/0):0,l=b=>{if(g===-1/0)return 0;let N=1,M=0,A=[];for(let F=0;F<s;F++){let k=b-c[F];if(k===0)return;let S=Math.floor(Math.log2(Math.abs(k))),_=y(k,-S);N*=_;let x=Math.floor(Math.log2(Math.abs(N)));N=y(N,-x),M+=S+x;let v=1/p[F].p/_;if(!Number.isFinite(v)||v===0)return;let z=Math.floor(Math.log2(Math.abs(v)));A.push({r:y(v,-z),x:z-p[F].e-S})}let E=A.reduce((F,k)=>Math.max(F,k.x),-1/0),R=0;for(let F=0;F<s;F++)R+=y(A[F].r,A[F].x-E)*y(e[F],-g);if(R===0)return 0;let w=Math.floor(Math.log2(Math.abs(R)));return C(N*y(R,-w),M+E+g+w)};return u.map(b=>{let N=0,M=0,A=n.lastIndexOf(b);if(A>=0)return e[A];let E=0,R=0;for(let x=0;x<s;x++){let v=(f?b/2:b)-c[x],z=h[x]/v;N+=z*e[x],M+=z,E+=Math.abs(z),R+=Math.abs(z*e[x])}let w=N/M;if(m&&Number.isFinite(E)&&E>0&&Math.abs(M)<y(E,-100)&&Number.isFinite(R)&&Math.abs(N)>=y(R,-26)){let x=l(f?b/2:b);if(x!==void 0)return x}if(Number.isFinite(w)||!m)return w;let F=p.map((x,v)=>{let z=(f?b/2:b)-c[v],U=Math.floor(Math.log2(Math.abs(z)));return{r:1/x.p/y(z,-U),x:-x.e-U}});if(!F.every(x=>Number.isFinite(x.r)&&Number.isFinite(x.x)))return w;let k=F.reduce((x,v)=>Math.max(x,v.x),-1/0),S=0,_=0;for(let x=0;x<s;x++){let v=y(F[x].r,F[x].x-k);S+=v*e[x],_+=v}return S/_})}function St(o,i,t,n){let e=Array.from(o),s=Array.from(i),u=Array.from(t),r=e.length;if(s.length!==r||u.length!==r)throw new RangeError("'xi', 'yi' and 'di' must have the same length");let a=T([...e].sort((h,m)=>h-m)),f=a===0?X(e,s,u):void 0;if(f?.lost&&[e,s,u].every(h=>h.every(Number.isFinite))){let h=Math.floor(Math.log2($(e.map(Math.abs))));h!==0&&([a,f]=[h,void 0])}f===void 0&&(f=X(e.map(h=>y(h,-a)),s,u.map(h=>y(h,a))));let{z:c,coef:p}=f,d=2*r;return Array.from(n,h=>{let m=p[d-1],g=a===0?h:y(h,-a);for(let l=d-2;l>=0;l--)m=m*(g-c[l])+p[l];return m})}function X(o,i,t){let n=o.flatMap(f=>[f,f]),e=n.length,s=!1,u=i.flatMap(f=>[f,f]),r=[u[0]],a=u.slice();for(let f=1;f<e;f++){let c=[];for(let p=0;p<e-f;p++)if(f===1&&n[p+1]===n[p])c.push(t[p>>1]);else{let d=a[p+1]-a[p],h=n[p+f]-n[p],m=J(a[p],a[p+1],h);Number.isFinite(a[p+1])&&Number.isFinite(a[p])&&d!==0&&h!==0&&!(Math.abs(m)>=2**-1022&&Math.abs(m)<1/0)&&(s=!0),c.push(m)}r.push(c[0]),a=c}return{z:n,coef:r,lost:s}}var vt=["method"];function It(o,i,t,n=[],e={}){j(e,vt,"ode");let s=e.method??"rk4";if(s!=="euler"&&s!=="rk2"&&s!=="rk4")throw new RangeError(`unknown method '${String(s)}'`);if(!i.every(Number.isFinite))throw new RangeError("'times' must be finite values");let u=[...n],r=o.length,a=(d,h)=>{let m=Array.from(t(d,h,u));if(m.length!==r)throw new RangeError(`The number of derivatives returned by func() (${m.length}) must equal the length of the initial conditions vector (${r})`);return m},f=(d,h,m)=>d.map((g,l)=>g+h*m[l]),c=[...o],p=[];if(i.length===0)return p;p.push([i[0],...c]);for(let d=1;d<i.length;d++){let h=i[d-1],m=i[d]-h;if(!Number.isFinite(m)&&Number.isFinite(h)&&Number.isFinite(i[d])){c=_t(c,h,i[d]/2-h/2,s,a),p.push([i[d],...c]);continue}let g=a(h,c);if(s==="euler")c=f(c,m,g);else if(s==="rk2"){let l=a(h+m,f(c,m,g));c=c.map((b,N)=>b+m*(.5*g[N]+.5*l[N]))}else{let l=a(h+m/2,f(c,m/2,g)),b=a(h+m/2,f(c,m/2,l)),N=a(h+m,f(c,m,b)),M=m/6,A=m===0||Math.abs(M)>=2**-1022,E=Math.abs(m)<1?2**60:1;c=c.map((R,w)=>{let F=M*(g[w]+2*l[w]+2*b[w]+N[w]);if(A&&Number.isFinite(F))return R+F;let k=g[w]/4+l[w]/2+b[w]/2+N[w]/4,S=m*E*k;if(!Number.isFinite(k)&&[g[w],l[w],b[w],N[w]].every(Number.isFinite)){let x=g[w]/8+l[w]/4+b[w]/4+N[w]/8;return R+2*(m*x/1.5)}if(Number.isFinite(S)||!Number.isFinite(k))return R+S/1.5/E;let _=m*k;return R+(Number.isFinite(_)?_/1.5:2*(m/2*k/1.5))})}p.push([i[d],...c])}return p}function _t(o,i,t,n,e){let s=(d,h,m)=>d.map((g,l)=>g+h*m[l]+h*m[l]),u=i+t,r=u+t,a=e(i,o);if(n==="euler")return s(o,t,a);if(n==="rk2"){let d=e(r,s(o,t,a));return s(o,t,a.map((h,m)=>.5*h+.5*d[m]))}let f=e(u,o.map((d,h)=>d+t*a[h])),c=e(u,o.map((d,h)=>d+t*f[h])),p=e(r,s(o,t,c));return s(o,t/1.5,a.map((d,h)=>d/4+f[h]/2+c[h]/2+p[h]/4))}var zt=["method","eps","d","zeroTol","r"],jt=["method","eps","d","zeroTol","r"],Ot=["method","eps","d","zeroTol","r"];function et(o){if(!(Number.isFinite(o)&&o!==0))throw new RangeError("'eps' must be a finite nonzero number")}function rt(o){let i=o.eps??1e-4;return et(i),i}function G(o,i,t){let n=i.eps??1e-4,e=i.d??t,s=i.zeroTol??Math.sqrt(Number.EPSILON/7e-7);if(!(Number.isFinite(e)&&e!==0))throw new RangeError("'d' must be a finite nonzero number");if(et(n),!(Number.isFinite(s)&&s>=0))throw new RangeError("'zeroTol' must be a non-negative finite number");let u=i.r??4;if(!(Number.isInteger(u)&&u>=1))throw new RangeError("'r' must be a positive integer");if(u>512)throw new RangeError("'r' must be at most 512");let r=o.map(a=>Math.abs(e*a)+(Math.abs(a)<s?n:0));return r.forEach((a,f)=>{if(!(Math.abs(a)>0&&Math.abs(a)<1/0))throw new RangeError(`the step for x[${f}] is ${a}: not a nonzero finite number`)}),{eps:n,r:u,h0:r}}function q(o){let i=[...o];for(let t=1;t<i.length;t++){let n=4**t;for(let e=0;e<i.length-t;e++)i[e]=(i[e+1]*n-i[e])/(n-1)}return i[0]}function I(o,i,t){let n=[...o];return n[i]=n[i]+t,n}function ot(o){let i=o.method??"Richardson";if(i!=="Richardson"&&i!=="simple")throw new RangeError(`unknown method "${String(i)}" (expected "Richardson" or "simple")`);return i}function $t(o,i,t={}){j(t,zt,"grad");let n=[...i],e=n.length;if(ot(t)==="simple"){let a=rt(t),f=o([...n]);return n.map((c,p)=>(o(I(n,p,a))-f)/a)}let{r:s,h0:u}=G(n,t,1e-4),r=[];for(let a=0;a<e;a++){let f=[],c=u[a];for(let p=0;p<s;p++){if(p>0&&Math.abs(f[p-1])<1e-20?f.push(0):f.push((o(I(n,a,c))-o(I(n,a,-c)))/(2*c)),Number.isNaN(f[p]))throw new RangeError(`func returned NaN at step ${c} from x`);c/=2}r.push(q(f))}return r}function Tt(o,i,t={}){j(t,Ot,"jacobian");let n=[...i],e=n.length,s=Array.from(o([...n])),u=s.map(()=>new Array(e).fill(NaN)),r=c=>{let p=o(c);if(p.length!==s.length)throw new RangeError(`jacobian: func returned ${p.length} values at a shifted x, but ${s.length} at x`);return p};if(ot(t)==="simple"){let c=rt(t);for(let p=0;p<e;p++){let d=r(I(n,p,c));s.forEach((h,m)=>u[m][p]=(d[m]-h)/c)}return u}let{r:a,h0:f}=G(n,t,1e-4);for(let c=0;c<e;c++){let p=s.map(()=>[]),d=f[c];for(let h=0;h<a;h++){let m=r(I(n,c,d)),g=r(I(n,c,-d));s.forEach((l,b)=>p[b].push((m[b]-g[b])/(2*d))),d/=2}s.forEach((h,m)=>u[m][c]=q(p[m]))}return u}function Ct(o,i,t={}){if(j(t,jt,"hessian"),(t.method??"Richardson")!=="Richardson")throw new RangeError('hessian supports only method "Richardson"');let n=[...i],e=n.length,{r:s,h0:u}=G(n,t,.1),r=o([...n]),a=[];for(let c=0;c<e;c++){let p=[],d=u[c];for(let h=0;h<s;h++){let m=o(I(n,c,d)),g=o(I(n,c,-d)),l=m-2*r+g,b=d**2;!Number.isFinite(l)&&Number.isFinite(m)&&Number.isFinite(g)&&Number.isFinite(r)?p.push((m/d-2*(r/d)+g/d)/d):p.push(Number.isFinite(b)?l/b:l/d/d),d/=2}a.push(q(p))}let f=n.map(()=>new Array(e).fill(NaN));for(let c=0;c<e;c++){f[c][c]=a[c];for(let p=0;p<c;p++){let d=[],h=u[c],m=u[p];for(let g=0;g<s;g++){let l=I(I(n,c,h),p,m),b=I(I(n,c,-h),p,-m),N=o(l),M=o(b),A=N-2*r+M,E=2*h*m;!Number.isFinite(A)&&Number.isFinite(N)&&Number.isFinite(M)&&Number.isFinite(r)?d.push((N/h/m-2*(r/h/m)+M/h/m-a[c]*(h/m)-a[p]*(m/h))/2):Number.isFinite(E)&&Number.isFinite(h**2)&&Number.isFinite(m**2)?d.push((A-a[c]*h**2-a[p]*m**2)/E):d.push((A/h/m-a[c]*(h/m)-a[p]*(m/h))/2),h/=2,m/=2}f[c][p]=f[p][c]=q(d)}}return f}export{gt as approx,kt as barylag,$t as grad,St as hermiteInterp,Ct as hessian,st as integrate,Tt as jacobian,It as ode,ft as optim,at as optimHess,it as optimize,Ft as spline,At as splinefun,xt as splinefunH,ct as uniroot};
|
|
1
|
+
/*! rStats.js 1.0.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
|
|
2
|
+
import{a as st,b as it,c as ct,e as at,f as ft}from"./chunks/chunk-4F2IALD4.js";import"./chunks/chunk-3W5NFFAA.js";import{a as D,f as Z}from"./chunks/chunk-QZK3CCBA.js";import"./chunks/chunk-UKNDX4BA.js";import{b as P}from"./chunks/chunk-BQSIBJVX.js";import"./chunks/chunk-NSWENS3S.js";import"./chunks/chunk-BWKHYRM6.js";import{a as $,b as V,c as K}from"./chunks/chunk-CKV4JWW2.js";import{l as j,u as y,v as C,x as Q}from"./chunks/chunk-63OPBEYO.js";var ut=["xout","method","n","yleft","yright","rule","f","ties"],lt=["n","method","xmin","xmax","xout","ties"],ht=["method","ties"];function H(o,i,t="mean"){if(o.length!==i.length)throw new RangeError("'x' and 'y' lengths differ");let n=[];for(let r=0;r<o.length;r++)!Number.isNaN(o[r])&&!Number.isNaN(i[r])&&n.push(r);n.sort((r,a)=>o[r]-o[a]);let e=typeof t=="function"?t:t==="min"?r=>K(r):t==="max"?r=>$(r):Q,s=[],u=[];for(let r=0;r<n.length;){let a=o[n[r]],f=r+1;for(;f<n.length&&o[n[f]]===a;)f++;s.push(a),u.push(f-r===1?i[n[r]]:e(n.slice(r,f).map(c=>i[c]))),r=f}return{x:s,y:u}}function mt(o,i,t,n){let e=(n-o[t])/(o[t+1]-o[t]);(!Number.isFinite(o[t+1]-o[t])||!Number.isFinite(n-o[t]))&&(e=(n/2-o[t]/2)/(o[t+1]/2-o[t]/2));let s=i[t+1]-i[t];return!Number.isFinite(s)&&Number.isFinite(i[t])&&Number.isFinite(i[t+1])?2*(i[t]/2+(i[t+1]/2-i[t]/2)*e):i[t]+s*e}function J(o,i,t){let n=i-o;return!Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)?2*((i/2-o/2)/t):n/t}function O(o,i,t){let n=1,e=t;for(let s of o){if(s===0)return 0*n;let u=Math.floor(Math.log2(Math.abs(s)));n*=y(s,-u),e+=u}for(let s of i){let u=Math.floor(Math.log2(Math.abs(s)));n/=y(s,-u),e-=u}return C(n,e)}function pt(o,i,t){let n=(e,s)=>e===0?0:e*s;return n(1-t,o[i])+n(t,o[i+1])}function bt(o){if(o===void 0)return"linear";if(typeof o=="string"&&o.length>0){let i=["linear","constant"].filter(t=>t.startsWith(o));if(i.length===1)return i[0]}throw new RangeError("invalid interpolation method")}function dt(o){let i=typeof o=="number"?[o]:Array.isArray(o)?o:[],t=n=>n===1||n===2;if(i.length<1||i.length>2||!i.every(t))throw new RangeError("'rule' must be 1 or 2, or a pair of them");return[i[0],i[i.length-1]]}function gt(o,i,t={}){j(t,ut,"approx");let{n=50,f:e=0,rule:s=1,ties:u="mean"}=t,r=bt(t.method),[a,f]=dt(s),c=H(o,i,u),p=c.x.length;if(p<=1&&r==="linear")throw new RangeError("need at least two non-NA values to interpolate");if(p===0)throw new RangeError("zero non-NA points");if(r==="constant"&&!(e>=0&&e<=1))throw new RangeError("approx(): invalid f value");let d=t.yleft??(a===1?NaN:c.y[0]),h=t.yright??(f===1?NaN:c.y[p-1]),m;if(t.xout!==void 0)m=Array.from(t.xout);else{if(!Number.isFinite(n)&&!Number.isNaN(n))throw new RangeError("'length.out' must be a finite number");if(!(n>0))throw new RangeError("'approx' requires n >= 1");m=D(c.x[0],c.x[p-1],n)}let g=c.x,l=c.y,b=Z(m,g),N=m.map((M,A)=>{let E=b[A];if(Number.isNaN(E))return NaN;if(E===0)return d;let R=E-1;return M===g[R]?l[R]:E===p?h:r==="linear"?mt(g,l,R,M):pt(l,R,e)});return{x:m,y:N}}function W(o,i){let t=o.length,n=new Array(t).fill(0),e=new Array(t).fill(0),s=new Array(t).fill(0);if(t<2)return{b:n,c:e,d:s};if(t<3)return n[0]=J(i[0],i[1],o[1]-o[0]),n[1]=n[0],{b:n,c:e,d:s};let u=t-1;s[0]=o[1]-o[0],e[1]=(i[1]-i[0])/s[0];for(let r=1;r<u;r++)s[r]=o[r+1]-o[r],n[r]=2*(s[r-1]+s[r]),e[r+1]=(i[r+1]-i[r])/s[r],e[r]=e[r+1]-e[r];n[0]=-s[0],n[u]=-s[t-2],e[0]=0,e[u]=0,t>3&&(e[0]=e[2]/(o[3]-o[1])-e[1]/(o[2]-o[0]),e[u]=e[t-2]/(o[u]-o[t-3])-e[t-3]/(o[t-2]-o[t-4]),e[0]=e[0]*s[0]*s[0]/(o[3]-o[0]),e[u]=-e[u]*s[t-2]*s[t-2]/(o[u]-o[t-4]));for(let r=1;r<t;r++){let a=s[r-1]/n[r-1];n[r]=n[r]-a*s[r-1],e[r]=e[r]-a*e[r-1]}e[u]=e[u]/n[u];for(let r=t-2;r>=0;r--)e[r]=(e[r]-s[r]*e[r+1])/n[r];n[u]=(i[u]-i[t-2])/s[t-2]+s[t-2]*(e[t-2]+2*e[u]);for(let r=0;r<u;r++)n[r]=(i[r+1]-i[r])/s[r]-s[r]*(e[r+1]+2*e[r]),s[r]=(e[r+1]-e[r])/s[r],e[r]=3*e[r];return e[u]=3*e[u],s[u]=s[t-2],{b:n,c:e,d:s}}function tt(o,i,t){let n=o.length,e=new Array(n).fill(0),s=new Array(n).fill(0),u=new Array(n).fill(0);for(let r=0;r<n-1;r++){let a=o[r+1]-o[r];e[r]=(i[r+1]-i[r])/a-a*(t[r+1]+2*t[r]),s[r]=3*t[r],u[r]=(t[r+1]-t[r])/a}return{b:e,c:s,d:u}}function Nt(o,i){let t=o.length;if(t<3)return W(o,i);let n=Array.from({length:t-1},(f,c)=>o[c+1]-o[c]),e=n.map((f,c)=>(i[c+1]-i[c])/f),s=new Array(t).fill(0),u=new Array(t).fill(0);for(let f=1;f<t-1;f++)s[f]=2*(n[f-1]+n[f]),u[f]=e[f]-e[f-1];for(let f=2;f<t-1;f++){let c=n[f-1]/s[f-1];s[f]=s[f]-c*n[f-1],u[f]=u[f]-c*u[f-1]}let r=new Array(t).fill(0);r[t-2]=u[t-2]/s[t-2];for(let f=t-3;f>=1;f--)r[f]=(u[f]-n[f]*r[f+1])/s[f];let a=tt(o,i,r);return a.b[t-1]=e[t-2]+n[t-2]*r[t-2],a}function wt(o,i){let t=o.length;if(i[0]!==i[t-1])throw new RangeError("periodic spline needs y[1] == y[n]");if(t<3)return{b:new Array(t).fill(0),c:new Array(t).fill(0),d:new Array(t).fill(0)};let n=t-1,e=Array.from({length:n},(l,b)=>o[b+1]-o[b]),s=e.map((l,b)=>(i[b+1]-i[b])/l),u=l=>l===0?n-1:l-1,r=Array.from({length:n},(l,b)=>2*(e[u(b)]+e[b])),a=Array.from({length:n},(l,b)=>s[b]-s[u(b)]),f=e.slice(),c=new Array(n).fill(0);c[0]=e[n-1],c[n-2]=c[n-2]+e[n-2];let p=c[0],d=r[n-1],h=a[n-1];for(let l=0;l<n-1;l++){if(l+1<n-1){let N=e[l]/r[l];r[l+1]=r[l+1]-N*f[l],c[l+1]=c[l+1]-N*c[l],a[l+1]=a[l+1]-N*a[l]}let b=p/r[l];d-=b*c[l],h-=b*a[l],l+1<n-1&&(p=(l+1===n-2?e[n-2]:0)-b*f[l])}let m=new Array(t).fill(0);m[n-1]=h/d;for(let l=n-2;l>=0;l--){let b=a[l]-c[l]*m[n-1]-(l<n-2?f[l]*m[l+1]:0);m[l]=b/r[l]}m[t-1]=m[0];let g=tt(o,i,m);return g.b[t-1]=g.b[0],g.c[t-1]=g.c[0],g.d[t-1]=g.d[0],g}function Mt(o,i){let t=o.length,{b:n,c:e,d:s}=W(o,i);if(t<2)return{b:n,c:e,d:s};let u=Array.from({length:t-1},(a,f)=>(i[f+1]-i[f])/(o[f+1]-o[f]));for(let a=0;a<t;a++){let f=u[a===0?0:a-1],c=u[a===t-1?t-2:a],p=Math.min(Math.abs(f),Math.abs(c)),d=f>0&&c>0||f<0&&c<0?c>0:n[a]>=0;n[a]=d?Math.min(Math.max(0,n[a]),3*p):Math.max(Math.min(0,n[a]),-3*p)}for(let a=0;a<t-1;a++){let f=o[a+1]-o[a],c=(i[a+1]-i[a])/f;e[a]=(3*c-2*n[a]-n[a+1])/f,s[a]=(n[a]+n[a+1]-2*c)/(f*f)}let r=o[t-1]-o[t-2];return e[t-1]=(n[t-2]+2*n[t-1]-3*(i[t-1]-i[t-2])/r)/r,s[t-1]=s[t-2],{b:n,c:e,d:s}}function T(o){let i=o.length;return i<2||!o.every(Number.isFinite)||Number.isFinite(o[i-1]-o[0])?0:Math.floor(Math.log2($(o.map(Math.abs))))}function L(o,i,t,n){let e=H(o,i,n),s=e.x.length;if(s===0)throw new RangeError("zero non-NA points");t==="periodic"&&e.y[s-1]!==e.y[0]&&(e.y[s-1]=e.y[0]),t==="hyman"&&yt(e.y);let u=t==="fmm"?W(e.x,e.y):t==="natural"?Nt(e.x,e.y):t==="periodic"?wt(e.x,e.y):t==="hyman"?Mt(e.x,e.y):(()=>{throw new RangeError(`invalid spline method '${String(t)}'`)})();return{method:t,...e,...u}}function yt(o){let i=!0,t=!0;for(let n=1;n<o.length;n++){let e=o[n]-o[n-1];e>=0||(i=!1),e<=0||(t=!1)}if(!i&&!t)throw new RangeError("'y' must be increasing or decreasing")}function B(o){let i=Math.trunc(o);if(!(i>=0&&i<=3))throw new RangeError("'deriv' must be between 0 and 3");return i}function Y(o,i,t){let n=B(t),{x:e,y:s,b:u,c:r,d:a,method:f}=o,c=e.length,p=f==="natural",d=e[c-1]-e[0],h=0;return Array.from(i,m=>{let g=m;if(f==="periodic"&&c>1){let N=(g-e[0])%d;N<0&&(N+=d),g=e[0]+N}if(p&&n>0&&g<=e[0])return n===1?u[0]:0;if(!(e[h]<=g&&(h===c-1||g<=e[h+1]))){let N=0,M=c;for(;M-N>1;){let A=N+M>>1;e[A]<=g?N=A:M=A}h=N}let l=g-e[h],b=p&&g<e[0]?0:a[h];switch(n){case 0:return s[h]+l*(u[h]+l*(r[h]+l*b));case 1:return u[h]+l*(2*r[h]+l*(3*b));case 2:return 2*r[h]+l*(6*b);default:return 6*b}})}function Ft(o,i,t={}){j(t,lt,"spline");let{method:n="fmm",ties:e="mean"}=t,s=L(o,i,n,e),u=T(s.x);u!==0&&(s=L(Array.from(o,a=>y(a,-u)),i,n,e));let r;if(t.xout!==void 0)r=Array.from(t.xout);else{let a=s.x.length,f=t.n??3*a;if(!Number.isFinite(f))throw new RangeError("'length.out' must be a finite number");if(!(f>0))throw new RangeError("'spline' requires n >= 1");r=D(t.xmin??y(s.x[0],u),t.xmax??y(s.x[a-1],u),f)}return{x:r,y:Y(s,u===0?r:r.map(a=>y(a,-u)),0)}}function At(o,i,t={}){j(t,ht,"splinefun");let n=Et(o,i,t);return(e,...s)=>n(e,P(["deriv"],s,"the function from splinefun").deriv??0)}function Et(o,i,t){let{method:n="fmm",ties:e="mean"}=t;if(n==="monoH.FC"){let r=H(o,i,e);if(r.x.length===0)throw new RangeError("zero non-NA points");let a=T(r.x);a!==0&&(r=H(Array.from(o,c=>y(c,-a)),i,e));let f=Rt(r.x,r.y);return(c,p)=>nt(r.x,r.y,f,a,a,c,p)}let s=L(o,i,n,e),u=T(s.x);return u===0?(r,a)=>Y(s,r,a):(s=L(Array.from(o,r=>y(r,-u)),i,n,e),(r,a)=>{let f=B(a);return Y(s,Array.from(r,c=>y(c,-u)),f).map(c=>y(c,-f*u))})}function Rt(o,i){let t=o.length;if(t<2)throw new RangeError("length(m) must be at least two");let n=Array.from({length:t-1},(s,u)=>(i[u+1]-i[u])/(o[u+1]-o[u])),e=Array.from({length:t},(s,u)=>u===0?n[0]:u===t-1?n[t-2]:V(n[u-1],n[u]));for(let s=0;s<t-1;s++){let u=n[s];if(u===0){e[s]=0,e[s+1]=0;continue}let r=e[s]/u,a=e[s+1]/u,f=2*r+a-3,c=r+2*a-3;if(!(Number.isFinite(r*(f+c))&&Number.isFinite(f*f)&&Number.isFinite(r*r+a*a))&&Number.isFinite(e[s])&&Number.isFinite(e[s+1])&&Number.isFinite(u)){let d=M=>M===0?-1/0:Math.floor(Math.log2(Math.abs(M))),h=Math.max(d(e[s]),d(e[s+1]))-d(u),m=O([e[s]],[u],-h),g=O([e[s+1]],[u],-h),l=C(3,-h),b=2*m+g-l,N=m+2*g-l;if(b>0&&N>0&&m*(b+N)<b*b){let M=3*u/Math.sqrt(m*m+g*g);e[s]=M*m,e[s+1]=M*g}continue}if(f>0&&c>0&&r*(f+c)<f*f){let d=3*u/Math.sqrt(r*r+a*a);e[s]=d*r,e[s+1]=d*a}}return e}function nt(o,i,t,n,e,s,u){let r=B(u),a=o.length;return Array.from(s,f=>{if(Number.isNaN(f))return NaN;let c=n===0?f:y(f,-n),p=0,d=a;for(;p<d;){let w=p+d>>1;o[w]<=c?p=w+1:d=w}let h=p;if(h===0||h===a){let w=h===0?0:a-1;return r===0?i[w]+y(t[w]*(c-o[w]),n-e):r===1?y(t[w],-e):0}let m=o[h-1],g=o[h]-m,l=(c-m)/g,b=l-1,N=i[h-1],M=i[h],A=t[h-1],E=t[h],R=y(J(N,M,g),e-n);switch(r){case 0:{let w=l*l*(3-2*l),F=(k,S)=>{let _=y(g*k,n-e)*S;return Number.isFinite(_)||!Number.isFinite(k)||!Number.isFinite(S)?_:O([g,k,S],[],n-e)};return N*(1-w)+F(A,l*b*b)+M*w+F(E,l*l*b)}case 1:{if(Number.isFinite(R)||!Number.isFinite(N)||!Number.isFinite(M))return y(R*(-6*l*b)+A*(b*(3*l-1))+E*(l*(3*l-2)),-e);let w=M-N;return(Number.isFinite(w)?O([w,-6*l*b],[g],-n):O([M/2-N/2,-6*l*b],[g],1-n))+y(A*(b*(3*l-1))+E*(l*(3*l-2)),-e)}case 2:{if(Number.isFinite(R)||!Number.isFinite(N)||!Number.isFinite(M))return y((R*(6-12*l)+A*(6*l-4)+E*(6*l-2))/g,-e-n);let w=M-N;return(Number.isFinite(w)?O([w,6-12*l],[g,g],-2*n):O([M/2-N/2,6-12*l],[g,g],1-2*n))+y((A*(6*l-4)+E*(6*l-2))/g,-e-n)}default:{let w=-12*R+6*A+6*E,F=g*g;return F>=2**-1022&&F<1/0?y(w/F,-e-2*n):y(w/g/g,-e-2*n)}}})}function xt(o,i,t){let n=o.length;if(i.length!==n||t.length!==n)throw new RangeError("'x', 'y' and 'm' must have the same length");let e=Array.from({length:n},(c,p)=>p).sort((c,p)=>o[c]-o[p]),s=e.map(c=>o[c]),u=e.map(c=>i[c]),r=e.map(c=>t[c]);for(let c=1;c<n;c++)if(!(s[c]-s[c-1]>0))throw new RangeError("'x' must be *strictly* increasing (non - NA)");let a=T(s),f=a===0?s:s.map(c=>y(c,-a));return(c,...p)=>nt(f,u,r,a,0,c,P(["deriv"],p,"the function from splinefunH").deriv??0)}function kt(o,i,t){let n=Array.from(o),e=Array.from(i),s=n.length;if(e.length!==s)throw new RangeError("'xi' and 'yi' must have the same length");let u=Array.from(t),r=K(n),a=$(n);if(u.some(b=>b<r||b>a))throw new RangeError("Some interpolation points outside the nodes.");let f=Number.isFinite(r)&&Number.isFinite(a)&&!Number.isFinite(a-r),c=f?n.map(b=>b/2):n,p=c.map((b,N)=>{let M=1,A=0;for(let E=0;E<s;E++){if(E===N)continue;let R=b-c[E],w=M*R;if(M!==0&&R!==0&&Number.isFinite(R)&&!(Math.abs(w)>=2**-1022&&Math.abs(w)<1/0)){let k=Math.floor(Math.log2(Math.abs(M))),S=Math.floor(Math.log2(Math.abs(R)));M=y(M,-k)*y(R,-S),A+=k+S;continue}M=w;let F=Math.abs(M);if(F>2**500||F<2**-500&&F>0){let k=Math.floor(Math.log2(F));M=y(M,-k),A+=k}}return{p:M,e:A}}),d=p.reduce((b,N)=>Math.max(b,-N.e),-1/0),h=p.map(b=>y(1/b.p,-b.e-d)),m=n.every(Number.isFinite)&&e.every(Number.isFinite),g=m?e.reduce((b,N)=>N===0?b:Math.max(b,Math.floor(Math.log2(Math.abs(N)))),-1/0):0,l=b=>{if(g===-1/0)return 0;let N=1,M=0,A=[];for(let F=0;F<s;F++){let k=b-c[F];if(k===0)return;let S=Math.floor(Math.log2(Math.abs(k))),_=y(k,-S);N*=_;let x=Math.floor(Math.log2(Math.abs(N)));N=y(N,-x),M+=S+x;let v=1/p[F].p/_;if(!Number.isFinite(v)||v===0)return;let z=Math.floor(Math.log2(Math.abs(v)));A.push({r:y(v,-z),x:z-p[F].e-S})}let E=A.reduce((F,k)=>Math.max(F,k.x),-1/0),R=0;for(let F=0;F<s;F++)R+=y(A[F].r,A[F].x-E)*y(e[F],-g);if(R===0)return 0;let w=Math.floor(Math.log2(Math.abs(R)));return C(N*y(R,-w),M+E+g+w)};return u.map(b=>{let N=0,M=0,A=n.lastIndexOf(b);if(A>=0)return e[A];let E=0,R=0;for(let x=0;x<s;x++){let v=(f?b/2:b)-c[x],z=h[x]/v;N+=z*e[x],M+=z,E+=Math.abs(z),R+=Math.abs(z*e[x])}let w=N/M;if(m&&Number.isFinite(E)&&E>0&&Math.abs(M)<y(E,-100)&&Number.isFinite(R)&&Math.abs(N)>=y(R,-26)){let x=l(f?b/2:b);if(x!==void 0)return x}if(Number.isFinite(w)||!m)return w;let F=p.map((x,v)=>{let z=(f?b/2:b)-c[v],U=Math.floor(Math.log2(Math.abs(z)));return{r:1/x.p/y(z,-U),x:-x.e-U}});if(!F.every(x=>Number.isFinite(x.r)&&Number.isFinite(x.x)))return w;let k=F.reduce((x,v)=>Math.max(x,v.x),-1/0),S=0,_=0;for(let x=0;x<s;x++){let v=y(F[x].r,F[x].x-k);S+=v*e[x],_+=v}return S/_})}function St(o,i,t,n){let e=Array.from(o),s=Array.from(i),u=Array.from(t),r=e.length;if(s.length!==r||u.length!==r)throw new RangeError("'xi', 'yi' and 'di' must have the same length");let a=T([...e].sort((h,m)=>h-m)),f=a===0?X(e,s,u):void 0;if(f?.lost&&[e,s,u].every(h=>h.every(Number.isFinite))){let h=Math.floor(Math.log2($(e.map(Math.abs))));h!==0&&([a,f]=[h,void 0])}f===void 0&&(f=X(e.map(h=>y(h,-a)),s,u.map(h=>y(h,a))));let{z:c,coef:p}=f,d=2*r;return Array.from(n,h=>{let m=p[d-1],g=a===0?h:y(h,-a);for(let l=d-2;l>=0;l--)m=m*(g-c[l])+p[l];return m})}function X(o,i,t){let n=o.flatMap(f=>[f,f]),e=n.length,s=!1,u=i.flatMap(f=>[f,f]),r=[u[0]],a=u.slice();for(let f=1;f<e;f++){let c=[];for(let p=0;p<e-f;p++)if(f===1&&n[p+1]===n[p])c.push(t[p>>1]);else{let d=a[p+1]-a[p],h=n[p+f]-n[p],m=J(a[p],a[p+1],h);Number.isFinite(a[p+1])&&Number.isFinite(a[p])&&d!==0&&h!==0&&!(Math.abs(m)>=2**-1022&&Math.abs(m)<1/0)&&(s=!0),c.push(m)}r.push(c[0]),a=c}return{z:n,coef:r,lost:s}}var vt=["method"];function It(o,i,t,n=[],e={}){j(e,vt,"ode");let s=e.method??"rk4";if(s!=="euler"&&s!=="rk2"&&s!=="rk4")throw new RangeError(`unknown method '${String(s)}'`);if(!i.every(Number.isFinite))throw new RangeError("'times' must be finite values");let u=[...n],r=o.length,a=(d,h)=>{let m=Array.from(t(d,h,u));if(m.length!==r)throw new RangeError(`The number of derivatives returned by func() (${m.length}) must equal the length of the initial conditions vector (${r})`);return m},f=(d,h,m)=>d.map((g,l)=>g+h*m[l]),c=[...o],p=[];if(i.length===0)return p;p.push([i[0],...c]);for(let d=1;d<i.length;d++){let h=i[d-1],m=i[d]-h;if(!Number.isFinite(m)&&Number.isFinite(h)&&Number.isFinite(i[d])){c=_t(c,h,i[d]/2-h/2,s,a),p.push([i[d],...c]);continue}let g=a(h,c);if(s==="euler")c=f(c,m,g);else if(s==="rk2"){let l=a(h+m,f(c,m,g));c=c.map((b,N)=>b+m*(.5*g[N]+.5*l[N]))}else{let l=a(h+m/2,f(c,m/2,g)),b=a(h+m/2,f(c,m/2,l)),N=a(h+m,f(c,m,b)),M=m/6,A=m===0||Math.abs(M)>=2**-1022,E=Math.abs(m)<1?2**60:1;c=c.map((R,w)=>{let F=M*(g[w]+2*l[w]+2*b[w]+N[w]);if(A&&Number.isFinite(F))return R+F;let k=g[w]/4+l[w]/2+b[w]/2+N[w]/4,S=m*E*k;if(!Number.isFinite(k)&&[g[w],l[w],b[w],N[w]].every(Number.isFinite)){let x=g[w]/8+l[w]/4+b[w]/4+N[w]/8;return R+2*(m*x/1.5)}if(Number.isFinite(S)||!Number.isFinite(k))return R+S/1.5/E;let _=m*k;return R+(Number.isFinite(_)?_/1.5:2*(m/2*k/1.5))})}p.push([i[d],...c])}return p}function _t(o,i,t,n,e){let s=(d,h,m)=>d.map((g,l)=>g+h*m[l]+h*m[l]),u=i+t,r=u+t,a=e(i,o);if(n==="euler")return s(o,t,a);if(n==="rk2"){let d=e(r,s(o,t,a));return s(o,t,a.map((h,m)=>.5*h+.5*d[m]))}let f=e(u,o.map((d,h)=>d+t*a[h])),c=e(u,o.map((d,h)=>d+t*f[h])),p=e(r,s(o,t,c));return s(o,t/1.5,a.map((d,h)=>d/4+f[h]/2+c[h]/2+p[h]/4))}var zt=["method","eps","d","zeroTol","r"],jt=["method","eps","d","zeroTol","r"],Ot=["method","eps","d","zeroTol","r"];function et(o){if(!(Number.isFinite(o)&&o!==0))throw new RangeError("'eps' must be a finite nonzero number")}function rt(o){let i=o.eps??1e-4;return et(i),i}function G(o,i,t){let n=i.eps??1e-4,e=i.d??t,s=i.zeroTol??Math.sqrt(Number.EPSILON/7e-7);if(!(Number.isFinite(e)&&e!==0))throw new RangeError("'d' must be a finite nonzero number");if(et(n),!(Number.isFinite(s)&&s>=0))throw new RangeError("'zeroTol' must be a non-negative finite number");let u=i.r??4;if(!(Number.isInteger(u)&&u>=1))throw new RangeError("'r' must be a positive integer");if(u>512)throw new RangeError("'r' must be at most 512");let r=o.map(a=>Math.abs(e*a)+(Math.abs(a)<s?n:0));return r.forEach((a,f)=>{if(!(Math.abs(a)>0&&Math.abs(a)<1/0))throw new RangeError(`the step for x[${f}] is ${a}: not a nonzero finite number`)}),{eps:n,r:u,h0:r}}function q(o){let i=[...o];for(let t=1;t<i.length;t++){let n=4**t;for(let e=0;e<i.length-t;e++)i[e]=(i[e+1]*n-i[e])/(n-1)}return i[0]}function I(o,i,t){let n=[...o];return n[i]=n[i]+t,n}function ot(o){let i=o.method??"Richardson";if(i!=="Richardson"&&i!=="simple")throw new RangeError(`unknown method "${String(i)}" (expected "Richardson" or "simple")`);return i}function $t(o,i,t={}){j(t,zt,"grad");let n=[...i],e=n.length;if(ot(t)==="simple"){let a=rt(t),f=o([...n]);return n.map((c,p)=>(o(I(n,p,a))-f)/a)}let{r:s,h0:u}=G(n,t,1e-4),r=[];for(let a=0;a<e;a++){let f=[],c=u[a];for(let p=0;p<s;p++){if(p>0&&Math.abs(f[p-1])<1e-20?f.push(0):f.push((o(I(n,a,c))-o(I(n,a,-c)))/(2*c)),Number.isNaN(f[p]))throw new RangeError(`func returned NaN at step ${c} from x`);c/=2}r.push(q(f))}return r}function Tt(o,i,t={}){j(t,Ot,"jacobian");let n=[...i],e=n.length,s=Array.from(o([...n])),u=s.map(()=>new Array(e).fill(NaN)),r=c=>{let p=o(c);if(p.length!==s.length)throw new RangeError(`jacobian: func returned ${p.length} values at a shifted x, but ${s.length} at x`);return p};if(ot(t)==="simple"){let c=rt(t);for(let p=0;p<e;p++){let d=r(I(n,p,c));s.forEach((h,m)=>u[m][p]=(d[m]-h)/c)}return u}let{r:a,h0:f}=G(n,t,1e-4);for(let c=0;c<e;c++){let p=s.map(()=>[]),d=f[c];for(let h=0;h<a;h++){let m=r(I(n,c,d)),g=r(I(n,c,-d));s.forEach((l,b)=>p[b].push((m[b]-g[b])/(2*d))),d/=2}s.forEach((h,m)=>u[m][c]=q(p[m]))}return u}function Ct(o,i,t={}){if(j(t,jt,"hessian"),(t.method??"Richardson")!=="Richardson")throw new RangeError('hessian supports only method "Richardson"');let n=[...i],e=n.length,{r:s,h0:u}=G(n,t,.1),r=o([...n]),a=[];for(let c=0;c<e;c++){let p=[],d=u[c];for(let h=0;h<s;h++){let m=o(I(n,c,d)),g=o(I(n,c,-d)),l=m-2*r+g,b=d**2;!Number.isFinite(l)&&Number.isFinite(m)&&Number.isFinite(g)&&Number.isFinite(r)?p.push((m/d-2*(r/d)+g/d)/d):p.push(Number.isFinite(b)?l/b:l/d/d),d/=2}a.push(q(p))}let f=n.map(()=>new Array(e).fill(NaN));for(let c=0;c<e;c++){f[c][c]=a[c];for(let p=0;p<c;p++){let d=[],h=u[c],m=u[p];for(let g=0;g<s;g++){let l=I(I(n,c,h),p,m),b=I(I(n,c,-h),p,-m),N=o(l),M=o(b),A=N-2*r+M,E=2*h*m;!Number.isFinite(A)&&Number.isFinite(N)&&Number.isFinite(M)&&Number.isFinite(r)?d.push((N/h/m-2*(r/h/m)+M/h/m-a[c]*(h/m)-a[p]*(m/h))/2):Number.isFinite(E)&&Number.isFinite(h**2)&&Number.isFinite(m**2)?d.push((A-a[c]*h**2-a[p]*m**2)/E):d.push((A/h/m-a[c]*(h/m)-a[p]*(m/h))/2),h/=2,m/=2}f[c][p]=f[p][c]=q(d)}}return f}export{gt as approx,kt as barylag,$t as grad,St as hermiteInterp,Ct as hessian,st as integrate,Tt as jacobian,It as ode,ft as optim,at as optimHess,it as optimize,Ft as spline,At as splinefun,xt as splinefunH,ct as uniroot};
|