@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,6 +1,12 @@
1
1
  export { lmer, type LmerContrastName, type LmerOptions, type LmerResult, type LmerVarCorr, type LmerRanef } from "../models/lmer.js";
2
2
  export { lmerContest, lmerSummary, type LmerContestF, type LmerContestOptions, type LmerContestT, type LmerSummary, type LmerSummaryOptions, } from "../models/lmerTest.js";
3
3
  export { lmerAnova, type LmerAnovaOptions, type LmerAnovaTable, type LmerAnovaType, type LmerCompareOptions, type LmerCompareTable, } from "../models/lmerAnova.js";
4
+ export { glmer, type GlmerOptions, type GlmerResult } from "../models/glmer.js";
5
+ export { glmerSummary, type GlmerSummary, type GlmerSummaryOptions } from "../models/glmerSummary.js";
6
+ export { glmerAnova, type GlmerAnovaOptions, type GlmerAnovaTable } from "../models/glmerAnova.js";
7
+ export { glmerPredict, lmerPredict, type GlmerPredictOptions, type LmerPredictOptions, type MixedPrediction, } from "../models/mixedPredict.js";
8
+ export type { GlmerFamilyName } from "../models/glmerFamily.js";
4
9
  export type { DataFrame } from "../models/modelFrame.js";
5
10
  export type { ContrastName } from "../models/modelMatrix.js";
11
+ export type { GlmLinkName } from "../models/glmFamily.js";
6
12
  export { setWarningHandler, type WarningHandler } from "../internal/warnings.js";
@@ -1,7 +1,12 @@
1
1
  // Mixed models (rStats.js/mixed): linear mixed models fitted by REML or maximum likelihood, as lme4's lmer, lmerTest's
2
- // Satterthwaite t- and F-tests and ANOVA tables of their fixed effects, and the likelihood-ratio comparison of fits
2
+ // Satterthwaite t- and F-tests and ANOVA tables of their fixed effects, the likelihood-ratio comparison of fits, and
3
+ // generalized linear mixed models, as lme4's glmer, and the predictions of both
3
4
  export { lmer } from "../models/lmer.js";
4
5
  export { lmerContest, lmerSummary, } from "../models/lmerTest.js";
5
6
  export { lmerAnova, } from "../models/lmerAnova.js";
7
+ export { glmer } from "../models/glmer.js";
8
+ export { glmerSummary } from "../models/glmerSummary.js";
9
+ export { glmerAnova } from "../models/glmerAnova.js";
10
+ export { glmerPredict, lmerPredict, } from "../models/mixedPredict.js";
6
11
  // The handler of R's warnings that the tests, models and fits return (also exported from the root and /distributions)
7
12
  export { setWarningHandler } from "../internal/warnings.js";
