@numero-uno-jpn/rstats 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +128 -0
- package/README.ja.md +44 -18
- package/README.md +45 -18
- package/dist/chunks/chunk-2C33MXSW.js +3 -0
- package/dist/chunks/chunk-34S5SQY6.js +2 -0
- package/dist/chunks/{chunk-URIO5LY5.js → chunk-4WE3OO62.js} +2 -2
- package/dist/chunks/chunk-5AYHCITP.js +2 -0
- package/dist/chunks/chunk-6JJQL6HL.js +2 -0
- package/dist/chunks/chunk-C7V2FH6L.js +3 -0
- package/dist/chunks/chunk-CZI7KUO3.js +2 -0
- package/dist/chunks/chunk-DXI5N2ET.js +2 -0
- package/dist/chunks/chunk-FY3FVOBM.js +2 -0
- package/dist/chunks/{chunk-QNNL7AZ3.js → chunk-H3WVPZDL.js} +2 -2
- package/dist/chunks/chunk-LHUIJQHY.js +2 -0
- package/dist/chunks/chunk-LV3W2F7N.js +2 -0
- package/dist/chunks/chunk-M4ITG7YR.js +2 -0
- package/dist/chunks/{chunk-FLJNSXSW.js → chunk-NSYZTS26.js} +2 -2
- package/dist/chunks/chunk-ONY5CISH.js +2 -0
- package/dist/chunks/chunk-RFE7MVP7.js +2 -0
- package/dist/chunks/{chunk-W26LRYOJ.js → chunk-SE7V2KLO.js} +1 -1
- package/dist/chunks/chunk-THIGHOKK.js +2 -0
- package/dist/chunks/chunk-TNMJPQPV.js +2 -0
- package/dist/chunks/chunk-WM7VFXTV.js +2 -0
- package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
- package/dist/chunks/chunk-XLSFJTTK.js +2 -0
- package/dist/chunks/{chunk-5UQCRBAG.js → chunk-Z37NELOS.js} +1 -1
- package/dist/chunks/chunk-ZFQWB222.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 +3 -0
- package/dist/entries/mixed.js +2 -0
- package/dist/entries/numerics.d.ts +2 -1
- package/dist/entries/tests.d.ts +8 -5
- package/dist/entries/tests.js +3 -1
- package/dist/htest/agreement.d.ts +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 +4 -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/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/lm.js +13 -3
- package/dist/models/lmer.d.ts +11 -6
- package/dist/models/lmer.js +20 -15
- package/dist/models/lmerAnova.d.ts +3 -3
- package/dist/models/lmerAnova.js +10 -5
- package/dist/models/lmerTest.d.ts +4 -4
- package/dist/models/lmerTest.js +19 -11
- package/dist/models/mauchly.d.ts +2 -0
- package/dist/models/mauchly.js +7 -2
- package/dist/models/modelFrame.js +2 -2
- package/dist/models/modelMatrix.js +7 -2
- 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 +15 -11
- package/llms.txt +5 -2
- 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-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
|
@@ -54,19 +54,19 @@ export function twoSampleData(formula, data, oneSample) {
|
|
|
54
54
|
if (pair !== null) {
|
|
55
55
|
const { terms, rhsVariables } = plainTerms(`~${sides.rhs}`, data);
|
|
56
56
|
if (!oneSample || !interceptOnly(terms, rhsVariables))
|
|
57
|
-
throw new
|
|
57
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
58
58
|
const frame = modelFrame(data, [pair[1], pair[2]]);
|
|
59
59
|
return { kind: "paired", x: numericValues(frame.variables[0], pair[1]), y: numericValues(frame.variables[1], pair[2]) };
|
|
60
60
|
}
|
|
61
61
|
const { terms, rhsVariables } = plainTerms(formula, data);
|
|
62
62
|
if (terms.response < 0)
|
|
63
|
-
throw new
|
|
63
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
64
64
|
const response = terms.variables[0];
|
|
65
65
|
if (oneSample && interceptOnly(terms, rhsVariables)) {
|
|
66
66
|
return { kind: "one", x: numericValues(modelFrame(data, [response]).variables[0], response) };
|
|
67
67
|
}
|
|
68
68
|
if (rhsVariables.length !== 1 || terms.terms.length !== 1)
|
|
69
|
-
throw new
|
|
69
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
70
70
|
const frame = modelFrame(data, [response, rhsVariables[0]], { dropUnusedLevels: true });
|
|
71
71
|
const values = numericValues(frame.variables[0], response);
|
|
72
72
|
const group = groupFactor(frame.variables[1]);
|
|
@@ -83,16 +83,16 @@ export function twoSampleData(formula, data, oneSample) {
|
|
|
83
83
|
export function twoGroupData(formula, data) {
|
|
84
84
|
const d = twoSampleData(formula, data, false);
|
|
85
85
|
if (d.kind !== "two")
|
|
86
|
-
throw new
|
|
86
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
87
87
|
return d;
|
|
88
88
|
}
|
|
89
89
|
/** The response and group of a formula `y ~ g` with one variable on the right (kruskal.test, fligner.test, bartlett.test) */
|
|
90
90
|
export function kSampleData(formula, data) {
|
|
91
91
|
const { terms, rhsVariables } = plainTerms(formula, data);
|
|
92
92
|
if (terms.response < 0)
|
|
93
|
-
throw new
|
|
93
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
94
94
|
if (rhsVariables.length !== 1)
|
|
95
|
-
throw new
|
|
95
|
+
throw new TypeError("'formula' should be of the form response ~ group");
|
|
96
96
|
const response = terms.variables[0];
|
|
97
97
|
const frame = modelFrame(data, [response, rhsVariables[0]], { dropUnusedLevels: true });
|
|
98
98
|
return { values: numericValues(frame.variables[0], response), group: groupFactor(frame.variables[1]) };
|
|
@@ -110,7 +110,7 @@ export function samplesByLevel(values, group) {
|
|
|
110
110
|
export function onewayData(formula, data) {
|
|
111
111
|
const { terms, rhsVariables } = plainTerms(formula, data);
|
|
112
112
|
if (terms.response < 0 || rhsVariables.length === 0)
|
|
113
|
-
throw new
|
|
113
|
+
throw new TypeError(MISSING_OR_INCORRECT);
|
|
114
114
|
const response = terms.variables[0];
|
|
115
115
|
const frame = modelFrame(data, [response, ...rhsVariables], { dropUnusedLevels: true });
|
|
116
116
|
const factors = frame.variables.slice(1).map(groupFactor);
|
|
@@ -135,11 +135,11 @@ export function blockData(formula, data) {
|
|
|
135
135
|
const sides = splitTilde(formula);
|
|
136
136
|
const parts = sides?.rhs.split("|");
|
|
137
137
|
if (sides === undefined || sides.lhs === "" || parts.length !== 2)
|
|
138
|
-
throw new
|
|
138
|
+
throw new TypeError(INCORRECT_BLOCKS);
|
|
139
139
|
const one = (text) => {
|
|
140
140
|
const { terms, rhsVariables } = plainTerms(text, data);
|
|
141
141
|
if (rhsVariables.length !== 1 || terms.terms.length !== 1)
|
|
142
|
-
throw new
|
|
142
|
+
throw new TypeError(INCORRECT_BLOCKS);
|
|
143
143
|
return rhsVariables[0];
|
|
144
144
|
};
|
|
145
145
|
const { terms } = plainTerms(`${sides.lhs} ~ 1`, data);
|
|
@@ -166,9 +166,9 @@ export function blockData(formula, data) {
|
|
|
166
166
|
export function correlationData(formula, data) {
|
|
167
167
|
const { terms, rhsVariables } = plainTerms(formula, data);
|
|
168
168
|
if (terms.response >= 0)
|
|
169
|
-
throw new
|
|
169
|
+
throw new TypeError("'formula' missing or invalid");
|
|
170
170
|
if (rhsVariables.length !== 2)
|
|
171
|
-
throw new
|
|
171
|
+
throw new TypeError("invalid formula");
|
|
172
172
|
const frame = modelFrame(data, rhsVariables);
|
|
173
173
|
return { x: numericValues(frame.variables[0], rhsVariables[0]), y: numericValues(frame.variables[1], rhsVariables[1]) };
|
|
174
174
|
}
|
|
@@ -10,7 +10,17 @@ export interface PropTrendTestResult extends Omit<HTest, "alternative"> {
|
|
|
10
10
|
parameter: number;
|
|
11
11
|
}
|
|
12
12
|
/**
|
|
13
|
-
*
|
|
13
|
+
* Options for {@link propTrendTest}.
|
|
14
|
+
*
|
|
15
|
+
* @category Hypothesis tests
|
|
16
|
+
*/
|
|
17
|
+
export interface PropTrendTestOptions {
|
|
18
|
+
/** Scores of the groups (as the third argument `score`). Default `1, 2, ..., k`. */
|
|
19
|
+
score?: Sample;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Chi-squared test for trend in proportions. Equivalent to R's `prop.trend.test(x, n, score)`. The scores are the
|
|
23
|
+
* third argument or the option `score` (giving both is a RangeError).
|
|
14
24
|
*
|
|
15
25
|
* @param x Numbers of events.
|
|
16
26
|
* @param n Numbers of trials.
|
|
@@ -26,6 +36,16 @@ export interface PropTrendTestResult extends Omit<HTest, "alternative"> {
|
|
|
26
36
|
* @category Hypothesis tests
|
|
27
37
|
*/
|
|
28
38
|
export declare function propTrendTest(x: Sample, n: Sample, score?: Sample): PropTrendTestResult;
|
|
39
|
+
/**
|
|
40
|
+
* Chi-squared test for trend in proportions, with the scores in the options:
|
|
41
|
+
* `propTrendTest(x, n, { score: [0, 1, 2, 4] })`.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* propTrendTest([15, 10, 8, 4], [30, 30, 30, 30], { score: [1, 2, 3, 4] }).statistic; // 9.573428850537288
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export declare function propTrendTest(x: Sample, n: Sample, options: PropTrendTestOptions): PropTrendTestResult;
|
|
29
49
|
/**
|
|
30
50
|
* Alternative of {@link jonckheereTest}.
|
|
31
51
|
*
|
package/dist/htest/trendTests.js
CHANGED
|
@@ -12,27 +12,20 @@
|
|
|
12
12
|
import { pgamma1 } from "../distributions/gamma.js";
|
|
13
13
|
import { pnorm } from "../distributions/normal.js";
|
|
14
14
|
import { dwilcox1 } from "../distributions/wilcox.js";
|
|
15
|
+
import { optionalArgs } from "../internal/optionalArgs.js";
|
|
15
16
|
import { levelText, numberLevels } from "../internal/levels.js";
|
|
16
17
|
import { ldexp, scaleToUnit, squareOver } from "../internal/summary.js";
|
|
17
18
|
import { compareCodePoints } from "../models/modelFrame.js";
|
|
18
19
|
import { matchChoice } from "./power.js";
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
* @example
|
|
29
|
-
* ```ts
|
|
30
|
-
* propTrendTest([15, 10, 8, 4], [30, 30, 30, 30]).statistic; // 9.573428850537288
|
|
31
|
-
* ```
|
|
32
|
-
*
|
|
33
|
-
* @category Hypothesis tests
|
|
34
|
-
*/
|
|
35
|
-
export function propTrendTest(x, n, score) {
|
|
20
|
+
import { reported } from "../internal/warnings.js";
|
|
21
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
22
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
23
|
+
import { optionsIn } from "../internal/optionalArgs.js";
|
|
24
|
+
const PROP_TREND_TEST_KEYS = ["score"];
|
|
25
|
+
const JONCKHEERE_TEST_KEYS = ["alternative", "exact", "variant", "levels"];
|
|
26
|
+
export function propTrendTest(x, n, ...args) {
|
|
27
|
+
checkOptions(optionsIn(args), PROP_TREND_TEST_KEYS, "propTrendTest"); // generated: option-keys.mjs
|
|
28
|
+
const { score } = optionalArgs(["score"], args);
|
|
36
29
|
const xs = Array.from(x);
|
|
37
30
|
const ns = Array.from(n);
|
|
38
31
|
const k = xs.length;
|
|
@@ -93,6 +86,7 @@ export function propTrendTest(x, n, score) {
|
|
|
93
86
|
parameter: 1,
|
|
94
87
|
parameterName: "df",
|
|
95
88
|
pValue: pgamma1(statistic, 0.5, 2, false, false),
|
|
89
|
+
warnings: [],
|
|
96
90
|
};
|
|
97
91
|
}
|
|
98
92
|
/** Weighted sums of the regression of f on the scores s over the given rows: the total weight and the centred sums */
|
|
@@ -181,6 +175,7 @@ function tiedVariance(groupSizes, all) {
|
|
|
181
175
|
* @category Hypothesis tests
|
|
182
176
|
*/
|
|
183
177
|
export function jonckheereTest(x, g, options = {}) {
|
|
178
|
+
checkOptions(options, JONCKHEERE_TEST_KEYS, "jonckheereTest"); // generated: option-keys.mjs
|
|
184
179
|
const alternative = matchChoice(options.alternative, ["two.sided", "increasing", "decreasing"]);
|
|
185
180
|
const variant = options.variant ?? "DescTools";
|
|
186
181
|
if (variant !== "DescTools" && variant !== "clinfun")
|
|
@@ -266,5 +261,5 @@ export function jonckheereTest(x, g, options = {}) {
|
|
|
266
261
|
}
|
|
267
262
|
const cap = variant === "clinfun" ? 0.5 : 1;
|
|
268
263
|
const pValue = alternative === "increasing" ? upper : alternative === "decreasing" ? lower : Math.min(1, 2 * Math.min(upper, lower, cap)); // (DescTools can exceed 1)
|
|
269
|
-
return { method: "Jonckheere-Terpstra test", alternative, statistic: jt, statisticName: "JT", pValue, warnings };
|
|
264
|
+
return reported("jonckheereTest", { method: "Jonckheere-Terpstra test", alternative, statistic: jt, statisticName: "JT", pValue, warnings });
|
|
270
265
|
}
|
package/dist/htest/types.d.ts
CHANGED
|
@@ -54,6 +54,8 @@ export interface HTest {
|
|
|
54
54
|
nullValue?: number;
|
|
55
55
|
/** Name of `nullValue` (R's `names(null.value)`), e.g. `"difference in means"`. */
|
|
56
56
|
nullValueName?: string;
|
|
57
|
+
/** R's warnings, each once, in R's order (an empty array when there are none). */
|
|
58
|
+
warnings: string[];
|
|
57
59
|
}
|
|
58
60
|
/** Like R's match.arg, abbreviations ("two", "l", "g") are also accepted */
|
|
59
61
|
export declare function matchAlternative(a: string | undefined): Alternative;
|
package/dist/htest/varTest.js
CHANGED
|
@@ -10,8 +10,13 @@ import { pgamma1 } from "../distributions/gamma.js";
|
|
|
10
10
|
import { groupMoments, ldexpWide } from "../internal/summary.js";
|
|
11
11
|
import { kSampleData, samplesByLevel, twoGroupData } from "./testFormula.js";
|
|
12
12
|
import { checkConfLevelOpen, matchAlternative } from "./types.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 VAR_TEST_KEYS = ["ratio", "alternative", "confLevel"];
|
|
16
|
+
// Generated by `node scripts/option-keys.mjs --write` (end)
|
|
13
17
|
const MIN_NORMAL = 2 ** -1022;
|
|
14
18
|
export function varTest(x, y, options = {}) {
|
|
19
|
+
checkOptions(options, VAR_TEST_KEYS, "varTest"); // generated: option-keys.mjs
|
|
15
20
|
if (typeof x === "string") {
|
|
16
21
|
const d = twoGroupData(x, y);
|
|
17
22
|
return varTest(d.x, d.y, options);
|
|
@@ -81,6 +86,7 @@ export function varTest(x, y, options = {}) {
|
|
|
81
86
|
estimateNames: "ratio of variances",
|
|
82
87
|
nullValue: ratio,
|
|
83
88
|
nullValueName: "ratio of variances",
|
|
89
|
+
warnings: [],
|
|
84
90
|
};
|
|
85
91
|
}
|
|
86
92
|
export function bartlettTest(x, data) {
|
|
@@ -135,5 +141,6 @@ export function bartlettTest(x, data) {
|
|
|
135
141
|
parameter: df,
|
|
136
142
|
parameterName: "df",
|
|
137
143
|
pValue: pgamma1(statistic, df / 2, 2, false, false),
|
|
144
|
+
warnings: [],
|
|
138
145
|
};
|
|
139
146
|
}
|
package/dist/htest/wilcoxTest.js
CHANGED
|
@@ -23,10 +23,20 @@ import { pwilcox1, qwilcox1 } from "../distributions/wilcox.js";
|
|
|
23
23
|
import { pnorm, qnorm } from "../distributions/normal.js";
|
|
24
24
|
import { completePairs, dropNaN, mean, rank, tieCounts, } from "../internal/summary.js";
|
|
25
25
|
import { uniroot } from "../internal/uniroot.js";
|
|
26
|
+
import { reported, Warnings } from "../internal/warnings.js";
|
|
26
27
|
import { twoSampleData } from "./testFormula.js";
|
|
27
28
|
import { matchAlternative } from "./types.js";
|
|
28
29
|
import { maxOf, midpoint, minOf } from "../internal/extremes.js";
|
|
30
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
31
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
32
|
+
import { isOptionsObject } from "../internal/optionalArgs.js";
|
|
33
|
+
const WILCOX_TEST_KEYS = [
|
|
34
|
+
"alternative", "mu", "paired", "exact", "correct", "confInt", "confLevel", "tolRoot",
|
|
35
|
+
];
|
|
29
36
|
export function wilcoxTest(x, y, options = {}) {
|
|
37
|
+
if (typeof x !== "string" && isOptionsObject(y))
|
|
38
|
+
checkOptions(y, WILCOX_TEST_KEYS, "wilcoxTest"); // generated: option-keys.mjs
|
|
39
|
+
checkOptions(options, WILCOX_TEST_KEYS, "wilcoxTest"); // generated: option-keys.mjs
|
|
30
40
|
if (typeof x === "string") {
|
|
31
41
|
if (options.paired !== undefined)
|
|
32
42
|
throw new Error("cannot use 'paired' in formula method");
|
|
@@ -79,10 +89,9 @@ export function wilcoxTest(x, y, options = {}) {
|
|
|
79
89
|
confInt,
|
|
80
90
|
confLevel,
|
|
81
91
|
tolRoot,
|
|
92
|
+
warnings: new Warnings(),
|
|
82
93
|
};
|
|
83
|
-
return yv === undefined
|
|
84
|
-
? signedRank(xs, exact, paired, ctx)
|
|
85
|
-
: rankSum(xs, yv, exact, ctx);
|
|
94
|
+
return reported("wilcoxTest", yv === undefined ? signedRank(xs, exact, paired, ctx) : rankSum(xs, yv, exact, ctx));
|
|
86
95
|
}
|
|
87
96
|
/** Continuity correction amount (two-sided: 0.5 in the direction of the statistic's sign) */
|
|
88
97
|
function correction(z, alternative, correct) {
|
|
@@ -185,9 +194,25 @@ function signedRank(x0, exactOpt, paired, ctx) {
|
|
|
185
194
|
pValue,
|
|
186
195
|
nullValue: mu,
|
|
187
196
|
nullValueName: paired ? "location shift" : "location",
|
|
197
|
+
warnings: ctx.warnings.list,
|
|
188
198
|
};
|
|
189
|
-
|
|
199
|
+
// R's warnings of the exact method it could not use (after those of the interval)
|
|
200
|
+
const exactWarnings = () => {
|
|
201
|
+
if (exact && ties) {
|
|
202
|
+
ctx.warnings.add("cannot compute exact p-value with ties");
|
|
203
|
+
if (ctx.confInt)
|
|
204
|
+
ctx.warnings.add("cannot compute exact confidence interval with ties");
|
|
205
|
+
}
|
|
206
|
+
if (exact && zeroes) {
|
|
207
|
+
ctx.warnings.add("cannot compute exact p-value with zeroes");
|
|
208
|
+
if (ctx.confInt)
|
|
209
|
+
ctx.warnings.add("cannot compute exact confidence interval with zeroes");
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
if (!ctx.confInt) {
|
|
213
|
+
exactWarnings();
|
|
190
214
|
return result;
|
|
215
|
+
}
|
|
191
216
|
// The interval is on the original scale (add mu back to the data with zero differences removed)
|
|
192
217
|
// (with half units, the observations other than mu themselves)
|
|
193
218
|
// R also adds mu back. Where mu dwarfs the data, (x - mu) + mu loses the observations (rnorm(n, 0, 1e-200) with
|
|
@@ -206,6 +231,7 @@ function signedRank(x0, exactOpt, paired, ctx) {
|
|
|
206
231
|
const ci = useExact
|
|
207
232
|
? signedRankExactCI(xo, ctx)
|
|
208
233
|
: signedRankNormalCI(xo, ctx);
|
|
234
|
+
exactWarnings();
|
|
209
235
|
return { ...result, ...ci };
|
|
210
236
|
}
|
|
211
237
|
/** Interval with the given finite ends, the other end(s) open according to the alternative */
|
|
@@ -249,9 +275,12 @@ function signedRankExactCI(x, ctx) {
|
|
|
249
275
|
const q = exactRank((p) => qsignrank1(p, n, true, false), alternative, a);
|
|
250
276
|
const tail = psignrank1(q - 1, n, true, false);
|
|
251
277
|
const achieved = alternative === "two.sided" ? 2 * tail : tail;
|
|
278
|
+
const notAchievable = achieved - a > a / 2;
|
|
279
|
+
if (notAchievable)
|
|
280
|
+
ctx.warnings.add("requested conf.level not achievable");
|
|
252
281
|
return {
|
|
253
282
|
confInt: shape(alternative, walsh[q - 1], walsh[N - q]),
|
|
254
|
-
confLevel:
|
|
283
|
+
confLevel: notAchievable ? 1 - signif2(achieved) : confLevel,
|
|
255
284
|
estimate: sortedMedian(walsh),
|
|
256
285
|
estimateNames: "(pseudo)median",
|
|
257
286
|
};
|
|
@@ -268,6 +297,9 @@ function signedRankNormalCI(x, ctx) {
|
|
|
268
297
|
const lo = minOf(x);
|
|
269
298
|
const hi = maxOf(x);
|
|
270
299
|
if (!Number.isFinite(lo) || !Number.isFinite(hi) || n === 1 || lo === hi) {
|
|
300
|
+
// R's statistic of x - lo has no non-zero values when all observations are equal (n = 1 included)
|
|
301
|
+
if (Number.isFinite(lo) && lo === hi)
|
|
302
|
+
ctx.warnings.add("cannot compute confidence interval when all observations are zero or tied");
|
|
271
303
|
return noInterval(alternative, midpoint(lo, hi), "midrange");
|
|
272
304
|
}
|
|
273
305
|
const stat = (d, corr) => {
|
|
@@ -290,6 +322,8 @@ function signedRankNormalCI(x, ctx) {
|
|
|
290
322
|
a *= 2;
|
|
291
323
|
enlarged = true;
|
|
292
324
|
}
|
|
325
|
+
if (enlarged)
|
|
326
|
+
ctx.warnings.add("requested conf.level not achievable");
|
|
293
327
|
checkTolRoot(tolRoot);
|
|
294
328
|
const crossing = (z) => uniroot((d) => stat(d, correct) - z, lo, hi, { tol: tolRoot, fLower: sLo - z, fUpper: sHi - z });
|
|
295
329
|
let confInt;
|
|
@@ -424,10 +458,15 @@ function rankSum(x, y, exactOpt, ctx) {
|
|
|
424
458
|
pValue,
|
|
425
459
|
nullValue: mu,
|
|
426
460
|
nullValueName: "location shift",
|
|
461
|
+
warnings: ctx.warnings.list,
|
|
427
462
|
};
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
463
|
+
const ci = !ctx.confInt ? {} : useExact ? rankSumExact(() => rankSumExactCI(x, y, ctx)) : rankSumNormalCI(x, y, ctx);
|
|
464
|
+
// R's warnings of the exact method it could not use (after those of the interval)
|
|
465
|
+
if (exact && ties) {
|
|
466
|
+
ctx.warnings.add("cannot compute exact p-value with ties");
|
|
467
|
+
if (ctx.confInt)
|
|
468
|
+
ctx.warnings.add("cannot compute exact confidence intervals with ties");
|
|
469
|
+
}
|
|
431
470
|
return { ...result, ...ci };
|
|
432
471
|
}
|
|
433
472
|
/**
|
|
@@ -459,9 +498,12 @@ function rankSumExactCI(x, y, ctx) {
|
|
|
459
498
|
const q = exactRank((p) => qwilcox1(p, nx, ny, true, false), alternative, a);
|
|
460
499
|
const tail = pwilcox1(q - 1, nx, ny, true, false);
|
|
461
500
|
const achieved = alternative === "two.sided" ? 2 * tail : tail;
|
|
501
|
+
const notAchievable = achieved - a > a / 2;
|
|
502
|
+
if (notAchievable)
|
|
503
|
+
ctx.warnings.add("Requested conf.level not achievable");
|
|
462
504
|
return {
|
|
463
505
|
confInt: shape(alternative, diffs[q - 1], diffs[M - q]),
|
|
464
|
-
confLevel:
|
|
506
|
+
confLevel: notAchievable ? 1 - achieved : confLevel,
|
|
465
507
|
estimate: sortedMedian(diffs),
|
|
466
508
|
estimateNames: "difference in location",
|
|
467
509
|
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Throws a RangeError if `options` has an enumerable key that is not in `keys`. `undefined` and `null` options, and
|
|
3
|
+
* values that are not objects, are left to the function. A key whose value is `undefined` is still checked. `path` is
|
|
4
|
+
* the key of a nested options object (such as `"control"`), written before the unknown key in the message.
|
|
5
|
+
*/
|
|
6
|
+
export declare function checkOptions(options: unknown, keys: ReadonlySet<string> | readonly string[], fnName: string, path?: string): void;
|
|
7
|
+
/**
|
|
8
|
+
* The nested options object at `path` (keys joined by dots, as `"family.link"`) of `options`, or `undefined` where a
|
|
9
|
+
* step is not an object (a family given by name): what checkOptions is called with for a nested object.
|
|
10
|
+
*/
|
|
11
|
+
export declare function nestedOptions(options: unknown, path: string): unknown;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// The check that an options object has no key the function does not know: a misspelt key ({ lowertail: false })
|
|
2
|
+
// would otherwise be ignored and give a wrong result without a sign. The key lists are generated from the option
|
|
3
|
+
// types by scripts/option-keys.mjs.
|
|
4
|
+
/**
|
|
5
|
+
* Throws a RangeError if `options` has an enumerable key that is not in `keys`. `undefined` and `null` options, and
|
|
6
|
+
* values that are not objects, are left to the function. A key whose value is `undefined` is still checked. `path` is
|
|
7
|
+
* the key of a nested options object (such as `"control"`), written before the unknown key in the message.
|
|
8
|
+
*/
|
|
9
|
+
export function checkOptions(options, keys, fnName, path) {
|
|
10
|
+
if (typeof options !== "object" || options === null)
|
|
11
|
+
return;
|
|
12
|
+
for (const key in options) {
|
|
13
|
+
if (Array.isArray(keys) ? keys.includes(key) : keys.has(key))
|
|
14
|
+
continue;
|
|
15
|
+
const name = path === undefined ? key : `${path}.${key}`;
|
|
16
|
+
throw new RangeError(`unknown option '${name}' for ${fnName} (known: ${[...keys].join(", ")})`);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The nested options object at `path` (keys joined by dots, as `"family.link"`) of `options`, or `undefined` where a
|
|
21
|
+
* step is not an object (a family given by name): what checkOptions is called with for a nested object.
|
|
22
|
+
*/
|
|
23
|
+
export function nestedOptions(options, path) {
|
|
24
|
+
let v = options;
|
|
25
|
+
for (const key of path.split(".")) {
|
|
26
|
+
if (typeof v !== "object" || v === null)
|
|
27
|
+
return undefined;
|
|
28
|
+
v = v[key];
|
|
29
|
+
}
|
|
30
|
+
return v;
|
|
31
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** An options object: a plain object, not an array, a typed array or a function */
|
|
2
|
+
export declare function isOptionsObject(v: unknown): v is Record<string, unknown>;
|
|
3
|
+
/**
|
|
4
|
+
* The optional arguments from `args` (the arguments from the first optional one on), each named by `names` in
|
|
5
|
+
* order. An options object at a position ends the positional arguments; one may also follow all of them. A key given
|
|
6
|
+
* both by position and in the options is a RangeError. Positional `undefined` counts as not given. With `fnName`, a key
|
|
7
|
+
* of the options that is not in `names` is a RangeError (checkOptions), for a function whose options are not checked
|
|
8
|
+
* by the generated code (the function splinefun returns).
|
|
9
|
+
*/
|
|
10
|
+
export declare function optionalArgs<O extends object>(names: readonly (keyof O & string)[], args: readonly unknown[], fnName?: string): Partial<O>;
|
|
11
|
+
/** The first options object among `args` (the optional arguments of optionalArgs), for the check of its keys */
|
|
12
|
+
export declare function optionsIn(args: readonly unknown[]): Record<string, unknown> | undefined;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Optional arguments that a function takes either by position (R's order) or in an options object: the object in
|
|
2
|
+
// place of the first optional argument, or after the positional ones. A value given both ways is a RangeError.
|
|
3
|
+
import { checkOptions } from "./checkOptions.js";
|
|
4
|
+
/** An options object: a plain object, not an array, a typed array or a function */
|
|
5
|
+
export function isOptionsObject(v) {
|
|
6
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && !ArrayBuffer.isView(v);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The optional arguments from `args` (the arguments from the first optional one on), each named by `names` in
|
|
10
|
+
* order. An options object at a position ends the positional arguments; one may also follow all of them. A key given
|
|
11
|
+
* both by position and in the options is a RangeError. Positional `undefined` counts as not given. With `fnName`, a key
|
|
12
|
+
* of the options that is not in `names` is a RangeError (checkOptions), for a function whose options are not checked
|
|
13
|
+
* by the generated code (the function splinefun returns).
|
|
14
|
+
*/
|
|
15
|
+
export function optionalArgs(names, args, fnName) {
|
|
16
|
+
const out = {};
|
|
17
|
+
let options;
|
|
18
|
+
for (let i = 0; i < args.length; i++) {
|
|
19
|
+
const a = args[i];
|
|
20
|
+
if (i <= names.length && isOptionsObject(a)) {
|
|
21
|
+
options = a;
|
|
22
|
+
break;
|
|
23
|
+
}
|
|
24
|
+
if (i < names.length && a !== undefined)
|
|
25
|
+
out[names[i]] = a;
|
|
26
|
+
}
|
|
27
|
+
if (options !== undefined) {
|
|
28
|
+
if (fnName !== undefined)
|
|
29
|
+
checkOptions(options, names, fnName);
|
|
30
|
+
for (const name of names) {
|
|
31
|
+
if (options[name] === undefined)
|
|
32
|
+
continue;
|
|
33
|
+
if (Object.hasOwn(out, name))
|
|
34
|
+
throw new RangeError(`'${name}' is given both as an argument and in the options`);
|
|
35
|
+
out[name] = options[name];
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
/** The first options object among `args` (the optional arguments of optionalArgs), for the check of its keys */
|
|
41
|
+
export function optionsIn(args) {
|
|
42
|
+
for (const a of args)
|
|
43
|
+
if (isOptionsObject(a))
|
|
44
|
+
return a;
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A function that receives R's warnings: the warning's text and the name of the function that gave it, once per
|
|
3
|
+
* distinct warning of a call, after the call has computed its result.
|
|
4
|
+
*
|
|
5
|
+
* @category Hypothesis tests
|
|
6
|
+
*/
|
|
7
|
+
export type WarningHandler = (message: string, source: string) => void;
|
|
8
|
+
/**
|
|
9
|
+
* Sets the function that receives R's warnings, and returns the one it replaces (`null` when there was none). Not an
|
|
10
|
+
* R function. It plays the part of R's printing of warnings (and, by throwing, of `options(warn = 2)`).
|
|
11
|
+
*
|
|
12
|
+
* Every test, model and fit returns R's warnings in its result's `warnings` whatever the handler. With a handler
|
|
13
|
+
* set, each call of such a function (and `pivotLonger` without `onWarning`) also passes its warnings to the handler
|
|
14
|
+
* once it has computed its result: each distinct warning once, in order, with the name of the function called (a
|
|
15
|
+
* function that calls another, such as `pairwiseWilcoxTest`, passes the warnings once, under its own name). A fit's
|
|
16
|
+
* warnings are passed once, when it is fitted (`lm`, `glm`, `aov`, `lmer`, ...): a function given a fit or a table
|
|
17
|
+
* (`anova`, `aovSummary`, `Anova`, `glmSummary`, `etaSquared`, `lmerSummary`, ...) keeps them in its result's
|
|
18
|
+
* `warnings` but passes only the warnings it adds. An error thrown by the handler propagates to the caller. By default
|
|
19
|
+
* there is no handler and nothing is printed.
|
|
20
|
+
*
|
|
21
|
+
* To print the warnings as R does, set `(message, source) => console.warn(source + ": " + message)`. A handler that
|
|
22
|
+
* throws (`(message) => { throw new Error(message); }`) turns each warning into an error, as R's `options(warn = 2)`.
|
|
23
|
+
*
|
|
24
|
+
* The handler is kept on `globalThis`, so it is one setting for every copy of the library loaded on a page.
|
|
25
|
+
*
|
|
26
|
+
* @param handler The function that receives the warnings, or `null` to stop passing them.
|
|
27
|
+
* @returns The handler set before, or `null`.
|
|
28
|
+
* @throws TypeError if `handler` is neither a function nor `null`.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```ts
|
|
32
|
+
* const seen: string[] = [];
|
|
33
|
+
* const previous = setWarningHandler((message, source) => { seen.push(`${source}: ${message}`); });
|
|
34
|
+
* optim([1, 1], (p) => (p[0] - 2) ** 2 + (p[1] - 3) ** 2, { lower: [0, 0] }).warnings;
|
|
35
|
+
* // ["bounds can only be used with method L-BFGS-B (or Brent)"]
|
|
36
|
+
* setWarningHandler(previous);
|
|
37
|
+
* seen; // ["optim: bounds can only be used with method L-BFGS-B (or Brent)"]
|
|
38
|
+
* ```
|
|
39
|
+
*
|
|
40
|
+
* @category Hypothesis tests
|
|
41
|
+
*/
|
|
42
|
+
export declare function setWarningHandler(handler: WarningHandler | null): WarningHandler | null;
|
|
43
|
+
/**
|
|
44
|
+
* Passes a call's warnings to the handler (each distinct one once, in order), unless the call is inside another
|
|
45
|
+
* public function (`unreported`) or no handler is set. An error of the handler propagates.
|
|
46
|
+
*/
|
|
47
|
+
export declare function reportWarnings(source: string, warnings: readonly string[]): void;
|
|
48
|
+
/**
|
|
49
|
+
* Passes the warnings of a result to the handler (reportWarnings) and returns the result. The warnings of `given` (the
|
|
50
|
+
* fits or tables the function was given, whose warnings the result keeps) are left out: they were passed by the call
|
|
51
|
+
* that made them.
|
|
52
|
+
*/
|
|
53
|
+
export declare function reported<T extends {
|
|
54
|
+
readonly warnings?: readonly string[];
|
|
55
|
+
}>(source: string, result: T, ...given: readonly unknown[]): T;
|
|
56
|
+
/** Runs a call of a public function inside another one: its warnings are not passed to the handler */
|
|
57
|
+
export declare function unreported<T>(f: () => T): T;
|
|
58
|
+
/** Collects warnings in order of first appearance, each once (as the fixtures list R's warnings) */
|
|
59
|
+
export declare class Warnings {
|
|
60
|
+
readonly list: string[];
|
|
61
|
+
add(message: string): void;
|
|
62
|
+
}
|
|
63
|
+
/** Runs f with `sink` as the sink of `warn` */
|
|
64
|
+
export declare function withWarnings<T>(sink: Warnings, f: () => T): T;
|
|
65
|
+
/** Adds a warning to the sink set by withWarnings (none outside it) */
|
|
66
|
+
export declare function warn(message: string): void;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// R's warnings: the collection of a call's warnings (each once, in order) and the handler that receives them when a
|
|
2
|
+
// public function returns (setWarningHandler).
|
|
3
|
+
//
|
|
4
|
+
// Every function that returns warnings in its result passes them to the handler at its end: `return reported("glm",
|
|
5
|
+
// result)` (or `reportWarnings("pivotLonger", warnings)` where the result has no `warnings`). A public function that
|
|
6
|
+
// calls another one that reports (pairwiseWilcoxTest calling wilcoxTest, aovEz calling lm) makes that call through
|
|
7
|
+
// `unreported`, so that only the outer call passes its warnings, which include the inner ones it keeps. A function
|
|
8
|
+
// that takes a fit or a table (anova, glmSummary, etaSquared) keeps the given object's warnings in its result but
|
|
9
|
+
// passes only those it adds: `reported("anova", table, fit)`; the fit's were passed when it was fitted. Nothing runs
|
|
10
|
+
// at the top level (package.json has sideEffects: false).
|
|
11
|
+
/** The key of the handler on globalThis, shared by every copy of the library on a page */
|
|
12
|
+
const HANDLER_KEY = "@numero-uno-jpn/rstats.warningHandler";
|
|
13
|
+
/** The handler set by setWarningHandler (null when none) */
|
|
14
|
+
function currentHandler() {
|
|
15
|
+
return globalThis[Symbol.for(HANDLER_KEY)] ?? null;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Sets the function that receives R's warnings, and returns the one it replaces (`null` when there was none). Not an
|
|
19
|
+
* R function. It plays the part of R's printing of warnings (and, by throwing, of `options(warn = 2)`).
|
|
20
|
+
*
|
|
21
|
+
* Every test, model and fit returns R's warnings in its result's `warnings` whatever the handler. With a handler
|
|
22
|
+
* set, each call of such a function (and `pivotLonger` without `onWarning`) also passes its warnings to the handler
|
|
23
|
+
* once it has computed its result: each distinct warning once, in order, with the name of the function called (a
|
|
24
|
+
* function that calls another, such as `pairwiseWilcoxTest`, passes the warnings once, under its own name). A fit's
|
|
25
|
+
* warnings are passed once, when it is fitted (`lm`, `glm`, `aov`, `lmer`, ...): a function given a fit or a table
|
|
26
|
+
* (`anova`, `aovSummary`, `Anova`, `glmSummary`, `etaSquared`, `lmerSummary`, ...) keeps them in its result's
|
|
27
|
+
* `warnings` but passes only the warnings it adds. An error thrown by the handler propagates to the caller. By default
|
|
28
|
+
* there is no handler and nothing is printed.
|
|
29
|
+
*
|
|
30
|
+
* To print the warnings as R does, set `(message, source) => console.warn(source + ": " + message)`. A handler that
|
|
31
|
+
* throws (`(message) => { throw new Error(message); }`) turns each warning into an error, as R's `options(warn = 2)`.
|
|
32
|
+
*
|
|
33
|
+
* The handler is kept on `globalThis`, so it is one setting for every copy of the library loaded on a page.
|
|
34
|
+
*
|
|
35
|
+
* @param handler The function that receives the warnings, or `null` to stop passing them.
|
|
36
|
+
* @returns The handler set before, or `null`.
|
|
37
|
+
* @throws TypeError if `handler` is neither a function nor `null`.
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```ts
|
|
41
|
+
* const seen: string[] = [];
|
|
42
|
+
* const previous = setWarningHandler((message, source) => { seen.push(`${source}: ${message}`); });
|
|
43
|
+
* optim([1, 1], (p) => (p[0] - 2) ** 2 + (p[1] - 3) ** 2, { lower: [0, 0] }).warnings;
|
|
44
|
+
* // ["bounds can only be used with method L-BFGS-B (or Brent)"]
|
|
45
|
+
* setWarningHandler(previous);
|
|
46
|
+
* seen; // ["optim: bounds can only be used with method L-BFGS-B (or Brent)"]
|
|
47
|
+
* ```
|
|
48
|
+
*
|
|
49
|
+
* @category Hypothesis tests
|
|
50
|
+
*/
|
|
51
|
+
export function setWarningHandler(handler) {
|
|
52
|
+
if (handler !== null && typeof handler !== "function")
|
|
53
|
+
throw new TypeError("handler must be a function or null");
|
|
54
|
+
const previous = currentHandler();
|
|
55
|
+
globalThis[Symbol.for(HANDLER_KEY)] = handler;
|
|
56
|
+
return previous;
|
|
57
|
+
}
|
|
58
|
+
/** How many calls of public functions through `unreported` are running: their warnings go to the outer call only */
|
|
59
|
+
let depth = 0;
|
|
60
|
+
/**
|
|
61
|
+
* Passes a call's warnings to the handler (each distinct one once, in order), unless the call is inside another
|
|
62
|
+
* public function (`unreported`) or no handler is set. An error of the handler propagates.
|
|
63
|
+
*/
|
|
64
|
+
export function reportWarnings(source, warnings) {
|
|
65
|
+
if (depth > 0 || warnings.length === 0)
|
|
66
|
+
return;
|
|
67
|
+
const handler = currentHandler();
|
|
68
|
+
if (handler === null)
|
|
69
|
+
return;
|
|
70
|
+
for (const message of new Set(warnings))
|
|
71
|
+
handler(message, source);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Passes the warnings of a result to the handler (reportWarnings) and returns the result. The warnings of `given` (the
|
|
75
|
+
* fits or tables the function was given, whose warnings the result keeps) are left out: they were passed by the call
|
|
76
|
+
* that made them.
|
|
77
|
+
*/
|
|
78
|
+
export function reported(source, result, ...given) {
|
|
79
|
+
const old = new Set(given.flatMap((g) => warningsOf(g)));
|
|
80
|
+
reportWarnings(source, (result.warnings ?? []).filter((w) => !old.has(w)));
|
|
81
|
+
return result;
|
|
82
|
+
}
|
|
83
|
+
/** The `warnings` of an object given to a function (a fit or a table), or none */
|
|
84
|
+
function warningsOf(g) {
|
|
85
|
+
const w = typeof g === "object" && g !== null ? g.warnings : undefined;
|
|
86
|
+
return Array.isArray(w) ? w.filter((m) => typeof m === "string") : [];
|
|
87
|
+
}
|
|
88
|
+
/** Runs a call of a public function inside another one: its warnings are not passed to the handler */
|
|
89
|
+
export function unreported(f) {
|
|
90
|
+
depth++;
|
|
91
|
+
try {
|
|
92
|
+
return f();
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
depth--;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** Collects warnings in order of first appearance, each once (as the fixtures list R's warnings) */
|
|
99
|
+
export class Warnings {
|
|
100
|
+
list = [];
|
|
101
|
+
add(message) {
|
|
102
|
+
if (!this.list.includes(message))
|
|
103
|
+
this.list.push(message);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** The warnings sink of the link functions that warn ("NaNs produced"); set while a fit runs */
|
|
107
|
+
let currentWarnings;
|
|
108
|
+
/** Runs f with `sink` as the sink of `warn` */
|
|
109
|
+
export function withWarnings(sink, f) {
|
|
110
|
+
const saved = currentWarnings;
|
|
111
|
+
currentWarnings = sink;
|
|
112
|
+
try {
|
|
113
|
+
return f();
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
currentWarnings = saved;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** Adds a warning to the sink set by withWarnings (none outside it) */
|
|
120
|
+
export function warn(message) {
|
|
121
|
+
currentWarnings?.add(message);
|
|
122
|
+
}
|