@numero-uno-jpn/rstats 0.9.0 → 0.11.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.
Files changed (142) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.ja.md +64 -12
  3. package/README.md +63 -11
  4. package/THIRD_PARTY_NOTICES.md +7 -2
  5. package/dist/chunks/chunk-5WDJPHYY.js +2 -0
  6. package/dist/chunks/chunk-7GQMKH3Z.js +2 -0
  7. package/dist/chunks/chunk-AHHS6AC4.js +3 -0
  8. package/dist/chunks/chunk-ALM3VHFP.js +2 -0
  9. package/dist/chunks/{chunk-TOVTN5Y2.js → chunk-C5XTWMGB.js} +1 -1
  10. package/dist/chunks/chunk-CGBNKHNZ.js +2 -0
  11. package/dist/chunks/{chunk-LWUSYIQ4.js → chunk-EZAFN5CD.js} +1 -1
  12. package/dist/chunks/{chunk-H2AP6TCR.js → chunk-EZWBRCJL.js} +1 -1
  13. package/dist/chunks/chunk-F5EDJFEO.js +2 -0
  14. package/dist/chunks/{chunk-FC2TLHZC.js → chunk-JWBO5WVN.js} +2 -2
  15. package/dist/chunks/{chunk-LE7TBHNI.js → chunk-TOGXTCZO.js} +2 -2
  16. package/dist/chunks/chunk-VJ4BDBMU.js +3 -0
  17. package/dist/chunks/chunk-Y5CNQ266.js +2 -0
  18. package/dist/chunks/{chunk-BGVMSDVJ.js → chunk-Y5PYRAYP.js} +2 -2
  19. package/dist/chunks/{chunk-5K4PS7IV.js → chunk-YSWGDOWK.js} +2 -2
  20. package/dist/data/grouping.d.ts +79 -0
  21. package/dist/data/grouping.js +262 -0
  22. package/dist/descriptive/dataFrames.d.ts +110 -0
  23. package/dist/descriptive/dataFrames.js +392 -0
  24. package/dist/descriptive/factanal.d.ts +56 -0
  25. package/dist/descriptive/factanal.js +186 -0
  26. package/dist/descriptive/missing.d.ts +35 -0
  27. package/dist/descriptive/missing.js +50 -0
  28. package/dist/descriptive/omega.d.ts +56 -0
  29. package/dist/descriptive/omega.js +323 -0
  30. package/dist/descriptive/pivot.d.ts +89 -0
  31. package/dist/descriptive/pivot.js +343 -0
  32. package/dist/descriptive.js +2 -2
  33. package/dist/distributions/bvnorm.d.ts +15 -0
  34. package/dist/distributions/bvnorm.js +131 -0
  35. package/dist/distributions/nbeta.js +34 -1
  36. package/dist/distributions/nchisq.d.ts +10 -0
  37. package/dist/distributions/nchisq.js +46 -0
  38. package/dist/distributions.js +2 -2
  39. package/dist/entries/descriptive.d.ts +4 -0
  40. package/dist/entries/descriptive.js +4 -0
  41. package/dist/entries/distributions.d.ts +1 -0
  42. package/dist/entries/distributions.js +1 -0
  43. package/dist/entries/linalg.d.ts +2 -0
  44. package/dist/entries/linalg.js +2 -0
  45. package/dist/entries/numerics.d.ts +2 -0
  46. package/dist/entries/numerics.js +1 -0
  47. package/dist/entries/tests.d.ts +22 -1
  48. package/dist/entries/tests.js +19 -1
  49. package/dist/htest/agreement.d.ts +141 -0
  50. package/dist/htest/agreement.js +274 -0
  51. package/dist/htest/ansariTest.d.ts +12 -0
  52. package/dist/htest/ansariTest.js +5 -17
  53. package/dist/htest/aov.d.ts +19 -0
  54. package/dist/htest/aov.js +22 -15
  55. package/dist/htest/cor.d.ts +12 -0
  56. package/dist/htest/cor.js +9 -27
  57. package/dist/htest/core/simulate.d.ts +2 -0
  58. package/dist/htest/core/simulate.js +1 -1
  59. package/dist/htest/dunnett.d.ts +5 -0
  60. package/dist/htest/dunnett.js +89 -0
  61. package/dist/htest/effectSize.d.ts +112 -0
  62. package/dist/htest/effectSize.js +385 -0
  63. package/dist/htest/ksTest.d.ts +13 -0
  64. package/dist/htest/ksTest.js +5 -8
  65. package/dist/htest/leveneTest.d.ts +30 -0
  66. package/dist/htest/leveneTest.js +41 -0
  67. package/dist/htest/multipleComparisons.d.ts +147 -0
  68. package/dist/htest/multipleComparisons.js +369 -0
  69. package/dist/htest/normalityTests.d.ts +44 -0
  70. package/dist/htest/normalityTests.js +164 -0
  71. package/dist/htest/onewayTest.d.ts +14 -0
  72. package/dist/htest/onewayTest.js +5 -7
  73. package/dist/htest/polycor.d.ts +117 -0
  74. package/dist/htest/polycor.js +468 -0
  75. package/dist/htest/power.d.ts +132 -0
  76. package/dist/htest/power.js +227 -0
  77. package/dist/htest/pwr.d.ts +263 -0
  78. package/dist/htest/pwr.js +440 -0
  79. package/dist/htest/rankTests.d.ts +64 -0
  80. package/dist/htest/rankTests.js +27 -29
  81. package/dist/htest/tTest.d.ts +20 -0
  82. package/dist/htest/tTest.js +19 -24
  83. package/dist/htest/testFormula.d.ts +57 -0
  84. package/dist/htest/testFormula.js +171 -0
  85. package/dist/htest/trendTests.d.ts +57 -0
  86. package/dist/htest/trendTests.js +167 -0
  87. package/dist/htest/varTest.d.ts +23 -0
  88. package/dist/htest/varTest.js +11 -21
  89. package/dist/htest/wilcoxTest.d.ts +14 -0
  90. package/dist/htest/wilcoxTest.js +9 -24
  91. package/dist/linalg/eigen.d.ts +8 -0
  92. package/dist/linalg/eigen.js +5 -4
  93. package/dist/linalg/expm.d.ts +48 -0
  94. package/dist/linalg/expm.js +472 -0
  95. package/dist/linalg/ops.d.ts +13 -2
  96. package/dist/linalg/ops.js +20 -5
  97. package/dist/linalg/schur.d.ts +48 -0
  98. package/dist/linalg/schur.js +225 -0
  99. package/dist/linalg.js +2 -2
  100. package/dist/models/anovaSequential.d.ts +58 -0
  101. package/dist/models/anovaSequential.js +138 -0
  102. package/dist/models/aovEz.d.ts +64 -0
  103. package/dist/models/aovEz.js +332 -0
  104. package/dist/models/aovStrata.d.ts +32 -0
  105. package/dist/models/aovStrata.js +104 -0
  106. package/dist/models/carAnova.d.ts +30 -0
  107. package/dist/models/carAnova.js +121 -0
  108. package/dist/models/coxph.d.ts +101 -0
  109. package/dist/models/coxph.js +502 -0
  110. package/dist/models/ddLeastSquares.d.ts +30 -0
  111. package/dist/models/ddLeastSquares.js +90 -0
  112. package/dist/models/ddMatrix.d.ts +10 -0
  113. package/dist/models/ddMatrix.js +91 -0
  114. package/dist/models/formula.d.ts +83 -0
  115. package/dist/models/formula.js +333 -0
  116. package/dist/models/lm.d.ts +84 -3
  117. package/dist/models/lm.js +141 -44
  118. package/dist/models/mauchly.d.ts +48 -0
  119. package/dist/models/mauchly.js +123 -0
  120. package/dist/models/modelFrame.d.ts +40 -0
  121. package/dist/models/modelFrame.js +131 -0
  122. package/dist/models/modelMatrix.d.ts +88 -0
  123. package/dist/models/modelMatrix.js +170 -0
  124. package/dist/models/survival.d.ts +87 -0
  125. package/dist/models/survival.js +238 -0
  126. package/dist/numerics.js +2 -2
  127. package/dist/optim/lbfgsb.d.ts +20 -0
  128. package/dist/optim/lbfgsb.js +1240 -0
  129. package/dist/optim/optim.d.ts +85 -0
  130. package/dist/optim/optim.js +610 -0
  131. package/dist/rstats.js +19 -4
  132. package/dist/special.js +2 -2
  133. package/dist/tests.js +17 -4
  134. package/llms.txt +114 -0
  135. package/package.json +3 -2
  136. package/dist/chunks/chunk-24U4DKRY.js +0 -2
  137. package/dist/chunks/chunk-IVOBWYLV.js +0 -2
  138. package/dist/chunks/chunk-JLSTEMSN.js +0 -2
  139. package/dist/chunks/chunk-MF4VBCHQ.js +0 -2
  140. package/dist/chunks/chunk-MSAUU6PY.js +0 -2
  141. package/dist/chunks/chunk-YC4JWUKG.js +0 -2
  142. package/dist/chunks/chunk-ZRO446BP.js +0 -2