@@ -20,7 +20,7 @@ export { pairwiseTTest, pairwiseWilcoxTest, pairwisePropTest, type PairwiseResul
20
20
  export { aov, TukeyHSD, zTest, type TukeyHSDOptions, type TukeyHSDResult, type ZTestOptions } from "../htest/aov.js";
21
21
  export type { GroupLabel } from "../htest/groups.js";
22
22
  export { lm, confint, predict, type LmOptions, type LmResult, type ConfintOptions, type PredictOptions } from "../models/lm.js";
23
- export { glm, glmSummary, glmResiduals, glmHatvalues, glmRstandard, glmCooksDistance, glmPredict, type GlmOptions, type GlmResult, type GlmModel, type GlmSummary, type GlmSummaryOptions, type GlmResidualType, type GlmResidualsOptions, type GlmPredictOptions, type GlmFamilyName, type GlmFamilySpec, type GlmLink, type GlmLinkName, type QuasiVariance, } from "../models/glm.js";
23
+ export { glm, glmSummary, glmResiduals, glmHatvalues, glmRstandard, glmCooksDistance, glmPredict, type GlmOptions, type GlmResult, type GlmModel, type GlmSummary, type GlmSummaryOptions, type GlmRstandardOptions, type GlmResidualType, type GlmResidualsOptions, type GlmPredictOptions, type GlmFamilyName, type GlmFamilySpec, type GlmLink, type GlmLinkName, type QuasiVariance, } from "../models/glm.js";
24
24
  export { glmConfint, type GlmConfintOptions } from "../models/glmConfint.js";
25
25
  export { glmAnova, type GlmAnovaOptions, type GlmAnovaResult, type GlmAnovaTest } from "../models/glmAnova.js";
26
26
  export { modelMatrix, type ModelMatrixOptions, type ModelMatrixResult, type ContrastName, } from "../models/modelMatrix.js";
@@ -4,15 +4,15 @@
4
4
  // Scores min(r, N + 1 - r) of the pooled ranks r (average ranks for ties); the statistic is the sum over the first
5
5
  // sample. Small samples without ties use the exact null distribution (src/htest/core/ansari.ts); the two-sided
6
6
  // p-value doubles the tail on the statistic's side of the centre floor((m+1)^2/4) + floor(m n / 2)/2 (the centre
7
- // follows R's ansari.test behaviour). Otherwise the statistic is standardised and compared with the normal, with Ansari
8
- // and Bradley's mean and the variance of a linear rank statistic from the observed sum of squared scores (the form
9
- // scipy.stats.ansari also uses).
7
+ // follows R's ansari.test behaviour). Otherwise the statistic is standardised and compared with the normal: without ties
8
+ // with Ansari and Bradley's mean and variance, with ties (as R 4.6) with the mean and variance of a sum of m of the
9
+ // observed scores drawn without replacement (R 4.5 and scipy.stats.ansari keep the no-ties mean).
10
10
  //
11
11
  // Interval and estimate (Bauer, JASA 67, 1972, section 5): with the locations taken as 0, AB(s) is the statistic of
12
12
  // x / s against y, a step function of the ratio of scales s. Exact: AB(s) is evaluated between consecutive
13
13
  // candidate ratios x_i / y_j >= 0 (and beyond the largest), and the limits are the candidate ratios where it crosses
14
14
  // the exact quantiles; the estimate is the midpoint of the crossing of the median. Normal approximation: the limits and
15
- // the estimate are where the standardised AB(s) (standardised as for the test: R 4.5.2's ansari.test) crosses the normal
15
+ // the estimate are where the standardised AB(s) (standardised as for the test, as R 4.6's ansari.test) crosses the normal
16
16
  // quantiles (and 0), found with R's uniroot conventions (tolerance 1e-4) in the range of the ratios of the positive
17
17
  // values and of the negative values. The candidate sets, evaluation points, search range, tolerance and the cases
18
18
  // returned as NaN (R's NA) follow R's documented and observed behaviour.
@@ -79,17 +79,7 @@ export function ansariTest(x, y, options = {}) {
79
79
  ci = exactInterval(xs, ys, alternative, confLevel, warnings);
80
80
  }
81
81
  else {
82
- // mean and variance with the sum of the scores at its value without ties (N (N + 2) / 4 for even N,
83
- // (N + 1)^2 / 4 for odd N), and the sum of their squares as observed
84
- let sq = 0;
85
- for (const v of a)
86
- sq += v * v;
87
- const even = N % 2 === 0;
88
- const mean = even ? (m * (N + 2)) / 4 : (m * (N + 1) ** 2) / (4 * N);
89
- const variance = even
90
- ? (m * n * (16 * sq - N * (N + 2) ** 2)) / (16 * N * (N - 1))
91
- : (m * n * (16 * N * sq - (N + 1) ** 4)) / (16 * N * N * (N - 1));
92
- const z = (statistic - mean) / Math.sqrt(variance);
82
+ const z = normalized(statistic, a, ties, m, n);
93
83
  // large AB means the first sample is concentrated in the middle: smaller scale
94
84
  pValue =
95
85
  alternative === "two.sided"
@@ -102,8 +92,9 @@ export function ansariTest(x, y, options = {}) {
102
92
  ci = normalInterval(xs, ys, alternative, confLevel, exactR ? new Warnings() : warnings);
103
93
  if (exactR && ties) {
104
94
  warnings.add("cannot compute exact p-value with ties");
95
+ // (R 4.6's text: "interval", where R 4.5 had "intervals")
105
96
  if (confInt)
106
- warnings.add("cannot compute exact confidence intervals with ties");
97
+ warnings.add("cannot compute exact confidence interval with ties");
107
98
  }
108
99
  }
109
100
  const result = {
@@ -124,6 +115,30 @@ export function ansariTest(x, y, options = {}) {
124
115
  result.nullValueName = "ratio of scales";
125
116
  return reported("ansariTest", result);
126
117
  }
118
+ /**
119
+ * The AB statistic standardized for the normal approximation. Without ties, with the moments of the scores of distinct
120
+ * ranks. With ties (as R 4.6), with those of the observed scores a of all N observations: mean m mean(a) and variance
121
+ * m n var(a) / N (var with the denominator N - 1), the variance of the sum of m scores drawn without replacement
122
+ */
123
+ function normalized(ab, a, ties, m, n) {
124
+ const N = m + n;
125
+ if (!ties) {
126
+ const even = N % 2 === 0;
127
+ const centred = even ? ab - (m * (N + 2)) / 4 : ab - (m * (N + 1) ** 2) / (4 * N);
128
+ const sd = even
129
+ ? Math.sqrt((m * n * (N + 2) * (N - 2)) / (48 * (N - 1)))
130
+ : Math.sqrt((m * n * (N + 1) * (3 + N * N)) / (48 * N * N));
131
+ return centred / sd;
132
+ }
133
+ let sum = 0;
134
+ for (const v of a)
135
+ sum += v;
136
+ const mean = sum / N;
137
+ let ss = 0;
138
+ for (const v of a)
139
+ ss += (v - mean) ** 2;
140
+ return (ab - m * mean) / Math.sqrt((m * n * (ss / (N - 1))) / N);
141
+ }
127
142
  /** AB statistic of x / s against y, with the scores of all observations and whether there are ties */
128
143
  function scaledStatistic(xs, ys, s) {
129
144
  const m = xs.length;
@@ -274,26 +289,9 @@ function exactInterval(xs, ys, alternative, confLevel, warnings) {
274
289
  function normalInterval(xs, ys, alternative, confLevel, warnings) {
275
290
  const m = xs.length;
276
291
  const n = ys.length;
277
- const N = m + n;
278
- const even = N % 2 === 0;
279
292
  const z = (s, zq) => {
280
293
  const { ab, a, ties } = scaledStatistic(xs, ys, s);
281
- const centred = even ? ab - (m * (N + 2)) / 4 : ab - (m * (N + 1) ** 2) / (4 * N);
282
- let sd;
283
- if (!ties) {
284
- sd = even
285
- ? Math.sqrt((m * n * (N + 2) * (N - 2)) / (48 * (N - 1)))
286
- : Math.sqrt((m * n * (N + 1) * (3 + N * N)) / (48 * N * N));
287
- }
288
- else {
289
- let sq = 0;
290
- for (const v of a)
291
- sq += v * v;
292
- sd = even
293
- ? Math.sqrt((m * n * (16 * sq - N * (N + 2) ** 2)) / (16 * N * (N - 1)))
294
- : Math.sqrt((m * n * (16 * N * sq - (N + 1) ** 4)) / (16 * N * N * (N - 1)));
295
- }
296
- return centred / sd - zq;
294
+ return normalized(ab, a, ties, m, n) - zq;
297
295
  };
298
296
  // search range: the ratios of the positive values, and of the non-positive x to the negative y
299
297
  const ends = [];
@@ -94,8 +94,8 @@ export declare function kendall(x: readonly number[], y: readonly number[]): Ken
94
94
  * value is less accurate.
95
95
  *
96
96
  * As R, `warnings` has "the standard deviation is zero" where x or y is constant (the correlation is `NaN`), and
97
- * "Cannot compute exact p-value with ties" where Kendall's or Spearman's exact p-value is asked for or the default
98
- * but there are ties (the approximation is used), and "NaNs produced" where Spearman's t approximation has 2 pairs
97
+ * "cannot compute exact p-value with ties" (R 4.6's text) where Kendall's or Spearman's exact p-value is asked for or
98
+ * the default but there are ties (the approximation is used), and "NaNs produced" where Spearman's t approximation has 2 pairs
99
99
  * (0 degrees of freedom: the p-value is `NaN`).
100
100
  *
101
101
  * @param x First sample.
package/dist/htest/cor.js CHANGED
@@ -443,7 +443,8 @@ const SD_ZERO = "the standard deviation is zero";
443
443
  /** R's warning of pt where the p-value is NaN (Spearman's t approximation with n = 2) */
444
444
  const NANS = "NaNs produced";
445
445
  /** R's warning where the exact p-value cannot be used because of ties */
446
- const TIES = "Cannot compute exact p-value with ties";
446
+ // (lower case since R 4.6, as the other tests' warning; R 4.5: "Cannot ...")
447
+ const TIES = "cannot compute exact p-value with ties";
447
448
  /** Whether all values are equal and finite */
448
449
  function finiteConstant(v) {
449
450
  return Number.isFinite(v[0]) && v.every((a) => a === v[0]);
@@ -0,0 +1,39 @@
1
+ /** Probability function of a statistic on the grid offset, offset + 1 / f, ..., with both cumulative tails */
2
+ export interface ScoreDistribution {
3
+ /** 1 or 2: the grid step of the statistic is 1 / f */
4
+ f: number;
5
+ /** Statistic at index 0 */
6
+ offset: number;
7
+ /** lower[i] = P(index <= i) */
8
+ lower: Float64Array;
9
+ /** upper[i] = P(index >= i) */
10
+ upper: Float64Array;
11
+ }
12
+ /** Largest table (doubles in one array; CONTRIBUTING rule 4) */
13
+ export declare const MAX_SCORE_TABLE: number;
14
+ /** Key of the multiset of scores (for caching distributions) */
15
+ export declare function scoreKey(scores: readonly number[]): string;
16
+ /** Steps and table length of signedScoreDistribution for these scores */
17
+ export declare function signedScoreCost(scores: readonly number[]): {
18
+ steps: number;
19
+ size: number;
20
+ };
21
+ /** Distribution of the sum of the scores with random signs (the scores counted with probability 1/2 each) */
22
+ export declare function signedScoreDistribution(scores: readonly number[]): ScoreDistribution;
23
+ /** Steps and largest row of rankSumScoreDistribution for these scores and first-sample size m */
24
+ export declare function rankSumScoreCost(scores: readonly number[], m: number): {
25
+ steps: number;
26
+ size: number;
27
+ };
28
+ /**
29
+ * Distribution of W = (sum of the scores of a random m-subset) - m (m + 1) / 2, the rank sum statistic given the
30
+ * pooled scores
31
+ */
32
+ export declare function rankSumScoreDistribution(scores: readonly number[], m: number): ScoreDistribution;
33
+ /** P(S < q + 1e-8), at most 1 (R's tail convention for the conditional distributions) */
34
+ export declare function lowerTail(d: ScoreDistribution, q: number): number;
35
+ /**
36
+ * P(S >= q + 1e-8): as R 4.6.2, 1 - P(S < q + 1e-8), except within 1/64 of the upper end of the lower tail (R's
37
+ * absolute threshold), where it is summed directly and keeps the digits of a small upper tail
38
+ */
39
+ export declare function upperTail(d: ScoreDistribution, q: number): number;
@@ -0,0 +1,151 @@
1
+ // Exact permutation distributions of sums of scores, for the conditional (tied or Pratt) exact Wilcoxon tests of
2
+ // wilcoxTest.
3
+ //
4
+ // Written for rStats.js from the definitions (the conditional distributions that Streitberg and Röhmel's shift
5
+ // algorithm computes, JASA 81, 1986; no ported code). The scores are mid-ranks, multiples of 1/2; with f = 1 when all
6
+ // are integers and f = 2 otherwise, the integer scores a_j = f score_j index the table.
7
+ // - Signed rank: each score is counted with probability 1/2, independently. The probability function of the sum is
8
+ // the coefficient list of prod_j (1 + t^{a_j}) / 2, built one factor at a time with the halving in each step, so
9
+ // that the entries stay probabilities (2^-k for k scores, exact for dyadic cases) and nothing overflows.
10
+ // - Rank sum: the m positions of the first sample are a uniformly random m-subset of the N scores. After the first i
11
+ // scores (ascending), P_i(j, s), the probability that a random j-subset of them sums to s, follows
12
+ // P_i(j, s) = (j / i) P_{i-1}(j - 1, s - a_i) + ((i - j) / i) P_{i-1}(j, s): convex combinations of probabilities,
13
+ // so no counts (C(100, 50) = 1e29) and no cancellation. Only k = min(m, N - m) rows are needed (the other sample's
14
+ // sum is the total minus this one), and a row j only while it can still reach k.
15
+ // Tails are cumulative sums of positive terms from either end, so small upper tails keep their digits (R's 1 - lower
16
+ // tail elsewhere).
17
+ /** Largest table (doubles in one array; CONTRIBUTING rule 4) */
18
+ export const MAX_SCORE_TABLE = 2 ** 24;
19
+ /** f and the integer scores f score_j, ascending */
20
+ function integerScores(scores) {
21
+ const f = scores.every((s) => Number.isInteger(s)) ? 1 : 2;
22
+ return [f, scores.map((s) => s * f).sort((a, b) => a - b)];
23
+ }
24
+ /** Key of the multiset of scores (for caching distributions) */
25
+ export function scoreKey(scores) {
26
+ return [...scores].sort((a, b) => a - b).join(",");
27
+ }
28
+ function withTails(f, offset, p) {
29
+ const len = p.length;
30
+ const lower = new Float64Array(len);
31
+ const upper = new Float64Array(len);
32
+ let s = 0;
33
+ for (let i = 0; i < len; i++)
34
+ lower[i] = s += p[i];
35
+ s = 0;
36
+ for (let i = len - 1; i >= 0; i--)
37
+ upper[i] = s += p[i];
38
+ return { f, offset, lower, upper };
39
+ }
40
+ /** Steps and table length of signedScoreDistribution for these scores */
41
+ export function signedScoreCost(scores) {
42
+ const [, a] = integerScores(scores);
43
+ let cur = 0;
44
+ let steps = 0;
45
+ for (const v of a)
46
+ steps += cur += v;
47
+ return { steps, size: cur + 1 };
48
+ }
49
+ /** Distribution of the sum of the scores with random signs (the scores counted with probability 1/2 each) */
50
+ export function signedScoreDistribution(scores) {
51
+ const [f, a] = integerScores(scores);
52
+ let total = 0;
53
+ for (const v of a)
54
+ total += v;
55
+ const p = new Float64Array(total + 1);
56
+ p[0] = 1;
57
+ let cur = 0;
58
+ for (const v of a) {
59
+ cur += v;
60
+ for (let s = cur; s >= v; s--)
61
+ p[s] = 0.5 * (p[s] + p[s - v]);
62
+ for (let s = v - 1; s >= 0; s--)
63
+ p[s] = 0.5 * p[s];
64
+ }
65
+ return withTails(f, 0, p);
66
+ }
67
+ /** Steps and largest row of rankSumScoreDistribution for these scores and first-sample size m */
68
+ export function rankSumScoreCost(scores, m) {
69
+ const [, a] = integerScores(scores);
70
+ const N = a.length;
71
+ const k = Math.min(m, N - m);
72
+ const pre = prefix(a);
73
+ let steps = 0;
74
+ for (let i = 1; i <= N; i++) {
75
+ for (let j = Math.max(1, k - (N - i)); j <= Math.min(i, k); j++)
76
+ steps += pre[i] - pre[i - j] - pre[j] + 1;
77
+ }
78
+ return { steps, size: pre[N] - pre[N - k] - pre[k] + 1 };
79
+ }
80
+ function prefix(a) {
81
+ const pre = [0];
82
+ for (const v of a)
83
+ pre.push(pre[pre.length - 1] + v);
84
+ return pre;
85
+ }
86
+ /**
87
+ * Distribution of W = (sum of the scores of a random m-subset) - m (m + 1) / 2, the rank sum statistic given the
88
+ * pooled scores
89
+ */
90
+ export function rankSumScoreDistribution(scores, m) {
91
+ const [f, a] = integerScores(scores);
92
+ const N = a.length;
93
+ const k = Math.min(m, N - m);
94
+ const pre = prefix(a);
95
+ // row j: sums of j-subsets, from pre[j] (the j smallest) to the sum of the j largest
96
+ const rows = [];
97
+ for (let j = 0; j <= k; j++)
98
+ rows.push(new Float64Array(pre[N] - pre[N - j] - pre[j] + 1));
99
+ rows[0][0] = 1;
100
+ for (let i = 1; i <= N; i++) {
101
+ const ai = a[i - 1];
102
+ for (let j = Math.min(i, k); j >= Math.max(1, k - (N - i)); j--) {
103
+ const row = rows[j];
104
+ const prev = rows[j - 1];
105
+ const wNew = j / i;
106
+ const wOld = (i - j) / i;
107
+ const lo = pre[j];
108
+ const hi = pre[i] - pre[i - j];
109
+ // P_{i-1}(j - 1, .) lives on [pre[j - 1], pre[i - 1] - pre[i - j]], so s - a_i on [pre[j - 1] + a_i, hi]
110
+ const shift = pre[j - 1] + ai;
111
+ const from = Math.max(lo, shift);
112
+ for (let s = hi; s >= from; s--)
113
+ row[s - lo] = wOld * row[s - lo] + wNew * prev[s - shift];
114
+ for (let s = from - 1; s >= lo; s--)
115
+ row[s - lo] = wOld * row[s - lo];
116
+ }
117
+ }
118
+ const row = rows[k];
119
+ const base = (m * (m + 1)) / 2;
120
+ if (k === m)
121
+ return withTails(f, pre[k] / f - base, row);
122
+ // the subsets were of the other sample: the first sample's sum is the total minus theirs (reversed)
123
+ const len = row.length;
124
+ const rev = new Float64Array(len);
125
+ for (let i = 0; i < len; i++)
126
+ rev[i] = row[len - 1 - i];
127
+ const hiK = pre[N] - pre[N - k];
128
+ return withTails(f, (pre[N] - hiK) / f - base, rev);
129
+ }
130
+ /** P(S < q + 1e-8), at most 1 (R's tail convention for the conditional distributions) */
131
+ export function lowerTail(d, q) {
132
+ const last = Math.ceil(d.f * (q - d.offset) + d.f * 1e-8) - 1;
133
+ if (last < 0)
134
+ return 0;
135
+ if (last >= d.lower.length)
136
+ return 1;
137
+ return Math.min(1, d.lower[last]);
138
+ }
139
+ /**
140
+ * P(S >= q + 1e-8): as R 4.6.2, 1 - P(S < q + 1e-8), except within 1/64 of the upper end of the lower tail (R's
141
+ * absolute threshold), where it is summed directly and keeps the digits of a small upper tail
142
+ */
143
+ export function upperTail(d, q) {
144
+ const L = lowerTail(d, q);
145
+ if (Math.abs(L - 1) >= 1 / 64)
146
+ return 1 - L;
147
+ const first = Math.ceil(d.f * (q - d.offset) + d.f * 1e-8);
148
+ if (first >= d.upper.length)
149
+ return 0;
150
+ return Math.min(1, d.upper[Math.max(0, first)]);
151
+ }
@@ -16,13 +16,26 @@ export interface WilcoxTestOptions {
16
16
  /** Paired test (signed rank test on `x - y`). Requires `y`. Default `false`. */
17
17
  paired?: boolean;
18
18
  /**
19
- * Compute an exact p-value. Default `null`: exact when the sample size is below 50 (both
20
- * samples, for two samples). Even with `true`, the normal approximation is used when
21
- * there are ties or zero differences, as in R.
19
+ * Compute an exact p-value (and interval). Default `null`: exact when the sample size is below 50 (both samples,
20
+ * for two samples; zero differences count). With ties or zero differences the exact test is the conditional
21
+ * (permutation) test given the mid-ranks, as in R 4.6; the signed rank test then ranks the zeros with the other
22
+ * differences and leaves them out of the permutation distribution (Pratt).
23
+ *
24
+ * The conditional distribution is built once for the p-value and again for each multiset of scores that the
25
+ * interval's search meets. Where that would take more than about 8 seconds, a RangeError suggesting `exact: false`
26
+ * is thrown before the computation. Measured on a Mac mini (Apple M1, Node 24) with data rounded to one or two
27
+ * decimals: the p-value up to about n = 2400 (one sample) and m = n = 320 (two samples); the interval up to about
28
+ * n = 150 to 300 (one sample; 4 s at n = 150 with 3 decimals, 4.6 s at n = 300 with 1) and m = n = 80 (two samples;
29
+ * 49 x 49 takes 3 s). Ties in few places (or none) cost less.
22
30
  */
23
31
  exact?: boolean | null;
24
- /** Apply a continuity correction in the normal approximation. Default `true`. */
25
- correct?: boolean;
32
+ /**
33
+ * Continuity correction of the normal approximation. Default `true`. As in R 4.6, also `0` (the same as `true`) or
34
+ * `1`, `2`, `3`: the continuity correction plus that many Edgeworth terms in the p-value (only without ties and zero
35
+ * differences; with them, the continuity correction only). The interval and estimate use the continuity correction
36
+ * alone. Any other number throws.
37
+ */
38
+ correct?: boolean | 0 | 1 | 2 | 3;
26
39
  /** Compute a confidence interval and the Hodges-Lehmann estimate. Default `false`. */
27
40
  confInt?: boolean;
28
41
  /** Confidence level of the interval. Default `0.95`. */
@@ -46,9 +59,11 @@ export interface WilcoxTestResult extends HTest {
46
59
  *
47
60
  * With one sample (or `paired: true`) performs the signed rank test; with two samples the
48
61
  * rank sum test. The choice between exact and normal-approximation p-values, the
49
- * Hodges-Lehmann estimates and the confidence intervals follow R, including R's behavior
50
- * when the requested confidence level cannot be reached. Only `NaN` is dropped; infinite
51
- * values are kept and ranked (as R actually does).
62
+ * Hodges-Lehmann estimates and the confidence intervals follow R 4.6: with ties or zeros the
63
+ * exact test is the conditional test given the mid-ranks, and an exact interval reports the
64
+ * confidence level it achieves. Only `NaN` is dropped; infinite values are kept and ranked (as
65
+ * R actually does). Where R 4.6.2 is wrong, the one-sample conditional interval and small
66
+ * two-sided normal p-values, see docs/differences-from-r.md.
52
67
  *
53
68
  * @param x Sample.
54
69
  * @param y Second sample for a two-sample or paired test. May be omitted, and the options