@numero-uno-jpn/rstats 0.17.0 → 1.1.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 (97) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/README.ja.md +20 -12
  3. package/README.md +22 -12
  4. package/THIRD_PARTY_NOTICES.md +3 -2
  5. package/dist/chunks/{chunk-4WE3OO62.js → chunk-4KCSBTR5.js} +2 -2
  6. package/dist/chunks/chunk-4VRMAYPY.js +3 -0
  7. package/dist/chunks/{chunk-RFE7MVP7.js → chunk-7IJCUSA5.js} +2 -2
  8. package/dist/chunks/chunk-7KJ24LYK.js +2 -0
  9. package/dist/chunks/{chunk-Z37NELOS.js → chunk-DR4GQ7PW.js} +1 -1
  10. package/dist/chunks/chunk-DTJG2IL2.js +2 -0
  11. package/dist/chunks/{chunk-C7V2FH6L.js → chunk-EJYCDE4Z.js} +1 -1
  12. package/dist/chunks/{chunk-LV3W2F7N.js → chunk-GGJA3JRO.js} +2 -2
  13. package/dist/chunks/{chunk-H3WVPZDL.js → chunk-GJEKNJP7.js} +2 -2
  14. package/dist/chunks/{chunk-2C33MXSW.js → chunk-GRUQRNX7.js} +2 -2
  15. package/dist/chunks/chunk-GYGQUYEP.js +2 -0
  16. package/dist/chunks/chunk-HRA7PCQT.js +2 -0
  17. package/dist/chunks/{chunk-WM7VFXTV.js → chunk-HUWOSLKE.js} +1 -1
  18. package/dist/chunks/{chunk-TNMJPQPV.js → chunk-HZLSNJQM.js} +2 -2
  19. package/dist/chunks/{chunk-ZFQWB222.js → chunk-JNWWLNE3.js} +2 -2
  20. package/dist/chunks/{chunk-DXI5N2ET.js → chunk-N5BDSMXS.js} +1 -1
  21. package/dist/chunks/{chunk-LHUIJQHY.js → chunk-NDTJ23A6.js} +2 -2
  22. package/dist/chunks/{chunk-SE7V2KLO.js → chunk-OG7UORIX.js} +1 -1
  23. package/dist/chunks/{chunk-ONY5CISH.js → chunk-QUTJEYDX.js} +2 -2
  24. package/dist/chunks/chunk-U7BRXOUS.js +2 -0
  25. package/dist/chunks/{chunk-FY3FVOBM.js → chunk-UMLMY4XS.js} +2 -2
  26. package/dist/chunks/{chunk-6JJQL6HL.js → chunk-X4J6UJHN.js} +2 -2
  27. package/dist/chunks/{chunk-34S5SQY6.js → chunk-Y4YWLSWU.js} +2 -2
  28. package/dist/chunks/{chunk-5AYHCITP.js → chunk-YN5MLKDL.js} +2 -2
  29. package/dist/chunks/{chunk-CZI7KUO3.js → chunk-Z2HGLFZN.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions/signrank.js +2 -2
  32. package/dist/distributions.js +2 -2
  33. package/dist/entries/mixed.d.ts +6 -0
  34. package/dist/entries/mixed.js +6 -1
  35. package/dist/entries/tests.d.ts +1 -1
  36. package/dist/htest/ansariTest.js +32 -34
  37. package/dist/htest/cor.d.ts +2 -2
  38. package/dist/htest/cor.js +2 -1
  39. package/dist/htest/core/scoreDistribution.d.ts +39 -0
  40. package/dist/htest/core/scoreDistribution.js +151 -0
  41. package/dist/htest/wilcoxTest.d.ts +23 -8
  42. package/dist/htest/wilcoxTest.js +521 -199
  43. package/dist/linalg/chol.d.ts +3 -3
  44. package/dist/linalg/chol.js +10 -2
  45. package/dist/linalg/qr.js +39 -15
  46. package/dist/linalg.js +2 -2
  47. package/dist/mixed.js +5 -4
  48. package/dist/models/anovaSequential.d.ts +16 -1
  49. package/dist/models/anovaSequential.js +40 -5
  50. package/dist/models/aovStrata.js +21 -4
  51. package/dist/models/formula.d.ts +5 -2
  52. package/dist/models/formula.js +31 -8
  53. package/dist/models/glm.d.ts +15 -4
  54. package/dist/models/glm.js +13 -6
  55. package/dist/models/glmer.d.ts +255 -0
  56. package/dist/models/glmer.js +635 -0
  57. package/dist/models/glmerAnova.d.ts +81 -0
  58. package/dist/models/glmerAnova.js +139 -0
  59. package/dist/models/glmerDeviance.d.ts +98 -0
  60. package/dist/models/glmerDeviance.js +576 -0
  61. package/dist/models/glmerFamily.d.ts +57 -0
  62. package/dist/models/glmerFamily.js +236 -0
  63. package/dist/models/glmerGradient.d.ts +46 -0
  64. package/dist/models/glmerGradient.js +301 -0
  65. package/dist/models/glmerStructure.d.ts +45 -0
  66. package/dist/models/glmerStructure.js +168 -0
  67. package/dist/models/glmerSummary.d.ts +102 -0
  68. package/dist/models/glmerSummary.js +94 -0
  69. package/dist/models/lmer.d.ts +16 -0
  70. package/dist/models/lmer.js +55 -306
  71. package/dist/models/lmerAnova.d.ts +49 -0
  72. package/dist/models/lmerAnova.js +91 -40
  73. package/dist/models/lmerTest.d.ts +8 -1
  74. package/dist/models/lmerTest.js +21 -8
  75. package/dist/models/mixedDeviance.d.ts +28 -2
  76. package/dist/models/mixedDeviance.js +84 -56
  77. package/dist/models/mixedMinimiser.d.ts +83 -0
  78. package/dist/models/mixedMinimiser.js +438 -0
  79. package/dist/models/mixedPredict.d.ts +121 -0
  80. package/dist/models/mixedPredict.js +530 -0
  81. package/dist/models/mixedStructure.d.ts +62 -3
  82. package/dist/models/mixedStructure.js +74 -29
  83. package/dist/models/modelMatrix.d.ts +8 -1
  84. package/dist/models/modelMatrix.js +49 -37
  85. package/dist/models/survival.d.ts +4 -1
  86. package/dist/models/survival.js +7 -1
  87. package/dist/numerics.js +2 -2
  88. package/dist/rstats.js +16 -16
  89. package/dist/special.js +2 -2
  90. package/dist/tests.js +13 -14
  91. package/llms.txt +11 -3
  92. package/package.json +1 -1
  93. package/dist/chunks/chunk-M4ITG7YR.js +0 -2
  94. package/dist/chunks/chunk-NSYZTS26.js +0 -2
  95. package/dist/chunks/chunk-THIGHOKK.js +0 -2
  96. package/dist/chunks/chunk-WMDYDTVQ.js +0 -2
  97. package/dist/chunks/chunk-XLSFJTTK.js +0 -2
@@ -1,4 +1,4 @@
1
- // Wilcoxon tests (R's wilcox.test): the one-sample / paired signed rank test and the two-sample rank sum test
1
+ // Wilcoxon tests (R's wilcox.test, R 4.6): the one-sample / paired signed rank test and the two-sample rank sum test
2
2
  // (Mann-Whitney).
3
3
  //
4
4
  // The statistics and normal approximation (mean, tie-corrected variance, direction of the continuity correction) use
@@ -10,23 +10,31 @@
10
10
  // their median; the normal-approximation interval is where the standardised statistic of the shifted data, a step
11
11
  // function of the shift, crosses the normal quantiles, found with R's uniroot conventions (src/internal/uniroot.ts,
12
12
  // tolerance tolRoot), and the estimate is where it crosses 0 without continuity correction. The switch between exact
13
- // and normal approximation, the reported confidence level when the requested one is not attainable, intervals that
14
- // cannot be formed, and names follow R's documented and observed behaviour.
15
- // - The exact method is used when exact = null and n < 50 (both < 50 for two samples). With ties or zero differences,
16
- // the normal approximation is used even when exact = true
13
+ // and normal approximation, the reported confidence levels, intervals that cannot be formed, and names follow R's
14
+ // documented and observed behaviour (oracle/wilcox46-behaviour.md).
15
+ // - The exact method is used when exact = null and n < 50 (n counting the zeros; both < 50 for two samples). With ties
16
+ // or zero differences it is the exact conditional (permutation) test given the mid-ranks (core/scoreDistribution.ts);
17
+ // the signed rank test then ranks the zeros with the data and leaves them out of the scores (Pratt 1959), while the
18
+ // normal approximation drops them first (Wilcoxon)
19
+ // - Exact intervals report the achieved confidence level. With ties or zeros they come from inverting the conditional
20
+ // test at the midpoints between consecutive Walsh averages (differences)
21
+ // - correct: 0..3 (0 as true) adds that many Edgeworth terms to the continuity-corrected normal approximation of the
22
+ // p-value, without ties and zeros only (Fellingham and Stoker 1964 for the signed rank, Fix and Hodges 1955 for the
23
+ // rank sum statistic)
17
24
  // - Only NaN is removed (R's documentation says non-finite values are removed, but in fact Inf is kept and ranked)
18
25
  // - For the one-sample normal-approximation interval, α is doubled repeatedly until the requested confidence level is reached
19
26
  // (only for alternative = "less" is reachability judged with the α/2 quantile; R's behaviour kept as is).
20
27
  // The two-sample interval is clamped at the ends and the confidence level is kept
21
28
  import { psignrank1, qsignrank1 } from "../distributions/signrank.js";
22
29
  import { pwilcox1, qwilcox1 } from "../distributions/wilcox.js";
23
- import { pnorm, qnorm } from "../distributions/normal.js";
30
+ import { dnorm, pnorm, qnorm } from "../distributions/normal.js";
24
31
  import { completePairs, dropNaN, mean, rank, tieCounts, } from "../internal/summary.js";
25
32
  import { uniroot } from "../internal/uniroot.js";
26
33
  import { reported, Warnings } from "../internal/warnings.js";
27
34
  import { twoSampleData } from "./testFormula.js";
28
35
  import { matchAlternative } from "./types.js";
29
36
  import { maxOf, midpoint, minOf } from "../internal/extremes.js";
37
+ import { lowerTail, MAX_SCORE_TABLE, rankSumScoreCost, rankSumScoreDistribution, scoreKey, signedScoreCost, signedScoreDistribution, upperTail, } from "./core/scoreDistribution.js";
30
38
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
31
39
  import { checkOptions } from "../internal/checkOptions.js";
32
40
  import { isOptionsObject } from "../internal/optionalArgs.js";
@@ -55,7 +63,7 @@ export function wilcoxTest(x, y, options = {}) {
55
63
  const mu = options.mu ?? 0;
56
64
  const paired = options.paired ?? false;
57
65
  const exact = options.exact ?? null;
58
- const correct = options.correct ?? true;
66
+ const correct = correctionTerms(options.correct ?? true);
59
67
  const confInt = options.confInt ?? false;
60
68
  const confLevel = options.confLevel ?? 0.95;
61
69
  const tolRoot = options.tolRoot ?? 1e-4;
@@ -93,6 +101,15 @@ export function wilcoxTest(x, y, options = {}) {
93
101
  };
94
102
  return reported("wilcoxTest", yv === undefined ? signedRank(xs, exact, paired, ctx) : rankSum(xs, yv, exact, ctx));
95
103
  }
104
+ /** R 4.6's reading of correct: false -1, true 0, a number 0..3 itself; another number is an error */
105
+ function correctionTerms(correct) {
106
+ if (typeof correct === "boolean")
107
+ return correct ? 0 : -1;
108
+ if (!(Number.isInteger(correct) && correct >= 0 && correct <= 3)) {
109
+ throw new RangeError("'correct' must be an integer between 0 and 3");
110
+ }
111
+ return correct;
112
+ }
96
113
  /** Continuity correction amount (two-sided: 0.5 in the direction of the statistic's sign) */
97
114
  function correction(z, alternative, correct) {
98
115
  if (!correct)
@@ -101,25 +118,58 @@ function correction(z, alternative, correct) {
101
118
  return Math.sign(z) * 0.5;
102
119
  return alternative === "greater" ? 0.5 : -0.5;
103
120
  }
104
- /** p-value from the standardised statistic */
105
- function normalP(z, alternative) {
121
+ /** 10 eps: R's slack in the exact intervals' tail comparisons */
122
+ const TAIL_TOL = 10 * Number.EPSILON;
123
+ /**
124
+ * p-value from the standardised statistic z and the Edgeworth correction e(z) (0 for none): the lower tail
125
+ * Phi(z) - e phi(z) and the upper tail Phi(-z) + e phi(z), each clamped to [0, 1]
126
+ */
127
+ function normalP(z, alternative, e = 0) {
128
+ const clamp = (p) => Math.min(1, Math.max(p, 0));
129
+ const lower = () => (e === 0 ? pnorm(z) : clamp(pnorm(z) - e * dnorm(z)));
130
+ const upper = () => (e === 0 ? pnorm(z, { lowerTail: false }) : clamp(pnorm(z, { lowerTail: false }) + e * dnorm(z)));
106
131
  if (alternative === "less")
107
- return pnorm(z);
132
+ return lower();
108
133
  if (alternative === "greater")
109
- return pnorm(z, { lowerTail: false });
110
- return 2 * Math.min(pnorm(z), pnorm(z, { lowerTail: false }));
111
- }
112
- /** Round to 2 significant digits (exact halves to even). 0 < v */
113
- function signif2(v) {
114
- if (!(v > 0) || !Number.isFinite(v))
115
- return v;
116
- const e = Math.floor(Math.log10(v));
117
- const k = 1 - e;
118
- const s = k >= 0 ? v * 10 ** k : v / 10 ** -k;
119
- let r = Math.round(s);
120
- if (r - s === 0.5 && r % 2 !== 0)
121
- r -= 1;
122
- return k >= 0 ? r / 10 ** k : r * 10 ** -k;
134
+ return upper();
135
+ // R 4.6.2 takes 2 min(F, 1 - F) with 1 - F formed from the lower tail F, which loses the digits of a small upper
136
+ // tail (wilcox.test(1:300, exact = FALSE) gives 0 for 6.1e-51). Its value where 1 - F keeps them (at most 7 bits
137
+ // lost from 1/64 on); the upper tail itself below (docs/differences-from-r.md)
138
+ const F = lower();
139
+ if (F <= 0.5)
140
+ return 2 * F;
141
+ const G = upper();
142
+ return G >= 1 / 64 ? 2 * (1 - F) : 2 * G;
143
+ }
144
+ /** He3, He5, He7: the Hermite polynomials of the Edgeworth terms */
145
+ function hermite(z) {
146
+ const z2 = z * z;
147
+ return [z * (z2 - 3), z * (z2 * (z2 - 10) + 15), z * (z2 * (z2 * (z2 - 21) + 105) - 105)];
148
+ }
149
+ /** Edgeworth correction e(z) of the signed rank statistic with n observations (Fellingham and Stoker 1964), k terms */
150
+ function edgeworthSignedRank(z, n, k) {
151
+ const D = n * (n + 1) * (2 * n + 1);
152
+ const c4 = -(3 * n * n + 3 * n - 1) / (10 * D);
153
+ const c6 = (4 * (3 * n ** 4 + 6 * n ** 3 - 3 * n + 1)) / (35 * D * D);
154
+ return edgeworth(z, c4, c6, k);
155
+ }
156
+ /** Edgeworth correction e(z) of the rank sum statistic with sizes m and n (Fix and Hodges 1955), k terms */
157
+ function edgeworthRankSum(z, m, n, k) {
158
+ const N = m + n;
159
+ const mn = m * n;
160
+ const c3 = -(N * (N + 1) - mn) / (20 * mn * (N + 1));
161
+ const c5 = (2 * (m ** 4 + n ** 4) + 4 * mn * (m * m + n * n) + 6 * mn * mn + 4 * (m ** 3 + n ** 3) + (7 * mn + N - 1) * N) /
162
+ (210 * mn * mn * (N + 1) ** 2);
163
+ return edgeworth(z, c3, c5, k);
164
+ }
165
+ function edgeworth(z, c1, c2, k) {
166
+ const [h3, h5, h7] = hermite(z);
167
+ let e = c1 * h3;
168
+ if (k >= 2)
169
+ e += c2 * h5;
170
+ if (k >= 3)
171
+ e += ((c1 * c1) / 2) * h7;
172
+ return e;
123
173
  }
124
174
  /** Median of an ascending array */
125
175
  function sortedMedian(s) {
@@ -130,6 +180,24 @@ function sortedMedian(s) {
130
180
  return n % 2 === 1 ? s[h] : mean([s[h - 1], s[h]]);
131
181
  }
132
182
  const ascending = (a, b) => a - b;
183
+ // ---- Limits of the exact conditional distributions (CONTRIBUTING rule 4) ----
184
+ /**
185
+ * Steps of the conditional distributions one call may take: inner-loop steps of core/scoreDistribution.ts (and
186
+ * EVAL_STEPS per observation and shift of an interval's scan), measured at 1 to 1.6 ns each on a Mac mini (Apple M1,
187
+ * Node 24), so at most about 8 s
188
+ */
189
+ const MAX_EXACT_STEPS = 5e9;
190
+ /** Steps counted per observation for each shift of an interval's scan (ranks, scores and their key) */
191
+ const EVAL_STEPS = 40;
192
+ function tooLarge(what) {
193
+ return new RangeError(`wilcoxTest: the exact conditional ${what} would take too long or too much memory: use exact: false`);
194
+ }
195
+ /** Cost of one conditional distribution, checked against the limits */
196
+ function checkedCost(cost, what) {
197
+ if (cost.size > MAX_SCORE_TABLE || cost.steps > MAX_EXACT_STEPS)
198
+ throw tooLarge(what);
199
+ return cost.steps;
200
+ }
133
201
  // ---- One-sample / paired (signed rank test) ----
134
202
  /** Signed rank statistic of x - d (zeros removed): [V - expectation, standard deviation] */
135
203
  function signedRankStat(x) {
@@ -146,7 +214,7 @@ function signedRankStat(x) {
146
214
  return [v, v - (n * (n + 1)) / 4, sigma];
147
215
  }
148
216
  function signedRank(x0, exactOpt, paired, ctx) {
149
- const { alternative, mu, correct } = ctx;
217
+ const { alternative, mu } = ctx;
150
218
  let x = x0.map((v) => v - mu);
151
219
  // A finite observation whose difference from mu overflows: the differences in half units (x / 2 - mu / 2). Then
152
220
  // abs(mu) >= 2^970, so each half difference is exactly half the rounded difference (a subnormal x / 2 rounds far
@@ -155,38 +223,9 @@ function signedRank(x0, exactOpt, paired, ctx) {
155
223
  if (halved)
156
224
  x = x0.map((v) => v / 2 - mu / 2);
157
225
  const zeroes = x.some((v) => v === 0);
158
- if (zeroes)
159
- x = x.filter((v) => v !== 0);
160
- const n = x.length;
161
- // only zero differences: nothing to rank (R returns a p-value of NaN)
162
- if (n === 0)
163
- throw new RangeError("no non-zero differences for the signed rank test");
164
- const exact = exactOpt ?? n < 50;
165
- const r = rank(x.map(Math.abs));
166
- const ties = tieCounts(r).length > 0;
167
- const [V, dz, sigma] = signedRankStat(x);
168
- let pValue;
169
- let method;
170
- const useExact = exact && !ties && !zeroes;
171
- if (useExact) {
172
- method = "Wilcoxon signed rank exact test";
173
- const total = (n * (n + 1)) / 2;
174
- if (alternative === "less")
175
- pValue = psignrank1(V, n, true, false);
176
- else if (alternative === "greater")
177
- pValue = psignrank1(V - 1, n, false, false);
178
- else {
179
- const p = V > total / 2
180
- ? psignrank1(V - 1, n, false, false)
181
- : psignrank1(V, n, true, false);
182
- pValue = Math.min(1, 2 * p);
183
- }
184
- }
185
- else {
186
- method = `Wilcoxon signed rank test${correct ? " with continuity correction" : ""}`;
187
- pValue = normalP((dz - correction(dz, alternative, correct)) / sigma, alternative);
188
- }
189
- const result = {
226
+ // R 4.6 counts the zeros in the switch to the normal approximation
227
+ const exact = exactOpt ?? x.length < 50;
228
+ const result = (method, V, pValue) => ({
190
229
  method,
191
230
  alternative,
192
231
  statistic: V,
@@ -195,44 +234,66 @@ function signedRank(x0, exactOpt, paired, ctx) {
195
234
  nullValue: mu,
196
235
  nullValueName: paired ? "location shift" : "location",
197
236
  warnings: ctx.warnings.list,
198
- };
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");
237
+ });
238
+ if (exact) {
239
+ // Pratt: the zeros take the smallest ranks of |x|, add nothing to V and are not among the scores
240
+ const r = rank(x.map(Math.abs));
241
+ const ties = tieCounts(r).length > 0;
242
+ let V = 0;
243
+ for (let i = 0; i < x.length; i++)
244
+ if (x[i] > 0)
245
+ V += r[i];
246
+ const method = "Wilcoxon signed rank exact test";
247
+ if (!ties && !zeroes) {
248
+ const n = x.length;
249
+ const total = (n * (n + 1)) / 2;
250
+ let pValue;
251
+ if (alternative === "less")
252
+ pValue = psignrank1(V, n, true, false);
253
+ else if (alternative === "greater")
254
+ pValue = psignrank1(V - 1, n, false, false);
255
+ else {
256
+ const p = V > total / 2 ? psignrank1(V - 1, n, false, false) : psignrank1(V, n, true, false);
257
+ pValue = Math.min(1, 2 * p);
258
+ }
259
+ const out = result(method, V, pValue);
260
+ return ctx.confInt ? { ...out, ...signedRankExactCI(x0, ctx) } : out;
205
261
  }
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");
262
+ const scores = r.filter((_, i) => x[i] !== 0);
263
+ checkedCost(signedScoreCost(scores), "distribution");
264
+ const dist = signedScoreDistribution(scores);
265
+ let pValue;
266
+ if (alternative === "less")
267
+ pValue = lowerTail(dist, V);
268
+ else if (alternative === "greater")
269
+ pValue = upperTail(dist, V - 0.25);
270
+ else {
271
+ let centre = 0;
272
+ for (const s of scores)
273
+ centre += s / 2;
274
+ pValue = Math.min(1, 2 * (V > centre ? upperTail(dist, V - 0.25) : lowerTail(dist, V)));
210
275
  }
211
- };
212
- if (!ctx.confInt) {
213
- exactWarnings();
214
- return result;
276
+ const out = result(method, V, pValue);
277
+ return ctx.confInt ? { ...out, ...signedRankConditionalCI(x0, ctx) } : out;
215
278
  }
216
- // The interval is on the original scale (add mu back to the data with zero differences removed)
217
- // (with half units, the observations other than mu themselves)
218
- // R also adds mu back. Where mu dwarfs the data, (x - mu) + mu loses the observations (rnorm(n, 0, 1e-200) with
219
- // mu = 0.5 gave R's interval NaN NaN and estimate 0): then the observations themselves, which are the same values
220
- // (x - mu = 0 exactly where x = mu). The bound 2^-26 of the largest observation leaves the rounding of ordinary
221
- // data, an ulp or two, to R's values (#502)
222
- let xo = halved ? x0.filter((v) => v !== mu) : x.map((v) => v + mu);
223
- if (!halved) {
224
- const direct = x0.filter((v) => v !== mu);
225
- let big = 0;
226
- for (const v of direct)
227
- big = Math.max(big, Math.abs(v));
228
- if (xo.some((v, i) => Math.abs(v - direct[i]) > 2 ** -26 * big))
229
- xo = direct;
230
- }
231
- const ci = useExact
232
- ? signedRankExactCI(xo, ctx)
233
- : signedRankNormalCI(xo, ctx);
234
- exactWarnings();
235
- return { ...result, ...ci };
279
+ // Normal approximation: the zeros are dropped first (Wilcoxon), as in R
280
+ const nonzero = zeroes ? x.filter((v) => v !== 0) : x;
281
+ const n = nonzero.length;
282
+ // only zero differences: nothing to rank (R returns a p-value of NaN)
283
+ if (n === 0)
284
+ throw new RangeError("no non-zero differences for the signed rank test");
285
+ const [V, dz, sigma] = signedRankStat(nonzero);
286
+ const ties = tieCounts(rank(nonzero.map(Math.abs))).length > 0;
287
+ // the Edgeworth terms only without ties and zeros (R)
288
+ const terms = ties || zeroes ? Math.min(ctx.correct, 0) : ctx.correct;
289
+ const z = (dz - correction(dz, alternative, terms >= 0)) / sigma;
290
+ const pValue = normalP(z, alternative, terms >= 1 ? edgeworthSignedRank(z, n, terms) : 0);
291
+ const out = result(`Wilcoxon signed rank test${ctx.correct >= 0 ? " with continuity correction" : ""}`, V, pValue);
292
+ if (!ctx.confInt)
293
+ return out;
294
+ // R 4.6 searches the interval on the observations themselves, the values equal to mu included (R 4.5 searched
295
+ // x - mu without its zeros and added mu back, which lost the observations where mu dwarfs them, #502)
296
+ return { ...out, ...signedRankNormalCI(x0, ctx) };
236
297
  }
237
298
  /** Interval with the given finite ends, the other end(s) open according to the alternative */
238
299
  function shape(alternative, lower, upper) {
@@ -249,48 +310,271 @@ function noInterval(alternative, estimate, estimateNames) {
249
310
  out.estimateNames = estimateNames;
250
311
  return out;
251
312
  }
252
- /** Order-statistic ranks of an exact distribution-free interval: q from the lower-tail quantile (0 replaced by 1) */
253
- function exactRank(quantile, alternative, a) {
254
- const q = quantile(alternative === "two.sided" ? a / 2 : a);
255
- return q === 0 ? 1 : q;
256
- }
257
313
  function checkTolRoot(tol) {
258
314
  if (!(tol > 0 && tol < Infinity))
259
315
  throw new RangeError("tolRoot must be a positive finite number");
260
316
  }
317
+ /** Sorted Walsh averages (x_i + x_j) / 2, i <= j (NaN, from -Inf and Inf, left out as R's sort does) */
318
+ function walshAverages(x) {
319
+ const n = x.length;
320
+ const walsh = [];
321
+ for (let i = 0; i < n; i++) {
322
+ for (let j = i; j < n; j++) {
323
+ const w = midpoint(x[i], x[j]);
324
+ if (!Number.isNaN(w))
325
+ walsh.push(w);
326
+ }
327
+ }
328
+ return walsh.sort(ascending);
329
+ }
261
330
  /**
262
- * Exact interval from the order statistics of the Walsh averages (Bauer 1972) and the Hodges-Lehmann estimate, their
263
- * median
331
+ * Exact interval from order statistics (Bauer 1972), as R 4.6: q is the lower a'-quantile of the statistic, raised by
332
+ * one where its tail is within 10 eps of a' (so that the excluded tail is at most a'); q = 0 gives (-Inf, Inf) with
333
+ * level 1 for every alternative. The level reported is the achieved one
264
334
  */
265
- function signedRankExactCI(x, ctx) {
335
+ function orderStatisticCI(sorted, cdf, quantile, ctx, estimateNames) {
266
336
  const { alternative, confLevel } = ctx;
337
+ const K = sorted.length;
338
+ const a = alternative === "two.sided" ? (1 - confLevel) / 2 : 1 - confLevel;
339
+ let q = quantile(a);
340
+ if (cdf(q) <= a + TAIL_TOL)
341
+ q++;
342
+ const estimate = sortedMedian(sorted);
343
+ if (q === 0)
344
+ return { confInt: [-Infinity, Infinity], confLevel: 1, estimate, estimateNames };
345
+ const tail = cdf(q - 1);
346
+ return {
347
+ confInt: shape(alternative, sorted[q - 1], sorted[K - q]),
348
+ confLevel: 1 - (alternative === "two.sided" ? 2 * tail : tail),
349
+ estimate,
350
+ estimateNames,
351
+ };
352
+ }
353
+ /** Classical exact interval: order statistics of the Walsh averages; the estimate their median (Hodges-Lehmann) */
354
+ function signedRankExactCI(x, ctx) {
267
355
  const n = x.length;
268
- const walsh = [];
269
- for (let i = 0; i < n; i++)
270
- for (let j = i; j < n; j++)
271
- walsh.push(midpoint(x[i], x[j]));
272
- walsh.sort(ascending);
273
- const N = walsh.length;
274
- const a = 1 - confLevel;
275
- const q = exactRank((p) => qsignrank1(p, n, true, false), alternative, a);
276
- const tail = psignrank1(q - 1, n, true, false);
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");
356
+ return orderStatisticCI(walshAverages(x), (q) => psignrank1(q, n, true, false), (p) => qsignrank1(p, n, true, false), ctx, "(pseudo)median");
357
+ }
358
+ /**
359
+ * Mid-ranks of v (no NaN) and a key of their multiset: the runs of ties in sorted order (the mid-ranks follow from
360
+ * them). From a native sort and binary searches, as the interval's scan does this at every shift
361
+ */
362
+ function ranksAndKey(v) {
363
+ const n = v.length;
364
+ const sorted = Float64Array.from(v).sort();
365
+ const ranks = new Array(n);
366
+ for (let i = 0; i < n; i++) {
367
+ const a = v[i];
368
+ let lo = 0;
369
+ let hi = n;
370
+ while (lo < hi) {
371
+ const m = (lo + hi) >>> 1;
372
+ if (sorted[m] < a)
373
+ lo = m + 1;
374
+ else
375
+ hi = m;
376
+ }
377
+ let up = lo;
378
+ hi = n;
379
+ while (up < hi) {
380
+ const m = (up + hi) >>> 1;
381
+ if (sorted[m] <= a)
382
+ up = m + 1;
383
+ else
384
+ hi = m;
385
+ }
386
+ ranks[i] = (lo + 1 + up) / 2;
387
+ }
388
+ let key = "";
389
+ for (let i = 0; i < n;) {
390
+ let j = i;
391
+ while (j + 1 < n && sorted[j + 1] === sorted[i])
392
+ j++;
393
+ if (j > i)
394
+ key += `${i}:${j - i + 1},`;
395
+ i = j + 1;
396
+ }
397
+ return { ranks, key };
398
+ }
399
+ /**
400
+ * Exact conditional interval (ties or zeros): the conditional test inverted at the midpoints between consecutive
401
+ * sorted Walsh averages (differences) A_1 <= ... <= A_K, as R 4.6. The lower end is the first A_k whose following
402
+ * midpoint has upperP > a' + 10 eps (-Inf where already A_1 - 1 has), with the tail of the last rejected point; the
403
+ * upper end likewise from the top with lowerP. The distribution is rebuilt for each multiset of scores (cached).
404
+ *
405
+ * An end at A_1 (A_K) is reported with the tail rejected there, at A_1 - 1 (A_K + 1). R 4.6.2 reports 0, which overstates
406
+ * the level (wilcox.test(c(1, 2, 3), c(3, 4, 5), conf.int = TRUE, alternative = "greater", conf.level = 0.92) gives
407
+ * level 1 where 0.95 is achieved; docs/differences-from-r.md)
408
+ */
409
+ function conditionalCI(A, at, distribution, cost, upperP, lowerP, scale, nScores, ctx, estimateNames) {
410
+ const { alternative, confLevel } = ctx;
411
+ const K = A.length;
412
+ const a = alternative === "two.sided" ? (1 - confLevel) / 2 : 1 - confLevel;
413
+ const a2 = a + TAIL_TOL;
414
+ const doLower = alternative !== "less";
415
+ const doUpper = alternative !== "greater";
416
+ const mid = (k) => midpoint(A[k - 1], A[k]);
417
+ // The shifts the scan will try, as far as it is likely to go (the scan stops near the a'-quantile of the
418
+ // statistic; a normal estimate plus a margin), evaluated first to check the time limit before starting: a
419
+ // distribution is built for each change of the multiset of scores, a few kept at once. Their statistics and keys
420
+ // are kept for the scan
421
+ const reach = Math.min(K - 1, Math.max(1, Math.ceil(scale.mean + qnorm(Math.min(a2, 1)) * scale.sd + 0.1 * scale.sd + 3)));
422
+ const CACHE = 8;
423
+ // shifts: the outer point, then the midpoints from that end (index 0 .. reach)
424
+ const lowerShift = (i) => (i === 0 ? A[0] - 1 : mid(i));
425
+ const upperShift = (i) => (i === 0 ? A[K - 1] + 1 : mid(K - i));
426
+ const planned = [new Map(), new Map()];
427
+ {
428
+ const seen = new Map();
429
+ let steps = 0;
430
+ const evalSteps = EVAL_STEPS * nScores;
431
+ for (const [side, shift] of [[0, lowerShift], [1, upperShift]]) {
432
+ if (side === 0 ? !doLower : !doUpper)
433
+ continue;
434
+ for (let i = 0; i <= reach; i++) {
435
+ steps += evalSteps;
436
+ if (steps > MAX_EXACT_STEPS)
437
+ throw tooLarge("interval");
438
+ let s;
439
+ try {
440
+ s = at(shift(i));
441
+ }
442
+ catch {
443
+ // an undefined shift (infinite data): the scan may stop before it, as R's (which stops at it otherwise)
444
+ break;
445
+ }
446
+ planned[side].set(i, [s.stat, s.key]);
447
+ if (seen.has(s.key)) {
448
+ seen.delete(s.key);
449
+ seen.set(s.key, true);
450
+ continue;
451
+ }
452
+ steps += cost(s.scores);
453
+ if (steps > MAX_EXACT_STEPS)
454
+ throw tooLarge("interval");
455
+ seen.set(s.key, true);
456
+ if (seen.size > CACHE)
457
+ seen.delete(seen.keys().next().value);
458
+ }
459
+ }
460
+ }
461
+ const cache = new Map();
462
+ /** The statistic and its distribution at the i-th shift from one end */
463
+ const evaluate = (side, i) => {
464
+ const t = side === 0 ? lowerShift(i) : upperShift(i);
465
+ let p = planned[side].get(i);
466
+ let scores;
467
+ if (p === undefined) {
468
+ const s = at(t);
469
+ p = [s.stat, s.key];
470
+ scores = s.scores;
471
+ }
472
+ const [stat, key] = p;
473
+ let d = cache.get(key);
474
+ if (d !== undefined)
475
+ cache.delete(key);
476
+ else {
477
+ d = distribution(scores ?? at(t).scores);
478
+ if (cache.size >= CACHE)
479
+ cache.delete(cache.keys().next().value);
480
+ }
481
+ cache.set(key, d);
482
+ return [stat, d];
483
+ };
484
+ const upperAt = (i) => {
485
+ const [stat, d] = evaluate(0, i);
486
+ return upperP(d, stat);
487
+ };
488
+ const lowerAt = (i) => {
489
+ const [stat, d] = evaluate(1, i);
490
+ return lowerP(d, stat);
491
+ };
492
+ let lower = -Infinity;
493
+ let lowerTailP = 0;
494
+ if (doLower) {
495
+ const p0 = upperAt(0);
496
+ if (!(p0 > a2)) {
497
+ let prev = p0;
498
+ let k = 1;
499
+ for (; k <= K - 1; k++) {
500
+ const p = upperAt(k);
501
+ if (p > a2)
502
+ break;
503
+ prev = p;
504
+ }
505
+ lower = A[k - 1];
506
+ lowerTailP = prev;
507
+ }
508
+ }
509
+ let upper = Infinity;
510
+ let upperTailP = 0;
511
+ if (doUpper) {
512
+ const p0 = lowerAt(0);
513
+ if (!(p0 > a2)) {
514
+ let prev = p0;
515
+ let k = K - 1;
516
+ for (; k >= 1; k--) {
517
+ const p = lowerAt(K - k);
518
+ if (p > a2)
519
+ break;
520
+ prev = p;
521
+ }
522
+ upper = A[k];
523
+ upperTailP = prev;
524
+ }
525
+ }
281
526
  return {
282
- confInt: shape(alternative, walsh[q - 1], walsh[N - q]),
283
- confLevel: notAchievable ? 1 - signif2(achieved) : confLevel,
284
- estimate: sortedMedian(walsh),
285
- estimateNames: "(pseudo)median",
527
+ confInt: [lower, upper],
528
+ confLevel: 1 - (lowerTailP + upperTailP),
529
+ estimate: sortedMedian(A),
530
+ estimateNames,
531
+ };
532
+ }
533
+ /**
534
+ * e = x - t, in half units where a finite difference overflows; an error where one is NaN (Inf - Inf at an infinite
535
+ * shift: R's statistic is then NA and R stops with "missing value where TRUE/FALSE needed")
536
+ */
537
+ function shiftedValues(x, t) {
538
+ let e = x.map((v) => v - t);
539
+ if (e.some((v) => Number.isNaN(v))) {
540
+ throw new Error("cannot compute the exact confidence interval: the shifted data have undefined values (infinite observations)");
541
+ }
542
+ if (Number.isFinite(t) && e.some((v, i) => !Number.isFinite(v) && Number.isFinite(x[i])))
543
+ e = x.map((v) => v / 2 - t / 2);
544
+ return e;
545
+ }
546
+ /**
547
+ * Exact conditional interval of the signed rank test (ties or zeros), from all observations (values equal to mu
548
+ * included). At a shift t the ranks of |x - t| over all n values are the scores (a value equal to t keeps its score
549
+ * and has a random sign), and v(t) is the sum over x - t > 0.
550
+ *
551
+ * R 4.6.2 rejects at the lower end where P(V > v) <= a' (a strict tail, where its two-sample interval uses
552
+ * P(W >= w)), which puts the lower end one Walsh average too high (for data without ties above the classical
553
+ * interval, at the same reported level) and never at -Inf. Here the lower end uses P(V >= v), and the tails reported
554
+ * for ends at A_1 or A_K are those rejected there (as for two samples, conditionalCI): the classical interval for data without ties, at the level it
555
+ * achieves (docs/differences-from-r.md)
556
+ */
557
+ function signedRankConditionalCI(x, ctx) {
558
+ const n = x.length;
559
+ const at = (t) => {
560
+ const e = shiftedValues(x, t);
561
+ const { ranks, key } = ranksAndKey(e.map(Math.abs));
562
+ let v = 0;
563
+ for (let i = 0; i < n; i++)
564
+ if (e[i] > 0)
565
+ v += ranks[i];
566
+ return { stat: v, scores: ranks, key };
286
567
  };
568
+ const K = (n * (n + 1)) / 2;
569
+ return conditionalCI(walshAverages(x), at, signedScoreDistribution, (s) => checkedCost(signedScoreCost(s), "interval"), (d, v) => upperTail(d, v - 0.25), lowerTail, { mean: K / 2, sd: Math.sqrt((n * (n + 1) * (2 * n + 1)) / 24) }, n, ctx, "(pseudo)median");
287
570
  }
288
571
  /**
289
572
  * Normal-approximation interval: the shifts d at which the standardised signed rank statistic of x - d crosses the
290
573
  * normal quantiles, and the estimate where it crosses 0 (found with uniroot, tolerance tolRoot)
291
574
  */
292
575
  function signedRankNormalCI(x, ctx) {
293
- const { alternative, correct, confLevel, tolRoot } = ctx;
576
+ const { alternative, confLevel, tolRoot } = ctx;
577
+ const correct = ctx.correct >= 0;
294
578
  const n = x.length;
295
579
  if (n === 0)
296
580
  return noInterval(alternative, NaN);
@@ -350,11 +634,10 @@ function signedRankNormalCI(x, ctx) {
350
634
  };
351
635
  }
352
636
  // ---- Two-sample (rank sum test) ----
353
- /** Rank sum statistic of x - d and y: [W, W - expectation, standard deviation] */
354
- function rankSumStat(x, y) {
355
- const nx = x.length;
356
- const ny = y.length;
357
- const r = rank([...x, ...y]);
637
+ /** Rank sum statistic from the pooled mid-ranks r (x first): [W, W - expectation, standard deviation, ties] */
638
+ function rankSumFromRanks(r, nx) {
639
+ const N = r.length;
640
+ const ny = N - nx;
358
641
  let s = 0;
359
642
  for (let i = 0; i < nx; i++)
360
643
  s += r[i];
@@ -362,20 +645,23 @@ function rankSumStat(x, y) {
362
645
  let ties = 0;
363
646
  for (const t of tieCounts(r))
364
647
  ties += t * t * t - t;
365
- const N = nx + ny;
366
648
  const sigma = Math.sqrt(((nx * ny) / 12) * (N + 1 - ties / (N * (N - 1))));
367
- return [W, W - (nx * ny) / 2, sigma];
649
+ return [W, W - (nx * ny) / 2, sigma, ties > 0];
650
+ }
651
+ /** Rank sum statistic of x - d and y: [W, W - expectation, standard deviation] */
652
+ function rankSumStat(x, y) {
653
+ const [W, dz, sigma] = rankSumFromRanks(rank([...x, ...y]), x.length);
654
+ return [W, dz, sigma];
368
655
  }
369
656
  /**
370
- * rankSumStat for x_i - d given in half units h_i = x_i / 2 - d / 2 (used where a finite x_i - d overflows, so
371
- * abs(d) >= 2^970), with whether there are ties. y stays in its own units: h_i is compared with y_j / 2, which is exact
372
- * except for a subnormal y_j, and there h_i is 0 (compared with y_j itself) or of magnitude above 2^900, so the order
373
- * is that of the differences. Halving y would merge neighbouring subnormals
657
+ * Pooled mid-ranks of x_i - d given in half units h_i = x_i / 2 - d / 2 (used where a finite x_i - d overflows, so
658
+ * abs(d) >= 2^970) and y. y stays in its own units: h_i is compared with y_j / 2, which is exact except for a
659
+ * subnormal y_j, and there h_i is 0 (compared with y_j itself) or of magnitude above 2^900, so the order is that of
660
+ * the differences. Halving y would merge neighbouring subnormals
374
661
  */
375
- function rankSumHalf(h, y) {
662
+ function pooledRanksHalf(h, y) {
376
663
  const nx = h.length;
377
- const ny = y.length;
378
- const N = nx + ny;
664
+ const N = nx + y.length;
379
665
  // sign of 2 h - v (h in half units, v in units)
380
666
  const cmpHalf = (hv, v) => {
381
667
  const w = hv === 0 || !Number.isFinite(hv) || !Number.isFinite(v) ? v : v / 2;
@@ -390,8 +676,7 @@ function rankSumHalf(h, y) {
390
676
  };
391
677
  const idx = Array.from({ length: N }, (_, i) => i);
392
678
  idx.sort((a, b) => cmp(a, b) || a - b);
393
- let s = 0;
394
- let ties = 0;
679
+ const r = new Array(N);
395
680
  let i = 0;
396
681
  while (i < N) {
397
682
  let j = i;
@@ -399,56 +684,82 @@ function rankSumHalf(h, y) {
399
684
  j++;
400
685
  const avg = (i + j + 2) / 2;
401
686
  for (let k = i; k <= j; k++)
402
- if (idx[k] < nx)
403
- s += avg;
404
- const t = j - i + 1;
405
- ties += t * t * t - t;
687
+ r[idx[k]] = avg;
406
688
  i = j + 1;
407
689
  }
408
- const W = s - (nx * (nx + 1)) / 2;
409
- const sigma = Math.sqrt(((nx * ny) / 12) * (N + 1 - ties / (N * (N - 1))));
410
- return [W, W - (nx * ny) / 2, sigma, ties > 0];
690
+ return r;
691
+ }
692
+ /**
693
+ * Pooled mid-ranks of (x - d, y), in half units where a finite x_i - d overflows. An x_i - d that is NaN (Inf - Inf,
694
+ * at an infinite shift of the conditional interval's search) is ranked after all others, in order, as R's rank does
695
+ * there (na.last = TRUE)
696
+ */
697
+ function pooledRanks(x, y, d) {
698
+ return pooledRanksAndKey(x, y, d).ranks;
699
+ }
700
+ /** pooledRanks with the key of their multiset (ranksAndKey's, or the sorted ranks on the rare paths) */
701
+ function pooledRanksAndKey(x, y, d) {
702
+ const e = x.map((v) => v - d);
703
+ if (e.some((v) => Number.isNaN(v))) {
704
+ const keep = e.map((v, i) => [v, i]).filter(([v]) => !Number.isNaN(v));
705
+ const rk = rank([...keep.map(([v]) => v), ...y]);
706
+ const r = new Array(x.length + y.length);
707
+ keep.forEach(([, i], k) => (r[i] = rk[k]));
708
+ y.forEach((_, j) => (r[x.length + j] = rk[keep.length + j]));
709
+ let next = keep.length + y.length;
710
+ e.forEach((v, i) => {
711
+ if (Number.isNaN(v))
712
+ r[i] = ++next;
713
+ });
714
+ return { ranks: r, key: scoreKey(r) };
715
+ }
716
+ if (Number.isFinite(d) && e.some((v, i) => !Number.isFinite(v) && Number.isFinite(x[i]))) {
717
+ const r = pooledRanksHalf(x.map((v) => v / 2 - d / 2), y);
718
+ return { ranks: r, key: scoreKey(r) };
719
+ }
720
+ return ranksAndKey([...e, ...y]);
411
721
  }
412
722
  function rankSum(x, y, exactOpt, ctx) {
413
- const { alternative, mu, correct } = ctx;
723
+ const { alternative, mu } = ctx;
414
724
  const nx = x.length;
415
725
  const ny = y.length;
416
- let xs = x.map((v) => v - mu);
417
726
  const exact = exactOpt ?? (nx < 50 && ny < 50);
418
- // A finite x_i - mu that overflows: ranked from x / 2 - mu / 2 against y (see rankSumHalf)
419
- const halved = xs.some((v, i) => !Number.isFinite(v) && Number.isFinite(x[i]));
420
- let ties;
421
- let W, dz, sigma;
422
- if (halved) {
423
- xs = x.map((v) => v / 2 - mu / 2);
424
- [W, dz, sigma, ties] = rankSumHalf(xs, y);
425
- }
426
- else {
427
- ties = tieCounts([...xs, ...y]).length > 0;
428
- [W, dz, sigma] = rankSumStat(xs, y);
429
- }
727
+ const r = pooledRanks(x, y, mu);
728
+ const [W, dz, sigma, ties] = rankSumFromRanks(r, nx);
430
729
  let pValue;
431
730
  let method;
432
- const useExact = exact && !ties;
433
- if (useExact) {
731
+ if (exact) {
434
732
  method = "Wilcoxon rank sum exact test";
435
- pValue = rankSumExact(() => {
733
+ if (!ties) {
734
+ pValue = rankSumExact(() => {
735
+ if (alternative === "less")
736
+ return pwilcox1(W, nx, ny, true, false);
737
+ if (alternative === "greater")
738
+ return pwilcox1(W - 1, nx, ny, false, false);
739
+ // R 4.6: both tails, not the one on the side of the statistic
740
+ return Math.min(2 * pwilcox1(W, nx, ny, true, false), 2 * pwilcox1(W - 1, nx, ny, false, false), 1);
741
+ });
742
+ }
743
+ else {
744
+ checkedCost(rankSumScoreCost(r, nx), "distribution");
745
+ const dist = rankSumScoreDistribution(r, nx);
436
746
  if (alternative === "less")
437
- return pwilcox1(W, nx, ny, true, false);
438
- if (alternative === "greater")
439
- return pwilcox1(W - 1, nx, ny, false, false);
440
- const p = W > (nx * ny) / 2
441
- ? pwilcox1(W - 1, nx, ny, false, false)
442
- : pwilcox1(W, nx, ny, true, false);
443
- return Math.min(1, 2 * p);
444
- });
747
+ pValue = lowerTail(dist, W);
748
+ else if (alternative === "greater")
749
+ pValue = upperTail(dist, W - 0.25);
750
+ else
751
+ pValue = Math.min(2 * lowerTail(dist, W), 2 * upperTail(dist, W - 0.25), 1);
752
+ }
445
753
  }
446
754
  else {
447
- method = `Wilcoxon rank sum test${correct ? " with continuity correction" : ""}`;
448
- // all values tied: W always equals its expectation, so p = 1 (R 4.5.2: 0 / 0 = NaN two-sided; R 4.6 returns 1)
449
- // (never with half units: an overflowing difference equals no y)
450
- const allTied = !halved && xs.every((v) => v === y[0]) && y.every((v) => v === y[0]);
451
- pValue = allTied ? 1 : normalP((dz - correction(dz, alternative, correct)) / sigma, alternative);
755
+ method = `Wilcoxon rank sum test${ctx.correct >= 0 ? " with continuity correction" : ""}`;
756
+ // the Edgeworth terms only without ties (R)
757
+ const terms = ties ? Math.min(ctx.correct, 0) : ctx.correct;
758
+ // all values tied: W always equals its expectation, so p = 1 (R: 0 / 0 = NaN, also R 4.6 with exact = FALSE; its
759
+ // exact conditional test, the default for small samples, gives 1 too)
760
+ const allTied = r.every((v) => v === r[0]);
761
+ const z = (dz - correction(dz, alternative, terms >= 0)) / sigma;
762
+ pValue = allTied ? 1 : normalP(z, alternative, terms >= 1 ? edgeworthRankSum(z, nx, ny, terms) : 0);
452
763
  }
453
764
  const result = {
454
765
  method,
@@ -460,13 +771,13 @@ function rankSum(x, y, exactOpt, ctx) {
460
771
  nullValueName: "location shift",
461
772
  warnings: ctx.warnings.list,
462
773
  };
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
- }
774
+ if (!ctx.confInt)
775
+ return result;
776
+ const ci = !exact
777
+ ? rankSumNormalCI(x, y, ctx)
778
+ : ties
779
+ ? rankSumConditionalCI(x, y, ctx)
780
+ : rankSumExact(() => rankSumExactCI(x, y, ctx));
470
781
  return { ...result, ...ci };
471
782
  }
472
783
  /**
@@ -483,37 +794,48 @@ function rankSumExact(f) {
483
794
  throw e;
484
795
  }
485
796
  }
486
- /** Exact interval from the order statistics of the differences x_i - y_j and their median as the estimate */
797
+ /** Sorted differences x_i - y_j */
798
+ function differences(x, y, dropNaN) {
799
+ const diffs = [];
800
+ for (const xi of x) {
801
+ for (const yj of y) {
802
+ const d = xi - yj;
803
+ if (!(dropNaN && Number.isNaN(d)))
804
+ diffs.push(d);
805
+ }
806
+ }
807
+ return diffs.sort(ascending);
808
+ }
809
+ /** Classical exact interval from the order statistics of the differences x_i - y_j; the estimate their median */
487
810
  function rankSumExactCI(x, y, ctx) {
488
- const { alternative, confLevel } = ctx;
489
811
  const nx = x.length;
490
812
  const ny = y.length;
491
- const diffs = [];
492
- for (const xi of x)
493
- for (const yj of y)
494
- diffs.push(xi - yj);
495
- diffs.sort(ascending);
496
- const M = diffs.length;
497
- const a = 1 - confLevel;
498
- const q = exactRank((p) => qwilcox1(p, nx, ny, true, false), alternative, a);
499
- const tail = pwilcox1(q - 1, nx, ny, true, false);
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");
504
- return {
505
- confInt: shape(alternative, diffs[q - 1], diffs[M - q]),
506
- confLevel: notAchievable ? 1 - achieved : confLevel,
507
- estimate: sortedMedian(diffs),
508
- estimateNames: "difference in location",
813
+ return orderStatisticCI(differences(x, y, false), (q) => pwilcox1(q, nx, ny, true, false), (p) => qwilcox1(p, nx, ny, true, false), ctx, "difference in location");
814
+ }
815
+ /**
816
+ * Exact conditional interval of the rank sum test (ties), as R 4.6: at a shift t the pooled mid-ranks of (x - t, y)
817
+ * are the scores and w(t) the statistic; the lower end from P(W >= w), the upper from P(W <= w). An end at the first
818
+ * or last difference with the tail rejected there, where R 4.6.2 reports 0 (see conditionalCI)
819
+ */
820
+ function rankSumConditionalCI(x, y, ctx) {
821
+ const nx = x.length;
822
+ const ny = y.length;
823
+ const at = (t) => {
824
+ const { ranks, key } = pooledRanksAndKey(x, y, t);
825
+ let w = 0;
826
+ for (let i = 0; i < nx; i++)
827
+ w += ranks[i];
828
+ return { stat: w - (nx * (nx + 1)) / 2, scores: ranks, key };
509
829
  };
830
+ return conditionalCI(differences(x, y, true), at, (s) => rankSumScoreDistribution(s, nx), (s) => checkedCost(rankSumScoreCost(s, nx), "interval"), (d, w) => upperTail(d, w - 0.25), lowerTail, { mean: (nx * ny) / 2, sd: Math.sqrt((nx * ny * (nx + ny + 1)) / 12) }, nx + ny, ctx, "difference in location");
510
831
  }
511
832
  /**
512
833
  * Normal-approximation interval: the shifts d at which the standardised rank sum statistic of (x - d, y) crosses the
513
834
  * normal quantiles (clamped to the range of the differences), and the estimate where it crosses 0
514
835
  */
515
836
  function rankSumNormalCI(x, y, ctx) {
516
- const { alternative, correct, confLevel, tolRoot } = ctx;
837
+ const { alternative, confLevel, tolRoot } = ctx;
838
+ const correct = ctx.correct >= 0;
517
839
  const lo = minOf(x) - maxOf(y);
518
840
  const hi = maxOf(x) - minOf(y);
519
841
  if (!Number.isFinite(lo) || !Number.isFinite(hi)) {