@@ -0,0 +1,343 @@
1
+ // Wide and long formats: tidyr's pivot_longer and pivot_wider.
2
+ //
3
+ // Written for rStats.js (no ported code) from oracle/pivot-behaviour.md. A data frame is the library's DataFrame (see
4
+ // dataFrames.ts): `null`, and `NaN` in a numeric column, is a missing value. Columns that are copied through (the
5
+ // columns not pivoted, the id columns) keep their kind (a Float64Array stays a Float64Array); a value column is a
6
+ // Float64Array when its sources are, else an array. Where tidyr would make a list column (a cell that several rows
7
+ // fill), pivotWider throws instead, since a data frame here cannot hold one. pivotLonger passes tidyr's warnings to
8
+ // its `onWarning` option.
9
+ import { formatR } from "../htest/core/simulate.js";
10
+ import { addColumn, compareValues, isMissing, pick, rowCount } from "./dataFrames.js";
11
+ const nameList = (v) => (typeof v === "string" ? [v] : [...v]);
12
+ function requireColumns(data, names) {
13
+ for (const n of names)
14
+ if (!Object.hasOwn(data, n))
15
+ throw new Error(`Column \`${n}\` doesn't exist.`);
16
+ }
17
+ /** The type of a column; `null` for an array of missing values only (which combines with any type) */
18
+ function columnType(name, col) {
19
+ if (col instanceof Float64Array)
20
+ return "double";
21
+ let type = null;
22
+ for (const v of col) {
23
+ if (v === null)
24
+ continue;
25
+ const t = typeof v === "number" ? "double" : typeof v === "string" ? "character" : "logical";
26
+ if (type !== null && t !== type)
27
+ throw new TypeError(`column '${name}' mixes ${type} and ${t} values`);
28
+ type = t;
29
+ }
30
+ return type;
31
+ }
32
+ /** The common type of the source columns of a value column: numbers absorb booleans, strings combine with neither */
33
+ function commonType(data, sources) {
34
+ let common = null;
35
+ for (const s of sources) {
36
+ const t = columnType(s, data[s]);
37
+ if (t === null)
38
+ continue;
39
+ if (common === null)
40
+ common = { type: t, column: s };
41
+ else if (common.type !== t) {
42
+ if (common.type === "character" || t === "character") {
43
+ throw new TypeError(`Can't combine \`${common.column}\` <${common.type}> and \`${s}\` <${t}>.`);
44
+ }
45
+ if (t === "double")
46
+ common = { type: t, column: s };
47
+ }
48
+ }
49
+ return common?.type ?? null;
50
+ }
51
+ /** The matches of a regular expression (as a string) in each name: its capture groups, `null` if it does not match */
52
+ function captures(names, pattern, count) {
53
+ const groups = new RegExp(`${pattern}|`).exec("").length - 1;
54
+ if (groups !== count)
55
+ throw new Error(`\`regex\` should define ${count} groups; ${groups} found.`);
56
+ const re = new RegExp(pattern);
57
+ return names.map((name) => {
58
+ const m = re.exec(name);
59
+ return Array.from({ length: count }, (_, j) => (m === null ? null : (m[j + 1] ?? null)));
60
+ });
61
+ }
62
+ /** The names split at the separator into `count` parts, and tidyr's warnings for names with more or fewer pieces */
63
+ function separated(names, sep, count, warnings) {
64
+ const re = new RegExp(sep, "g");
65
+ const extra = [];
66
+ const short = [];
67
+ const parts = names.map((name, i) => {
68
+ const pieces = [];
69
+ let start = 0;
70
+ for (const m of name.matchAll(re)) {
71
+ if (m[0].length === 0)
72
+ continue;
73
+ pieces.push(name.slice(start, m.index));
74
+ start = m.index + m[0].length;
75
+ }
76
+ pieces.push(name.slice(start));
77
+ if (pieces.length > count)
78
+ extra.push(i + 1);
79
+ if (pieces.length < count)
80
+ short.push(i + 1);
81
+ return Array.from({ length: count }, (_, j) => pieces[j] ?? null);
82
+ });
83
+ const rows = (r) => `${r.length} rows [${r.join(", ")}]`;
84
+ if (extra.length > 0)
85
+ warnings.push(`Expected ${count} pieces. Additional pieces discarded in ${rows(extra)}.`);
86
+ if (short.length > 0)
87
+ warnings.push(`Expected ${count} pieces. Missing pieces filled with \`NA\` in ${rows(short)}.`);
88
+ return parts;
89
+ }
90
+ /** The parts of each name, one per element of `namesTo` */
91
+ function nameParts(names, namesTo, options, warnings) {
92
+ const { namesSep, namesPattern } = options;
93
+ if (namesTo.length === 1) {
94
+ if (namesSep !== undefined)
95
+ throw new Error("`names_sep` can't be used with a length 1 `names_to`.");
96
+ if (namesPattern === undefined)
97
+ return names.map((n) => [n]);
98
+ const re = new RegExp(namesPattern);
99
+ return names.map((n) => [re.exec(n)?.[1] ?? null]);
100
+ }
101
+ if ((namesSep === undefined) === (namesPattern === undefined)) {
102
+ throw new Error("If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.");
103
+ }
104
+ return namesSep !== undefined
105
+ ? separated(names, namesSep, namesTo.length, warnings)
106
+ : captures(names, namesPattern, namesTo.length);
107
+ }
108
+ /**
109
+ * Reshapes a data frame from wide to long: the selected columns become rows. Equivalent to tidyr's `pivot_longer()`:
110
+ * the result has the columns not selected, a column per part of the selected names (`namesTo`), and the value
111
+ * column (`valuesTo`), or with `".value"` in `namesTo` one value column per value of that part. The values of the
112
+ * selected columns are combined into one type: numbers with booleans give numbers; strings with either are an error.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * const wide = { id: ["s1", "s2"], t1: [5.1, 4.8], t2: [6.3, 7.2] };
117
+ * pivotLonger(wide, { cols: ["t1", "t2"], namesTo: "time", valuesTo: "score" });
118
+ * // { id: ["s1", "s1", "s2", "s2"], time: ["t1", "t2", "t1", "t2"], score: [5.1, 6.3, 4.8, 7.2] }
119
+ * ```
120
+ */
121
+ export function pivotLonger(data, options) {
122
+ const n = rowCount(data);
123
+ const allNames = Object.keys(data);
124
+ const cols = typeof options.cols === "function" ? allNames.filter(options.cols) : [...new Set(options.cols)];
125
+ requireColumns(data, cols);
126
+ if (cols.length === 0)
127
+ throw new Error("`cols` must select at least one column.");
128
+ const namesTo = nameList(options.namesTo ?? "name");
129
+ const valuePosition = namesTo.indexOf(".value");
130
+ if (namesTo.lastIndexOf(".value") !== valuePosition)
131
+ throw new Error('`names_to` may contain ".value" only once');
132
+ const warnings = [];
133
+ const prefix = options.namesPrefix === undefined ? null : new RegExp(`^(?:${options.namesPrefix})`);
134
+ const stripped = cols.map((c) => (prefix === null ? c : c.replace(prefix, "")));
135
+ const parts = nameParts(stripped, namesTo, options, warnings);
136
+ // The keys (the parts other than ".value") and the value columns with their sources
137
+ const keys = [];
138
+ const values = [];
139
+ if (valuePosition < 0) {
140
+ keys.push(...parts);
141
+ values.push({ name: options.valuesTo ?? "value", sources: [...cols] });
142
+ }
143
+ else {
144
+ const keyIndex = new Map();
145
+ const valueIndex = new Map();
146
+ parts.forEach((p, c) => {
147
+ const key = p.filter((_, j) => j !== valuePosition);
148
+ const id = JSON.stringify(key);
149
+ let k = keyIndex.get(id);
150
+ if (k === undefined) {
151
+ k = keys.length;
152
+ keyIndex.set(id, k);
153
+ keys.push(key);
154
+ for (const v of values)
155
+ v.sources.push(null);
156
+ }
157
+ const name = p[valuePosition] ?? "NA";
158
+ let value = valueIndex.get(name);
159
+ if (value === undefined) {
160
+ value = { name, sources: keys.map(() => null) };
161
+ valueIndex.set(name, value);
162
+ values.push(value);
163
+ }
164
+ if (value.sources[k] !== null)
165
+ throw new Error(`the names give the value column '${name}' twice for one key`);
166
+ value.sources[k] = cols[c];
167
+ });
168
+ }
169
+ const types = values.map((v) => commonType(data, v.sources.filter((s) => s !== null)));
170
+ // Rows of the result: [input row, key]
171
+ let rows = [];
172
+ if (options.colsVary === "slowest") {
173
+ for (let k = 0; k < keys.length; k++)
174
+ for (let i = 0; i < n; i++)
175
+ rows.push([i, k]);
176
+ }
177
+ else {
178
+ for (let i = 0; i < n; i++)
179
+ for (let k = 0; k < keys.length; k++)
180
+ rows.push([i, k]);
181
+ }
182
+ const cellOf = (v, i, k) => {
183
+ const s = v.sources[k];
184
+ return s === null || s === undefined ? null : data[s][i];
185
+ };
186
+ if (options.valuesDropNa === true) {
187
+ rows = rows.filter(([i, k]) => values.some((v) => !isMissing(cellOf(v, i, k))));
188
+ }
189
+ const out = {};
190
+ const inputRows = rows.map(([i]) => i);
191
+ for (const name of allNames)
192
+ if (!cols.includes(name))
193
+ addColumn(out, name, pick(data[name], inputRows));
194
+ namesTo.forEach((to, j) => {
195
+ if (j === valuePosition)
196
+ return;
197
+ const transform = options.namesTransform?.[to];
198
+ const part = (k) => {
199
+ const p = keys[k][j < valuePosition || valuePosition < 0 ? j : j - 1];
200
+ return p === null || transform === undefined ? p : transform(p);
201
+ };
202
+ addColumn(out, to, rows.map(([, k]) => part(k)));
203
+ });
204
+ values.forEach((v, m) => {
205
+ const double = types[m] === "double";
206
+ if (double && v.sources.every((s) => s !== null && data[s] instanceof Float64Array)) {
207
+ addColumn(out, v.name, Float64Array.from(rows, ([i, k]) => cellOf(v, i, k)));
208
+ }
209
+ else {
210
+ const cells = rows.map(([i, k]) => {
211
+ const x = cellOf(v, i, k);
212
+ return double && typeof x === "boolean" ? Number(x) : x;
213
+ });
214
+ addColumn(out, v.name, cells);
215
+ }
216
+ });
217
+ if (options.onWarning !== undefined)
218
+ for (const w of new Set(warnings))
219
+ options.onWarning(w);
220
+ return out;
221
+ }
222
+ // ---- pivotWider ----
223
+ /** A value as an exact key (missing values are all one key) */
224
+ const keyOf = (v) => isMissing(v) ? "NA" : typeof v === "number" ? `n${v}` : typeof v === "string" ? `s${v}` : `b${String(v)}`;
225
+ /**
226
+ * The distinct combinations of the values of the columns, in order of first appearance: the combination of each row,
227
+ * and the first row of each combination
228
+ */
229
+ function combinations(cols, n) {
230
+ const index = new Map();
231
+ const firsts = [];
232
+ const codes = Array.from({ length: n }, (_, i) => {
233
+ const id = JSON.stringify(cols.map((c) => keyOf(c[i])));
234
+ let code = index.get(id);
235
+ if (code === undefined) {
236
+ code = firsts.length;
237
+ index.set(id, code);
238
+ firsts.push(i);
239
+ }
240
+ return code;
241
+ });
242
+ return { codes, firsts };
243
+ }
244
+ /** A value as part of a column name: numbers as R's as.character, booleans as TRUE and FALSE, missing as NA */
245
+ function labelText(v) {
246
+ if (isMissing(v))
247
+ return "NA";
248
+ if (typeof v === "number")
249
+ return Number.isFinite(v) ? formatR(v) : v > 0 ? "Inf" : "-Inf";
250
+ if (typeof v === "boolean")
251
+ return v ? "TRUE" : "FALSE";
252
+ return v;
253
+ }
254
+ /** An option given once for all value columns or by value column */
255
+ function perColumn(option, isSingle, name) {
256
+ if (option === undefined)
257
+ return undefined;
258
+ return isSingle(option) ? option : option[name];
259
+ }
260
+ /**
261
+ * Reshapes a data frame from long to wide: the values of `namesFrom` become columns, filled from `valuesFrom`.
262
+ * Equivalent to tidyr's `pivot_wider()`: one row per combination of the id columns (in order of first appearance),
263
+ * the new columns in order of first appearance of their names (unless `namesSort`). A cell that no row fills is
264
+ * `valuesFill` (default missing). A cell that several rows fill is an error unless `valuesFn` summarises the values
265
+ * (tidyr makes a list column there, which a data frame here cannot hold).
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * const long = { id: ["s1", "s1", "s2"], time: ["t1", "t2", "t1"], score: [5.1, 6.3, 4.8] };
270
+ * pivotWider(long, { namesFrom: "time", valuesFrom: "score" });
271
+ * // { id: ["s1", "s2"], t1: [5.1, 4.8], t2: [6.3, null] }
272
+ * ```
273
+ */
274
+ export function pivotWider(data, options = {}) {
275
+ const n = rowCount(data);
276
+ const namesFrom = nameList(options.namesFrom ?? "name");
277
+ const valuesFrom = nameList(options.valuesFrom ?? "value");
278
+ const idCols = options.idCols === undefined
279
+ ? Object.keys(data).filter((c) => !namesFrom.includes(c) && !valuesFrom.includes(c))
280
+ : nameList(options.idCols);
281
+ requireColumns(data, [...idCols, ...namesFrom, ...valuesFrom]);
282
+ const prefix = options.namesPrefix ?? "";
283
+ const sep = options.namesSep ?? "_";
284
+ const ids = combinations(idCols.map((c) => data[c]), n);
285
+ const labels = combinations(namesFrom.map((c) => data[c]), n);
286
+ // The name combinations in output order (positions in labels.firsts)
287
+ const nameOrder = labels.firsts.map((_, m) => m);
288
+ if (options.namesSort === true) {
289
+ nameOrder.sort((a, b) => {
290
+ for (const c of namesFrom) {
291
+ const d = compareValues(data[c][labels.firsts[a]], data[c][labels.firsts[b]]);
292
+ if (d !== 0)
293
+ return d;
294
+ }
295
+ return 0;
296
+ });
297
+ }
298
+ const nameText = labels.firsts.map((r) => prefix + namesFrom.map((c) => labelText(data[c][r])).join(sep));
299
+ // The rows of each cell (id combination, name combination), in data order
300
+ const nNames = labels.firsts.length;
301
+ const cellRows = Array.from({ length: ids.firsts.length * nNames }, () => []);
302
+ for (let i = 0; i < n; i++)
303
+ cellRows[ids.codes[i] * nNames + labels.codes[i]].push(i);
304
+ const isSummary = (o) => typeof o === "function";
305
+ const isFill = (o) => typeof o !== "object" || o === null;
306
+ const columnOf = (value, m) => {
307
+ const source = data[value];
308
+ const summary = perColumn(options.valuesFn, isSummary, value);
309
+ const fill = perColumn(options.valuesFill, isFill, value) ?? null;
310
+ const cells = ids.firsts.map((_, r) => {
311
+ const rows = cellRows[r * nNames + m];
312
+ if (rows.length === 0)
313
+ return fill;
314
+ if (summary !== undefined)
315
+ return summary(rows.map((i) => source[i]));
316
+ return source[rows[0]];
317
+ });
318
+ if (source instanceof Float64Array && cells.every((x) => x === null || typeof x === "number")) {
319
+ return Float64Array.from(cells, (x) => (x === null ? NaN : x));
320
+ }
321
+ return cells;
322
+ };
323
+ for (const value of valuesFrom) {
324
+ if (perColumn(options.valuesFn, isSummary, value) === undefined && cellRows.some((rows) => rows.length > 1)) {
325
+ throw new Error(`values from '${value}' are not uniquely identified; use valuesFn to summarise them`);
326
+ }
327
+ }
328
+ const out = {};
329
+ for (const c of idCols)
330
+ addColumn(out, c, pick(data[c], ids.firsts));
331
+ const columnName = (value, m) => valuesFrom.length === 1 ? nameText[m] : `${value}${sep}${nameText[m]}`;
332
+ if (options.namesVary === "slowest") {
333
+ for (const m of nameOrder)
334
+ for (const v of valuesFrom)
335
+ addColumn(out, columnName(v, m), columnOf(v, m));
336
+ }
337
+ else {
338
+ for (const v of valuesFrom)
339
+ for (const m of nameOrder)
340
+ addColumn(out, columnName(v, m), columnOf(v, m));
341
+ }
342
+ return out;
343
+ }
@@ -1,2 +1,2 @@
1
- /*! rStats.js 0.9.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{c as V}from"./chunks/chunk-MF4VBCHQ.js";import{d as T,e as O}from"./chunks/chunk-MSAUU6PY.js";import"./chunks/chunk-IVOBWYLV.js";import{a as q,b as Z,c as $,d as H,e as W,f as G,g as v,h as x,i as L,j as J,k as K,l as Y,m as ee,n as te,o as ne,p as re,q as oe,r as se,s as ie,t as ae,u as fe}from"./chunks/chunk-YC4JWUKG.js";import{a as j,b as ce,c as le,d as ue,e as me,f as he}from"./chunks/chunk-TOVTN5Y2.js";import{d as P}from"./chunks/chunk-BGVMSDVJ.js";import"./chunks/chunk-FC2TLHZC.js";import"./chunks/chunk-H2AP6TCR.js";var B=4*Number.EPSILON,de={4:[0,1],5:[.5,.5],6:[0,0],8:[1/3,1/3],9:[3/8,3/8]};function Ne(t,e,r){let s=t.length,f=i=>t[Math.min(Math.max(i,1),s)-1];if(r===7){let i=1+(s-1)*e,d=Math.floor(i),u=f(d),w=f(Math.ceil(i));if(i>d&&w!==u){let b=i-d;return(1-b)*u+b*w}return u}let o,n;if(r<=3){let i=r===3?s*e-.5:s*e;o=Math.floor(i*(1+B)),r===1?n=i>o?1:0:r===2?n=i>o?1:.5:n=i!==o||Math.abs(o%2)===1?1:0}else{let[i,d]=de[r],u=i+e*(s+1-i-d);o=Math.floor(u*(1+B)),n=u-o,Math.abs(n)<B&&(n=0)}let a=f(o),c=f(o+1);return n===1?c:n>0&&n<1&&a!==c?(1-n)*a+n*c:a}function F(t,e=[0,.25,.5,.75,1],r={}){let s=r.type??7;if(!(Number.isInteger(s)&&s>=1&&s<=9))throw new RangeError("'type' must be an integer in 1..9");let f=q(t,r.naRm);if(f===void 0)throw new RangeError("missing values and NaN's not allowed if 'na.rm' is FALSE");let o=f.sort((i,d)=>i-d),n=typeof e=="number"?[e]:Array.from(e),a=100*Number.EPSILON;if(n.some(i=>i<-a||i>1+a))throw new RangeError("'probs' outside [0,1]");let c=n.map(i=>Number.isNaN(i)||o.length===0?NaN:Ne(o,Math.min(Math.max(i,0),1),s));return typeof e=="number"?c[0]:c}function D(t,e={}){let[r,s]=F(t,[.25,.75],e);return s-r}function pe(t){let e=Array.from(t).filter(o=>!Number.isNaN(o)).sort((o,n)=>o-n),r=e.length;if(r===0)return[NaN,NaN,NaN,NaN,NaN];let s=Math.floor((r+3)/2)/2;return[1,s,(r+1)/2,r+1-s,r].map(o=>.5*(e[Math.floor(o)-1]+e[Math.ceil(o)-1]))}function ge(t,e={}){let r=q(t,e.naRm);if(r===void 0)return NaN;let s=e.center??x(r),f=e.constant??1.4826,o=e.low??!1,n=e.high??!1,a=r.map(i=>Math.abs(i-s)),c=a.length;if((o||n)&&c%2===0){if(o&&n)throw new RangeError("'low' and 'high' cannot be both TRUE");let i=c/2+(n?1:0),d=a.sort((u,w)=>u-w);return f*d[i-1]}return f*x(a)}function we(t,e){let r=t.length,s=new Array(r);if(e==="first"||e==="last"||e==="random"){let n=e==="random"?V(r):[],a=Array.from({length:r},(c,i)=>i);return a.sort((c,i)=>{let d=t[c]-t[i];return d!==0?d:e==="first"?c-i:e==="last"?i-c:n[c]-n[i]||c-i}),a.forEach((c,i)=>s[c]=i+1),s}let f=Array.from({length:r},(n,a)=>a).sort((n,a)=>t[n]-t[a]||n-a),o=0;for(;o<r;){let n=o;for(;n+1<r&&t[f[n+1]]===t[f[o]];)n++;let a=e==="average"?(o+n+2)/2:e==="min"?o+1:n+1;for(let c=o;c<=n;c++)s[f[c]]=a;o=n+1}return s}function I(t,e={}){let r=e.tiesMethod??"average";if(!["average","first","last","random","max","min"].includes(r))throw new RangeError(`invalid tiesMethod "${r}"`);let s=e.naLast??"last",f=Array.from(t),o=f.filter(u=>!Number.isNaN(u)),n=we(o,r),a=f.length-o.length,c=[],i=0,d=0;for(let u of f)Number.isNaN(u)?(d++,c.push(s==="keep"?NaN:s==="last"?o.length+d:d)):c.push(s==="first"?n[i++]+a:n[i++]);return c}var be=["pearson","kendall","spearman"],Me=["all.obs","complete.obs","pairwise.complete.obs","everything","na.or.complete"];function C(t,e,r,s){if(t===void 0)return r;if(e.includes(t))return t;let f=e.filter(o=>o.startsWith(t));if(t.length===0||f.length!==1)throw new RangeError(`invalid '${s}' argument`);return f[0]}function R(t){return t.length>0&&Array.isArray(t[0])}function Q(t){if(!R(t))return[Array.from(t)];let e=t[0].length;return Array.from({length:e},(r,s)=>t.map(f=>f[s]))}function U(t,e,r,s){let f=C(r.method,be,"pearson","method"),o=C(r.use,Me,"everything","use");if(e===void 0&&!R(t))throw new TypeError("supply both 'x' and 'y' or a matrix-like 'x'");let n=Q(t),a=e===void 0?n:Q(e),c=n[0]?.length??0;if(a.some(h=>h.length!==c))throw new RangeError("incompatible dimensions");let i=[...n,...a];if(o==="all.obs"&&i.some(h=>h.some(Number.isNaN)))throw new RangeError("missing observations in cov/cor");if(!s&&o==="pairwise.complete.obs"&&f!=="pearson")throw new RangeError("cannot handle 'pairwise.complete.obs'");let d;if((o==="complete.obs"||o==="na.or.complete")&&(d=Array.from({length:c},(h,m)=>i.every(l=>!Number.isNaN(l[m]))),!d.some(Boolean))){if(o==="complete.obs")throw new RangeError("no complete element pairs");return e===void 0||R(t)||R(e)?n.map(()=>a.map(()=>NaN)):NaN}let u=h=>{let m=d===void 0?h:h.filter((l,N)=>d[N]);return f==="spearman"&&o!=="pairwise.complete.obs"?I(m,{naLast:"keep"}):m},w=n.map(u),b=e===void 0?w:a.map(u),y=(h,m)=>{let l=h,N=m;if(o==="pairwise.complete.obs"){let p=h.map((k,M)=>!Number.isNaN(k)&&!Number.isNaN(m[M]));l=h.filter((k,M)=>p[M]),N=m.filter((k,M)=>p[M]),f==="spearman"&&(l=I(l),N=I(N))}else if(l.some(Number.isNaN)||N.some(Number.isNaN))return NaN;return f==="kendall"?s?O(l,N).tau:2*O(l,N).s:s?T(l,N)[0]:P(l,N)},E=w.map(h=>b.map(m=>y(h,m)));return s&&e===void 0&&o!=="pairwise.complete.obs"&&E.forEach((h,m)=>h[m]=1),e!==void 0&&!R(t)&&!R(e)?E[0][0]:E}function ke(t,e,r={}){return e!==void 0&&!Array.isArray(e)&&!ArrayBuffer.isView(e)?U(t,void 0,e,!1):U(t,e,r,!1)}function ye(t,e,r={}){return e!==void 0&&!Array.isArray(e)&&!ArrayBuffer.isView(e)?U(t,void 0,e,!0):U(t,e,r,!0)}function z(t,e={}){let r=Array.from(t).filter(Number.isFinite);if(r.length===0)return[];let s=e.n??5,f=e.minN??Math.floor(s/3),o=e.shrinkSml??.75,n=e.highUBias??1.5,a=e.u5Bias??.5+1.5*n,c=1/0,i=-1/0;for(let g of r)g<c&&(c=g),g>i&&(i=g);let d=i-c,u,w;if(d===0&&i===0)u=1,w=!0;else{u=Math.max(Math.abs(c),Math.abs(i));let A=(1+(a>=1.5*n+.5?1/(1+n):1.5/(1+a)))*Math.max(1,s)*Number.EPSILON;w=d<u*A*3}w?(u>10&&(u=9+u/10),u*=o,f>1&&(u/=f)):(u=s>1?d/s:d,d===1/0&&s>=2&&(u=i/s-c/s));let b=2**-20*Ae;u<b?u=b:u>Number.MAX_VALUE/1.25&&(u=Number.MAX_VALUE/1.25);let y=10**Math.floor(Math.log10(u)),E=[[2*y,n],[5*y,a],[10*y,n]],h=y;for(let[g,A]of E)if(g-u<A*(u-h))h=g;else break;let m=1e-10,l=Math.floor(c/h+m);for(;l*h>c+m*h;)l--;for(;!Number.isFinite(l*h);)l++;let N=Math.ceil(i/h-m);for(;N*h<i-m*h;)N++;for(;!Number.isFinite(N*h);)N--;let p=Math.trunc(.5+N-l);if(p<f){let g=f-p,A=Math.floor(g/2),_=g%2;c===0&&l===0&&i!==0?N+=g:i===0&&N===0&&c!==0?l-=g:l>=0?(N+=A,l-=A+_):(l-=A,N+=A+_),p=f}let k=l*h<c?l*h:c,M=N*h>i?N*h:i;if(p<=0)return[k];let S;if(Number.isFinite(M-k))S=j(k,M,p+1);else{let g=M/p-k/p;S=Array.from({length:p+1},(A,_)=>k+_*g),S[p]=M}let X=M/p-k/p;return S.map(g=>Math.abs(g)<1e-14*X?0:g)}var Ae=22250738585072014e-324;function Ee(t){return t===0||!Number.isFinite(t)?t:Number(t.toPrecision(5))}function xe(t,e){let r=t.length,[s,f]=L(t),o=f-s;switch(e.toLowerCase()){case"sturges":return Math.ceil(Math.log2(r)+1);case"scott":{let n=3.5*v(t)*r**-.3333333333333333;return n>0?Math.max(1,Math.ceil(o/n)):1}case"fd":case"freedman-diaconis":{let n=t.map(Ee),a=2*D(n);for(let c=1/8;a===0&&c>=1/512;c/=2){let[i,d]=F(n,[c,1-c]);a=(d-i)/(1-2*c)}return a===0&&(a=3.5*v(t)),a>0?Math.ceil(o/a*r**(1/3)):1}default:throw new RangeError("unknown 'breaks' algorithm")}}function Re(t,e){let r=t.slice(1).map((s,f)=>s-t[f]);return t.length>5?x(r):t.length<=3?e:Math.min(...r.filter(s=>s>0))}function Le(t,e={}){let r=Array.from(t).filter(Number.isFinite),s=r.length,f=e.right??!0,o=e.includeLowest??!0,n=e.breaks??"Sturges",a;if(typeof n!="string"&&typeof n!="number"&&n.length>1)a=[...n].sort((m,l)=>m-l);else{o=!0;let m=typeof n=="string"?xe(r,n):typeof n=="number"?n:n[0];if(!Number.isFinite(m)||m<1)throw new RangeError("invalid number of 'breaks'");m=Math.min(m,1e6);let[l,N]=L(r);a=z([l,N],{n:m,minN:1});for(let p=1;p<a.length;p++)if(!(a[p]-a[p-1]>0))throw new RangeError("'breaks' are not strictly increasing")}let c=a.length,[i,d]=s>0?L(r):[0,0],u=1e-7*Re(a,d-i),w=a.map((m,l)=>f?l===0&&o?m-u:m+u:l<c-1?m-u:o?m+u:m-u),b=new Array(Math.max(0,c-1)).fill(0),y=0;for(let m of r){let l=Ie(m,w,f,o);l>=0&&(b[l]++,y++)}if(y<s)throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");let E=b.map((m,l)=>m/(s*(a[l+1]-a[l]))),h=b.map((m,l)=>.5*(a[l+1]+a[l]));return{breaks:a,counts:b,density:E,mids:h}}function Ie(t,e,r,s){let f=e.length-1;if(f<1)return-1;if(r){if(t===e[0]&&s)return 0;if(!(t>e[0]&&t<=e[f]))return-1;let a=1,c=f;for(;a<c;){let i=a+c>>1;t<=e[i]?c=i:a=i+1}return a-1}if(t===e[f]&&s)return f-1;if(!(t>=e[0]&&t<e[f]))return-1;let o=0,n=f-1;for(;o<n;){let a=o+n+1>>1;e[a]<=t?o=a:n=a-1}return o}function Se(t){let e=Array.from(t).filter(s=>!Number.isNaN(s)).sort((s,f)=>s-f),r=e.length;if(r<1)throw new RangeError("'x' must have 1 or more non-missing values");return s=>{if(Number.isNaN(s))return NaN;let f=0,o=r;for(;f<o;){let n=f+o>>1;e[n]<=s?f=n+1:o=n}return f/r}}export{D as IQR,ye as cor,ke as cov,Y as cummax,ee as cummin,K as cumprod,J as cumsum,me as cut,ae as cv,te as diff,Se as ecdf,he as findInterval,pe as fivenum,oe as geometricMean,Le as hist,re as kurtosis,ge as mad,H as mean,ie as meanAD,x as median,se as modes,z as pretty,$ as prod,F as quantile,L as range,I as rank,fe as scale,v as sd,ne as skewness,Z as sum,le as table,ce as tabulate,ue as unique,G as variance,W as weightedMean};
1
+ /*! rStats.js 0.11.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 J,e as S,q as fe,r as ue,s as me}from"./chunks/chunk-AHHS6AC4.js";import"./chunks/chunk-Y5CNQ266.js";import{A as ke,B as Re,C as Fe,D as je,E as Se,F as Te,a as q,b as T,c as z,d as k,e as G,f as he,g as pe,j as ge,k as ye,l as V,m as de,n as we,o as be,p as Ne,q as Ee,r as _,s as R,t as j,u as Ae,v as xe,w as Me,x as $e,y as ve,z as Oe}from"./chunks/chunk-CGBNKHNZ.js";import{a as X}from"./chunks/chunk-ALM3VHFP.js";import{a as H,b as _e,c as Ce,d as Ie,e as Le,f as Pe}from"./chunks/chunk-C5XTWMGB.js";import"./chunks/chunk-5WDJPHYY.js";import"./chunks/chunk-Y5PYRAYP.js";import"./chunks/chunk-JWBO5WVN.js";import"./chunks/chunk-EZWBRCJL.js";var B=4*Number.EPSILON,Ue={4:[0,1],5:[.5,.5],6:[0,0],8:[1/3,1/3],9:[3/8,3/8]};function qe(e,n,t){let r=e.length,o=a=>e[Math.min(Math.max(a,1),r)-1];if(t===7){let a=1+(r-1)*n,g=Math.floor(a),m=o(g),y=o(Math.ceil(a));if(a>g&&y!==m){let b=a-g;return(1-b)*m+b*y}return m}let i,l;if(t<=3){let a=t===3?r*n-.5:r*n;i=Math.floor(a*(1+B)),t===1?l=a>i?1:0:t===2?l=a>i?1:.5:l=a!==i||Math.abs(i%2)===1?1:0}else{let[a,g]=Ue[t],m=a+n*(r+1-a-g);i=Math.floor(m*(1+B)),l=m-i,Math.abs(l)<B&&(l=0)}let s=o(i),u=o(i+1);return l===1?u:l>0&&l<1&&s!==u?(1-l)*s+l*u:s}function C(e,n=[0,.25,.5,.75,1],t={}){let r=t.type??7;if(!(Number.isInteger(r)&&r>=1&&r<=9))throw new RangeError("'type' must be an integer in 1..9");let o=V(e,t.naRm);if(o===void 0)throw new RangeError("missing values and NaN's not allowed if 'na.rm' is FALSE");let i=o.sort((a,g)=>a-g),l=typeof n=="number"?[n]:Array.from(n),s=100*Number.EPSILON;if(l.some(a=>a<-s||a>1+s))throw new RangeError("'probs' outside [0,1]");let u=l.map(a=>Number.isNaN(a)||i.length===0?NaN:qe(i,Math.min(Math.max(a,0),1),r));return typeof n=="number"?u[0]:u}function W(e,n={}){let[t,r]=C(e,[.25,.75],n);return r-t}function ze(e){let n=Array.from(e).filter(i=>!Number.isNaN(i)).sort((i,l)=>i-l),t=n.length;if(t===0)return[NaN,NaN,NaN,NaN,NaN];let r=Math.floor((t+3)/2)/2;return[1,r,(t+1)/2,t+1-r,t].map(i=>.5*(n[Math.floor(i)-1]+n[Math.ceil(i)-1]))}function Ve(e,n={}){let t=V(e,n.naRm);if(t===void 0)return NaN;let r=n.center??R(t),o=n.constant??1.4826,i=n.low??!1,l=n.high??!1,s=t.map(a=>Math.abs(a-r)),u=s.length;if((i||l)&&u%2===0){if(i&&l)throw new RangeError("'low' and 'high' cannot be both TRUE");let a=u/2+(l?1:0),g=s.sort((m,y)=>m-y);return o*g[a-1]}return o*R(s)}var K=e=>e===null||typeof e=="number"&&Number.isNaN(e),Y=e=>Array.isArray(e)||ArrayBuffer.isView(e);function Be(e){if(Y(e))return{columns:[e],rows:e.length};if(typeof e!="object"||e===null)throw new TypeError("the arguments must be arrays or data frames");let n=Object.values(e),t=n[0]?.length??0;if(n.some(r=>r.length!==t))throw new RangeError("not all arguments have the same length");return{columns:n,rows:t}}function ee(...e){if(e.length===0)throw new RangeError("no input has determined the number of cases");let n=e.map(Be),t=n[0].rows;if(n.some(o=>o.rows!==t))throw new RangeError("not all arguments have the same length");let r=n.flatMap(o=>o.columns);return Array.from({length:t},(o,i)=>r.every(l=>!K(l[i])))}function We(e){if(Y(e))return Array.from(e).filter(r=>!K(r));let n=ee(e),t={};for(let[r,o]of Object.entries(e)){let i=Array.from(o).filter((l,s)=>n[s]);t[r]=o instanceof Float64Array?Float64Array.from(i):i}return t}function ne(e,n={}){let t=Array.from(e).filter(Number.isFinite);if(t.length===0)return[];let r=n.n??5,o=n.minN??Math.floor(r/3),i=n.shrinkSml??.75,l=n.highUBias??1.5,s=n.u5Bias??.5+1.5*l,u=1/0,a=-1/0;for(let w of t)w<u&&(u=w),w>a&&(a=w);let g=a-u,m,y;if(g===0&&a===0)m=1,y=!0;else{m=Math.max(Math.abs(u),Math.abs(a));let M=(1+(s>=1.5*l+.5?1/(1+l):1.5/(1+s)))*Math.max(1,r)*Number.EPSILON;y=g<m*M*3}y?(m>10&&(m=9+m/10),m*=i,o>1&&(m/=o)):(m=r>1?g/r:g,g===1/0&&r>=2&&(m=a/r-u/r));let b=2**-20*Ze;m<b?m=b:m>Number.MAX_VALUE/1.25&&(m=Number.MAX_VALUE/1.25);let d=10**Math.floor(Math.log10(m)),x=[[2*d,l],[5*d,s],[10*d,l]],N=d;for(let[w,M]of x)if(w-m<M*(m-N))N=w;else break;let h=1e-10,f=Math.floor(u/N+h);for(;f*N>u+h*N;)f--;for(;!Number.isFinite(f*N);)f++;let c=Math.ceil(a/N-h);for(;c*N<a-h*N;)c++;for(;!Number.isFinite(c*N);)c--;let p=Math.trunc(.5+c-f);if(p<o){let w=o-p,M=Math.floor(w/2),O=w%2;u===0&&f===0&&a!==0?c+=w:a===0&&c===0&&u!==0?f-=w:f>=0?(c+=M,f-=M+O):(f-=M,c+=M+O),p=o}let E=f*N<u?f*N:u,A=c*N>a?c*N:a;if(p<=0)return[E];let $;if(Number.isFinite(A-E))$=H(E,A,p+1);else{let w=A/p-E/p;$=Array.from({length:p+1},(M,O)=>E+O*w),$[p]=A}let v=A/p-E/p;return $.map(w=>Math.abs(w)<1e-14*v?0:w)}var Ze=22250738585072014e-324;function De(e){return e===0||!Number.isFinite(e)?e:Number(e.toPrecision(5))}function Qe(e,n){let t=e.length,[r,o]=j(e),i=o-r;switch(n.toLowerCase()){case"sturges":return Math.ceil(Math.log2(t)+1);case"scott":{let l=3.5*_(e)*t**-.3333333333333333;return l>0?Math.max(1,Math.ceil(i/l)):1}case"fd":case"freedman-diaconis":{let l=e.map(De),s=2*W(l);for(let u=1/8;s===0&&u>=1/512;u/=2){let[a,g]=C(l,[u,1-u]);s=(g-a)/(1-2*u)}return s===0&&(s=3.5*_(e)),s>0?Math.ceil(i/s*t**(1/3)):1}default:throw new RangeError("unknown 'breaks' algorithm")}}function Je(e,n){let t=e.slice(1).map((r,o)=>r-e[o]);return e.length>5?R(t):e.length<=3?n:Math.min(...t.filter(r=>r>0))}function Xe(e,n={}){let t=Array.from(e).filter(Number.isFinite),r=t.length,o=n.right??!0,i=n.includeLowest??!0,l=n.breaks??"Sturges",s;if(typeof l!="string"&&typeof l!="number"&&l.length>1)s=[...l].sort((h,f)=>h-f);else{i=!0;let h=typeof l=="string"?Qe(t,l):typeof l=="number"?l:l[0];if(!Number.isFinite(h)||h<1)throw new RangeError("invalid number of 'breaks'");h=Math.min(h,1e6);let[f,c]=j(t);s=ne([f,c],{n:h,minN:1});for(let p=1;p<s.length;p++)if(!(s[p]-s[p-1]>0))throw new RangeError("'breaks' are not strictly increasing")}let u=s.length,[a,g]=r>0?j(t):[0,0],m=1e-7*Je(s,g-a),y=s.map((h,f)=>o?f===0&&i?h-m:h+m:f<u-1?h-m:i?h+m:h-m),b=new Array(Math.max(0,u-1)).fill(0),d=0;for(let h of t){let f=Ge(h,y,o,i);f>=0&&(b[f]++,d++)}if(d<r)throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");let x=b.map((h,f)=>h/(r*(s[f+1]-s[f]))),N=b.map((h,f)=>.5*(s[f+1]+s[f]));return{breaks:s,counts:b,density:x,mids:N}}function Ge(e,n,t,r){let o=n.length-1;if(o<1)return-1;if(t){if(e===n[0]&&r)return 0;if(!(e>n[0]&&e<=n[o]))return-1;let s=1,u=o;for(;s<u;){let a=s+u>>1;e<=n[a]?u=a:s=a+1}return s-1}if(e===n[o]&&r)return o-1;if(!(e>=n[0]&&e<n[o]))return-1;let i=0,l=o-1;for(;i<l;){let s=i+l+1>>1;n[s]<=e?i=s:l=s-1}return i}function He(e){let n=Array.from(e).filter(r=>!Number.isNaN(r)).sort((r,o)=>r-o),t=n.length;if(t<1)throw new RangeError("'x' must have 1 or more non-missing values");return r=>{if(Number.isNaN(r))return NaN;let o=0,i=t;for(;o<i;){let l=o+i>>1;n[l]<=r?o=l+1:i=l}return o/t}}var I=e=>e===null||typeof e=="number"&&Number.isNaN(e),Ke=(e,n)=>typeof e=="number"?e-n:typeof e=="string"?X(e,n):Number(e)-Number(n),Ye=e=>typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="string"?e:Number.isFinite(e)?S(e):e>0?"Inf":"-Inf";function en(e,n){let t=Array.from(n,s=>s===0?0:s),r=new Set(t.filter(s=>!I(s)).map(s=>typeof s));if(r.size>1)throw new TypeError(`${e} mixes ${[...r].join(" and ")} labels`);let o=[...r][0];if(o!==void 0&&o!=="number"&&o!=="string"&&o!=="boolean")throw new TypeError(`${e} has labels of an unsupported type`);let i=[...new Set(t.filter(s=>!I(s)))].sort(Ke),l=new Map(i.map((s,u)=>[s,u]));return{levels:i,codes:t.map(s=>I(s)?-1:l.get(s))}}var F=e=>Array.isArray(e)||e instanceof Float64Array;function se(e){if(e instanceof Float64Array)return[e];if(!Array.isArray(e))throw new TypeError("the group labels must be an array or an array of arrays");if(e.length>0&&e.every(F))return[...e];if(e.some(F))throw new TypeError("the group labels must be an array or an array of arrays");return[e]}function Z(e,n,t){e.forEach((l,s)=>{if(l.length!==t)throw new RangeError(`${n[s]} must have one label per row (${t}), not ${l.length}`)});let r=e.map((l,s)=>en(n[s],l)),o=r.reduce((l,s)=>l*s.levels.length,1),i=new Array(t);for(let l=0;l<t;l++){let s=0,u=1;for(let a of r){let g=a.codes[l];if(g<0){s=-1;break}s+=g*u,u*=a.levels.length}i[l]=s}return{factors:r,size:o,cells:i}}function D(e){let n=Array.from({length:e.size},()=>[]);return e.cells.forEach((t,r)=>{t>=0&&n[t].push(r)}),n}function le(e,n){return e.factors.map(t=>{let r=t.levels.length,o=t.levels[n%r];return n=Math.floor(n/r),o})}var ae=(e,n)=>Array.from({length:e},(t,r)=>e===1?n:`${n}[${r}]`);function nn(e,n,t){let r=Array.from(e),o=se(n),i=Z(o,ae(o.length,"index"),r.length),l=D(i).map(a=>a.length===0?null:{value:t(a.map(g=>r[g]))}),u=l.every(a=>a===null||typeof a.value=="number")?l.map(a=>a===null?NaN:a.value):l.map(a=>a===null?null:a.value);return{dim:i.factors.map(a=>a.levels.length),dimnames:i.factors.map(a=>[...a.levels]),values:u}}function tn(e,n){let t={};for(let[r,o]of Object.entries(e))t[r]=o instanceof Float64Array?Float64Array.from(n,i=>o[i]):n.map(i=>o[i]);return t}function rn(e){let t=Object.values(e)[0]?.length??0;for(let[r,o]of Object.entries(e)){if(!F(o))throw new TypeError(`column '${r}' must be an array`);if(o.length!==t)throw new RangeError(`the columns of the data frame have different lengths (found for '${r}')`)}return t}function on(e,n,t={}){let r=t.sep??".",o=se(n),i=!F(e);if(i&&(typeof e!="object"||e===null))throw new TypeError("x must be an array or a data frame");let l=i?rn(e):e.length,s=Z(o,ae(o.length,"f"),l),u=i?[]:Array.from(e),a=new Map;return D(s).forEach((g,m)=>{if(g.length===0&&(t.drop||s.factors.length===1))return;let y=le(s,m).map(Ye).join(r);a.set(y,i?tn(e,g):g.map(b=>u[b]))}),a}function te(e,n){if(n===void 0)throw new Error(`object '${e}' not found`);if(!F(n))throw new TypeError(`column '${e}' must be an array`);return Array.from(n,t=>{if(t===null)return NaN;if(typeof t!="number")throw new TypeError(`column '${e}' to summarise must be numeric`);return t})}function re(e,n){let t=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0;if(t===void 0)throw new Error(`object '${n}' not found`);if(!F(t))throw new TypeError(`column '${n}' must be an array`);return t}function L(e,n){if(e.type==="var")n.push(e.name);else if(e.type==="binary"&&e.op==="+")L(e.left,n),L(e.right,n);else if(e.type==="paren")L(e.arg,n);else throw new SyntaxError("invalid formula: the right-hand side must be grouping variables joined by '+'");return n}function sn(e,n){if(typeof e!="string")throw new TypeError("the formula must be a string");let t=e.indexOf("~");if(t<0)throw new SyntaxError("invalid formula: missing '~'");let r=e.slice(0,t).trim(),o=L(J(`~ ${e.slice(t+1)}`).rhs,[]),i=/^[A-Za-z.][A-Za-z0-9._]*$/,l;if(r===".")l=n.filter(s=>!o.includes(s));else{let s=/^cbind\s*\((.*)\)$/s.exec(r);if(l=s===null?[r]:s[1].split(",").map(u=>u.trim()),l.some(u=>!i.test(u)||u==="."))throw new SyntaxError("invalid formula: the left-hand side must be a variable, cbind(...) of variables or '.'")}return{values:l,groups:o}}function oe(e,n,t,r,o,i){let l=r[0]?.length??0;e.forEach((m,y)=>{if(n[y].length!==l)throw new RangeError(`variable lengths differ (found for '${m}')`)});let s=Z(r,t,l),u=D(s).map((m,y)=>({cell:y,rows:m.filter(o)})).filter(m=>m.rows.length>0),a={},g=u.map(m=>le(s,m.cell));return t.forEach((m,y)=>{a[m]=g.map(b=>b[y])}),e.forEach((m,y)=>{let b=n[y],x=u.map(h=>i(h.rows.map(f=>b[f]))).map(h=>{if(typeof h=="number")return{names:void 0,values:[h]};if(Array.isArray(h))return{names:void 0,values:[...h]};let f=h;return{names:Object.keys(f),values:Object.values(f)}}),N=x[0]?.values.length??1;if(x.some(h=>h.values.length!==N))throw new RangeError("fun must return values of the same length for every group");if(N===1&&x[0]?.names===void 0){a[m]=x.map(h=>h.values[0]);return}for(let h=0;h<N;h++){let f=x[0].names?.[h]??String(h+1);a[`${m}.${f}`]=x.map(c=>c.values[h])}}),a}function ln(e,n,t){if(typeof n!="object"||n===null)throw new TypeError("the data must be an object of columns");if(typeof e=="string"){let s=n,{values:u,groups:a}=sn(e,Object.keys(s)),g=d=>Object.prototype.hasOwnProperty.call(s,d),m=u.map(d=>te(d,g(d)?s[d]:void 0)),y=a.map(d=>re(s,d));return oe(u,m,a,y,d=>m.every(x=>!Number.isNaN(x[d]))&&y.every(x=>!I(x[d])),t)}if(typeof e!="object"||e===null)throw new TypeError("x must be a data frame");let r=Object.keys(e),o=r.map(s=>te(s,e[s])),i=Object.keys(n);if(i.length===0)throw new RangeError("'by' must name at least one grouping column");let l=i.map(s=>re(n,s));return oe(r,o,i,l,()=>!0,t)}var P=e=>typeof e=="string"?[e]:[...e];function ce(e,n){for(let t of n)if(!Object.hasOwn(e,t))throw new Error(`Column \`${t}\` doesn't exist.`)}function an(e,n){if(n instanceof Float64Array)return"double";let t=null;for(let r of n){if(r===null)continue;let o=typeof r=="number"?"double":typeof r=="string"?"character":"logical";if(t!==null&&o!==t)throw new TypeError(`column '${e}' mixes ${t} and ${o} values`);t=o}return t}function cn(e,n){let t=null;for(let r of n){let o=an(r,e[r]);if(o!==null){if(t===null)t={type:o,column:r};else if(t.type!==o){if(t.type==="character"||o==="character")throw new TypeError(`Can't combine \`${t.column}\` <${t.type}> and \`${r}\` <${o}>.`);o==="double"&&(t={type:o,column:r})}}}return t?.type??null}function fn(e,n,t){let r=new RegExp(`${n}|`).exec("").length-1;if(r!==t)throw new Error(`\`regex\` should define ${t} groups; ${r} found.`);let o=new RegExp(n);return e.map(i=>{let l=o.exec(i);return Array.from({length:t},(s,u)=>l===null?null:l[u+1]??null)})}function un(e,n,t,r){let o=new RegExp(n,"g"),i=[],l=[],s=e.map((a,g)=>{let m=[],y=0;for(let b of a.matchAll(o))b[0].length!==0&&(m.push(a.slice(y,b.index)),y=b.index+b[0].length);return m.push(a.slice(y)),m.length>t&&i.push(g+1),m.length<t&&l.push(g+1),Array.from({length:t},(b,d)=>m[d]??null)}),u=a=>`${a.length} rows [${a.join(", ")}]`;return i.length>0&&r.push(`Expected ${t} pieces. Additional pieces discarded in ${u(i)}.`),l.length>0&&r.push(`Expected ${t} pieces. Missing pieces filled with \`NA\` in ${u(l)}.`),s}function mn(e,n,t,r){let{namesSep:o,namesPattern:i}=t;if(n.length===1){if(o!==void 0)throw new Error("`names_sep` can't be used with a length 1 `names_to`.");if(i===void 0)return e.map(s=>[s]);let l=new RegExp(i);return e.map(s=>[l.exec(s)?.[1]??null])}if(o===void 0==(i===void 0))throw new Error("If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.");return o!==void 0?un(e,o,n.length,r):fn(e,i,n.length)}function hn(e,n){let t=q(e),r=Object.keys(e),o=typeof n.cols=="function"?r.filter(n.cols):[...new Set(n.cols)];if(ce(e,o),o.length===0)throw new Error("`cols` must select at least one column.");let i=P(n.namesTo??"name"),l=i.indexOf(".value");if(i.lastIndexOf(".value")!==l)throw new Error('`names_to` may contain ".value" only once');let s=[],u=n.namesPrefix===void 0?null:new RegExp(`^(?:${n.namesPrefix})`),a=o.map(f=>u===null?f:f.replace(u,"")),g=mn(a,i,n,s),m=[],y=[];if(l<0)m.push(...g),y.push({name:n.valuesTo??"value",sources:[...o]});else{let f=new Map,c=new Map;g.forEach((p,E)=>{let A=p.filter((O,U)=>U!==l),$=JSON.stringify(A),v=f.get($);if(v===void 0){v=m.length,f.set($,v),m.push(A);for(let O of y)O.sources.push(null)}let w=p[l]??"NA",M=c.get(w);if(M===void 0&&(M={name:w,sources:m.map(()=>null)},c.set(w,M),y.push(M)),M.sources[v]!==null)throw new Error(`the names give the value column '${w}' twice for one key`);M.sources[v]=o[E]})}let b=y.map(f=>cn(e,f.sources.filter(c=>c!==null))),d=[];if(n.colsVary==="slowest")for(let f=0;f<m.length;f++)for(let c=0;c<t;c++)d.push([c,f]);else for(let f=0;f<t;f++)for(let c=0;c<m.length;c++)d.push([f,c]);let x=(f,c,p)=>{let E=f.sources[p];return E==null?null:e[E][c]};n.valuesDropNa===!0&&(d=d.filter(([f,c])=>y.some(p=>!T(x(p,f,c)))));let N={},h=d.map(([f])=>f);for(let f of r)o.includes(f)||k(N,f,z(e[f],h));if(i.forEach((f,c)=>{if(c===l)return;let p=n.namesTransform?.[f],E=A=>{let $=m[A][c<l||l<0?c:c-1];return $===null||p===void 0?$:p($)};k(N,f,d.map(([,A])=>E(A)))}),y.forEach((f,c)=>{let p=b[c]==="double";if(p&&f.sources.every(E=>E!==null&&e[E]instanceof Float64Array))k(N,f.name,Float64Array.from(d,([E,A])=>x(f,E,A)));else{let E=d.map(([A,$])=>{let v=x(f,A,$);return p&&typeof v=="boolean"?Number(v):v});k(N,f.name,E)}}),n.onWarning!==void 0)for(let f of new Set(s))n.onWarning(f);return N}var pn=e=>T(e)?"NA":typeof e=="number"?`n${e}`:typeof e=="string"?`s${e}`:`b${String(e)}`;function ie(e,n){let t=new Map,r=[];return{codes:Array.from({length:n},(i,l)=>{let s=JSON.stringify(e.map(a=>pn(a[l]))),u=t.get(s);return u===void 0&&(u=r.length,t.set(s,u),r.push(l)),u}),firsts:r}}function gn(e){return T(e)?"NA":typeof e=="number"?Number.isFinite(e)?S(e):e>0?"Inf":"-Inf":typeof e=="boolean"?e?"TRUE":"FALSE":e}function Q(e,n,t){if(e!==void 0)return n(e)?e:e[t]}function yn(e,n={}){let t=q(e),r=P(n.namesFrom??"name"),o=P(n.valuesFrom??"value"),i=n.idCols===void 0?Object.keys(e).filter(c=>!r.includes(c)&&!o.includes(c)):P(n.idCols);ce(e,[...i,...r,...o]);let l=n.namesPrefix??"",s=n.namesSep??"_",u=ie(i.map(c=>e[c]),t),a=ie(r.map(c=>e[c]),t),g=a.firsts.map((c,p)=>p);n.namesSort===!0&&g.sort((c,p)=>{for(let E of r){let A=G(e[E][a.firsts[c]],e[E][a.firsts[p]]);if(A!==0)return A}return 0});let m=a.firsts.map(c=>l+r.map(p=>gn(e[p][c])).join(s)),y=a.firsts.length,b=Array.from({length:u.firsts.length*y},()=>[]);for(let c=0;c<t;c++)b[u.codes[c]*y+a.codes[c]].push(c);let d=c=>typeof c=="function",x=c=>typeof c!="object"||c===null,N=(c,p)=>{let E=e[c],A=Q(n.valuesFn,d,c),$=Q(n.valuesFill,x,c)??null,v=u.firsts.map((w,M)=>{let O=b[M*y+p];return O.length===0?$:A!==void 0?A(O.map(U=>E[U])):E[O[0]]});return E instanceof Float64Array&&v.every(w=>w===null||typeof w=="number")?Float64Array.from(v,w=>w===null?NaN:w):v};for(let c of o)if(Q(n.valuesFn,d,c)===void 0&&b.some(p=>p.length>1))throw new Error(`values from '${c}' are not uniquely identified; use valuesFn to summarise them`);let h={};for(let c of i)k(h,c,z(e[c],u.firsts));let f=(c,p)=>o.length===1?m[p]:`${c}${s}${m[p]}`;if(n.namesVary==="slowest")for(let c of g)for(let p of o)k(h,f(p,c),N(p,c));else for(let c of o)for(let p of g)k(h,f(c,p),N(c,p));return h}export{W as IQR,ln as aggregate,ee as completeCases,me as cor,ue as cov,Me as cummax,$e as cummin,xe as cumprod,Ae as cumsum,Le as cut,Se as cv,ve as diff,He as ecdf,Pe as findInterval,ze as fivenum,ge as fromRows,Re as geometricMean,Xe as hist,ke as kurtosis,Ve as mad,be as mean,je as meanAD,R as median,he as merge,Fe as modes,We as naOmit,hn as pivotLonger,yn as pivotWider,ne as pretty,we as prod,C as quantile,j as range,fe as rank,Te as scale,_ as sd,Oe as skewness,on as split,pe as subset,de as sum,Ce as table,_e as tabulate,nn as tapply,ye as toRows,Ie as unique,Ee as variance,Ne as weightedMean};
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Probability that a standard bivariate normal pair (X, Y) with correlation `rho` lies in the rectangle
3
+ * `lower ≤ (X, Y) ≤ upper`. Equivalent to mvtnorm's `pmvnorm(lower, upper, corr = matrix(c(1, rho, rho, 1), 2))`.
4
+ * Bounds may be infinite. Accurate to about 1e-15 absolute.
5
+ *
6
+ * @param lower - Lower bounds `[a1, a2]`.
7
+ * @param upper - Upper bounds `[b1, b2]`.
8
+ * @param rho - Correlation, in [−1, 1].
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * pbvnorm([-Infinity, -Infinity], [0, 0], 0.5); // 0.3333333333333333
13
+ * ```
14
+ */
15
+ export declare function pbvnorm(lower: readonly [number, number] | readonly number[], upper: readonly [number, number] | readonly number[], rho: number): number;
@@ -0,0 +1,131 @@
1
+ // Rectangle probabilities of the standard bivariate normal distribution (what mvtnorm's pmvnorm gives in two
2
+ // dimensions).
3
+ //
4
+ // Written for rStats.js from oracle/polycor-behaviour.md and the method published by A. Genz, "Numerical computation
5
+ // of rectangular bivariate and trivariate normal and t probabilities", Statistics and Computing 14 (2004) 251-260
6
+ // (after Drezner and Wesolowsky); no code was ported. The upper orthant probability P(X > h, Y > k) is Sheppard's
7
+ // integral over θ in [0, asin ρ], by Gauss-Legendre quadrature with 6, 12 or 20 nodes, for |ρ| < 0.925; closer to
8
+ // |ρ| = 1 it is Φ(−max(h, k)) minus an integral in t = sqrt(1 − ρ²)-scale whose singular part is taken out by a
9
+ // Taylor expansion and integrated in closed form. A rectangle is the alternating sum of four orthants, after
10
+ // reflecting (X, Y) → (−X, −Y) when that puts the rectangle in the upper tail (smaller orthants, less cancellation);
11
+ // it is clipped at 0.
12
+ import { pnorm } from "./normal.js";
13
+ /** Nodes in (0, 1) and weights of the n-point Gauss-Legendre rule on [−1, 1] (the symmetric half), by Newton's method */
14
+ function gaussLegendre(n) {
15
+ const x = [];
16
+ const w = [];
17
+ for (let i = 1; i <= n / 2; i++) {
18
+ let z = Math.cos((Math.PI * (i - 0.25)) / (n + 0.5));
19
+ let dp = 0;
20
+ for (let it = 0; it < 100; it++) {
21
+ // Legendre P_n(z) and its derivative by the three-term recurrence
22
+ let p0 = 1;
23
+ let p1 = z;
24
+ for (let k = 2; k <= n; k++)
25
+ [p0, p1] = [p1, ((2 * k - 1) * z * p1 - (k - 1) * p0) / k];
26
+ dp = (n * (z * p1 - p0)) / (z * z - 1);
27
+ const dz = p1 / dp;
28
+ z -= dz;
29
+ if (Math.abs(dz) <= 1e-17)
30
+ break;
31
+ }
32
+ x.push(z);
33
+ w.push(2 / ((1 - z * z) * dp * dp));
34
+ }
35
+ return { x, w };
36
+ }
37
+ const RULES = [gaussLegendre(6), gaussLegendre(12), gaussLegendre(20)];
38
+ const TWO_PI = 2 * Math.PI;
39
+ const upperPhi = (x) => pnorm(x, { lowerTail: false });
40
+ /** P(X > h, Y > k) for the standard bivariate normal with correlation r (h, k finite) */
41
+ function upperOrthant(h, k, r) {
42
+ if (r === 1)
43
+ return upperPhi(Math.max(h, k));
44
+ if (r === -1)
45
+ return Math.max(0, upperPhi(h) - pnorm(-k));
46
+ const { x, w } = RULES[Math.abs(r) < 0.3 ? 0 : Math.abs(r) < 0.75 ? 1 : 2];
47
+ const hk = h * k;
48
+ if (Math.abs(r) < 0.925) {
49
+ // Sheppard: Φ(−h)Φ(−k) + (1/2π) ∫_0^{asin r} exp(−(h² − 2hk sin θ + k²)/(2 cos² θ)) dθ
50
+ const hs = (h * h + k * k) / 2;
51
+ const asr = Math.asin(r);
52
+ let s = 0;
53
+ for (let i = 0; i < x.length; i++) {
54
+ for (const node of [1 - x[i], 1 + x[i]]) {
55
+ const sn = Math.sin((asr * node) / 2);
56
+ s += w[i] * Math.exp((sn * hk - hs) / (1 - sn * sn));
57
+ }
58
+ }
59
+ return (s * asr) / (2 * TWO_PI) + upperPhi(h) * upperPhi(k);
60
+ }
61
+ // |r| near 1: for r < 0 use P(X > h, Y > k; r) = Φ(−h) − P(X > h, −Y > −k; −r)
62
+ const kk = r < 0 ? -k : k;
63
+ const hkk = r < 0 ? -hk : hk;
64
+ const as = (1 - r) * (1 + r);
65
+ const a = Math.sqrt(as);
66
+ const bs = (h - kk) ** 2;
67
+ const c = (4 - hkk) / 8;
68
+ const d = (12 - hkk) / 16;
69
+ // P(X > h, Y > k; |r|) − Φ(−max(h, k)) = −(1/2π) (closed-form part + quadrature of the remainder) over t in (0, a)
70
+ let s = a * Math.exp(-(bs / as + hkk) / 2) * (1 - (c * (bs - as) * (1 - (d * bs) / 5)) / 3 + (c * d * as * as) / 5);
71
+ if (hkk > -160) {
72
+ const b = Math.sqrt(bs);
73
+ s -= Math.exp(-hkk / 2) * Math.sqrt(TWO_PI) * pnorm(-b / a) * b * (1 - (c * bs * (1 - (d * bs) / 5)) / 3);
74
+ }
75
+ const half = a / 2;
76
+ for (let i = 0; i < x.length; i++) {
77
+ for (const node of [1 - x[i], 1 + x[i]]) {
78
+ const xs = (half * node) ** 2;
79
+ const rs = Math.sqrt(1 - xs);
80
+ s +=
81
+ half *
82
+ w[i] *
83
+ (Math.exp(-bs / (2 * xs) - hkk / (1 + rs)) / rs - Math.exp(-(bs / xs + hkk) / 2) * (1 + c * xs * (1 + d * xs)));
84
+ }
85
+ }
86
+ const tail = -s / TWO_PI;
87
+ if (r > 0)
88
+ return tail + upperPhi(Math.max(h, kk));
89
+ return -tail + (kk > h ? pnorm(kk) - pnorm(h) : 0);
90
+ }
91
+ /** P(X > h, Y > k) with infinite bounds allowed */
92
+ function orthant(h, k, r) {
93
+ if (h === Infinity || k === Infinity)
94
+ return 0;
95
+ if (h === -Infinity)
96
+ return k === -Infinity ? 1 : upperPhi(k);
97
+ if (k === -Infinity)
98
+ return upperPhi(h);
99
+ return upperOrthant(h, k, r);
100
+ }
101
+ /**
102
+ * Probability that a standard bivariate normal pair (X, Y) with correlation `rho` lies in the rectangle
103
+ * `lower ≤ (X, Y) ≤ upper`. Equivalent to mvtnorm's `pmvnorm(lower, upper, corr = matrix(c(1, rho, rho, 1), 2))`.
104
+ * Bounds may be infinite. Accurate to about 1e-15 absolute.
105
+ *
106
+ * @param lower - Lower bounds `[a1, a2]`.
107
+ * @param upper - Upper bounds `[b1, b2]`.
108
+ * @param rho - Correlation, in [−1, 1].
109
+ *
110
+ * @example
111
+ * ```ts
112
+ * pbvnorm([-Infinity, -Infinity], [0, 0], 0.5); // 0.3333333333333333
113
+ * ```
114
+ */
115
+ export function pbvnorm(lower, upper, rho) {
116
+ if (lower.length !== 2 || upper.length !== 2)
117
+ throw new TypeError("'lower' and 'upper' must have length 2");
118
+ if (!(rho >= -1 && rho <= 1))
119
+ throw new RangeError("'rho' must be in [-1, 1]");
120
+ let [a1, a2] = lower;
121
+ let [b1, b2] = upper;
122
+ if ([a1, a2, b1, b2].some(Number.isNaN))
123
+ return NaN;
124
+ if (!(a1 < b1 && a2 < b2))
125
+ return 0;
126
+ // reflect a rectangle in the lower half into the upper half
127
+ if (a1 + b1 + a2 + b2 < 0)
128
+ [a1, a2, b1, b2] = [-b1, -b2, -a1, -a2];
129
+ const p = orthant(a1, a2, rho) - orthant(a1, b2, rho) - orthant(b1, a2, rho) + orthant(b1, b2, rho);
130
+ return Math.max(0, p);
131
+ }
@@ -22,7 +22,7 @@ import { betaIncDD } from "../special/incbet.js";
22
22
  import { dbinomExponent, dbinomRawDD } from "../special/loader.js";
23
23
  import { dbeta1, pbeta1, qbeta1 } from "./beta.js";
24
24
  import { dfDensity1, pf1, qf1 } from "./f.js";
25
- import { dnchisq1, pnchisq1, qnchisq1 } from "./nchisq.js";
25
+ import { dnchisq1, negligibleTail, pnchisq1, qnchisq1 } from "./nchisq.js";
26
26
  function betaKernel(a, b, xd, xcd) {
27
27
  const ab = twoSum(a, b);
28
28
  // For very small x the ratio underflows, so keep it scaled by 2^500
@@ -284,8 +284,41 @@ export function pnf1(q, m, n, ncp, lowerTail, logP) {
284
284
  return pnfTiny(q, m, n, ncp, lowerTail, logP);
285
285
  if (ncp === 0)
286
286
  return pf1(q, m, n, lowerTail, logP);
287
+ const neg = negligibleTail(fTailBound(q, m, n, ncp), lowerTail, logP);
288
+ if (neg !== undefined)
289
+ return neg;
287
290
  return pnfRaw(q, m, n, ncp, lowerTail, logP);
288
291
  }
292
+ /** Below this log a probability rounds to 0 in double precision (as in src/distributions/nchisq.ts) */
293
+ const LOG_NEGLIGIBLE = -746;
294
+ /**
295
+ * Chernoff bounds of the noncentral F = (X/m)/(V/n), X ~ χ²(m, λ), V ~ χ²(n) independent. With c = q m/n,
296
+ * F <= q is X - cV <= 0, and E[e^(-s(X - cV))] = (1 + 2s)^(-m/2) e^(-λs/(1 + 2s)) (1 - 2cs)^(-n/2) for 0 < s < 1/(2c)
297
+ * bounds P[F <= q]; E[e^(s(X - cV))] = (1 - 2s)^(-m/2) e^(λs/(1 - 2s)) (1 + 2cs)^(-n/2) for 0 < s < 1/2 bounds
298
+ * P[F >= q]. Every s in range gives a valid bound; the smallest over a grid of s is taken. Returns the tail whose
299
+ * bound is below the double range.
300
+ */
301
+ function fTailBound(q, m, n, ncp) {
302
+ const c = (q * m) / n;
303
+ if (!(c > 0 && Number.isFinite(c)))
304
+ return undefined;
305
+ const lower = (s) => -(m / 2) * Math.log1p(2 * s) - (ncp * s) / (1 + 2 * s) - (n / 2) * Math.log1p(-2 * c * s);
306
+ const upper = (s) => -(m / 2) * Math.log1p(-2 * s) + (ncp * s) / (1 - 2 * s) - (n / 2) * Math.log1p(2 * c * s);
307
+ const best = (f, sMax) => {
308
+ let b = Infinity;
309
+ for (let i = 1; i <= 60; i++) {
310
+ const v = Math.min(f(sMax * 2 ** -i), f(sMax * (1 - 2 ** -i)));
311
+ if (v < b)
312
+ b = v;
313
+ }
314
+ return b;
315
+ };
316
+ if (best(lower, 1 / (2 * c)) < LOG_NEGLIGIBLE)
317
+ return "lower";
318
+ if (best(upper, 0.5) < LOG_NEGLIGIBLE)
319
+ return "upper";
320
+ return undefined;
321
+ }
289
322
  export function qnf1(p, m, n, ncp, lowerTail, logP) {
290
323
  if (Number.isNaN(p) || Number.isNaN(m) || Number.isNaN(n) || Number.isNaN(ncp))
291
324
  return NaN;
@@ -1,3 +1,13 @@
1
1
  export declare function dnchisq1(x: number, df: number, ncp: number, log: boolean): number;
2
2
  export declare function pnchisq1(q: number, df: number, ncp: number, lowerTail: boolean, logP: boolean): number;
3
+ /**
4
+ * A tail that a rigorous bound places below the smallest positive double: `far` is "lower" when P[X <= q] is
5
+ * negligible, "upper" when P[X > q] is, undefined when neither bound decides it
6
+ */
7
+ export type FarTail = "lower" | "upper" | undefined;
8
+ /**
9
+ * The value of the requested tail when the far tail is negligible: the far tail is exactly 0, the near tail exactly 1
10
+ * (log 0). The log of the far tail is left to the full computation (undefined).
11
+ */
12
+ export declare function negligibleTail(far: FarTail, lowerTail: boolean, logP: boolean): number | undefined;
3
13
  export declare function qnchisq1(p: number, df: number, ncp: number, lowerTail: boolean, logP: boolean): number;