@numero-uno-jpn/rstats 0.15.3 → 0.16.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 (285) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/README.ja.md +40 -33
  3. package/README.md +36 -28
  4. package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
  5. package/dist/chunks/chunk-5UQCRBAG.js +2 -0
  6. package/dist/chunks/chunk-6CSTWA5E.js +2 -0
  7. package/dist/chunks/chunk-72Y3HZID.js +2 -0
  8. package/dist/chunks/chunk-BG2KLEHM.js +2 -0
  9. package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
  10. package/dist/chunks/chunk-FLJNSXSW.js +2 -0
  11. package/dist/chunks/chunk-GM53LWSR.js +2 -0
  12. package/dist/chunks/chunk-JBCA56ZS.js +3 -0
  13. package/dist/chunks/chunk-K3RJAD2T.js +2 -0
  14. package/dist/chunks/chunk-KAZRWIB5.js +2 -0
  15. package/dist/chunks/chunk-KBVVIMXX.js +3 -0
  16. package/dist/chunks/chunk-N3SIFCZX.js +2 -0
  17. package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
  18. package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
  19. package/dist/chunks/chunk-SYWOBOTR.js +2 -0
  20. package/dist/chunks/chunk-URIO5LY5.js +2 -0
  21. package/dist/chunks/chunk-VTUGG2SV.js +2 -0
  22. package/dist/chunks/chunk-W26LRYOJ.js +2 -0
  23. package/dist/chunks/chunk-XHETEYVC.js +2 -0
  24. package/dist/chunks/{chunk-VLUL2HFW.js → chunk-YRZWONZB.js} +1 -1
  25. package/dist/chunks/chunk-ZGABZMWX.js +2 -0
  26. package/dist/data/grouping.js +20 -5
  27. package/dist/descriptive/basic.js +90 -8
  28. package/dist/descriptive/cov.js +12 -4
  29. package/dist/descriptive/dataFrames.d.ts +4 -2
  30. package/dist/descriptive/dataFrames.js +56 -18
  31. package/dist/descriptive/factanal.js +16 -7
  32. package/dist/descriptive/hist.d.ts +8 -5
  33. package/dist/descriptive/hist.js +71 -31
  34. package/dist/descriptive/missing.js +3 -1
  35. package/dist/descriptive/moments.js +72 -19
  36. package/dist/descriptive/omega.d.ts +1 -1
  37. package/dist/descriptive/omega.js +68 -9
  38. package/dist/descriptive/pivot.d.ts +21 -9
  39. package/dist/descriptive/pivot.js +161 -35
  40. package/dist/descriptive/quantile.js +2 -1
  41. package/dist/descriptive/rank.js +4 -1
  42. package/dist/descriptive/table.d.ts +3 -2
  43. package/dist/descriptive/table.js +24 -9
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.js +19 -2
  46. package/dist/distributions/beta.js +24 -4
  47. package/dist/distributions/binomial.js +37 -14
  48. package/dist/distributions/bvnorm.js +11 -2
  49. package/dist/distributions/cauchy.js +12 -4
  50. package/dist/distributions/chisq.js +7 -3
  51. package/dist/distributions/exponential.js +5 -0
  52. package/dist/distributions/f.js +32 -17
  53. package/dist/distributions/gamma.js +27 -3
  54. package/dist/distributions/geometric.js +49 -13
  55. package/dist/distributions/hypergeometric.d.ts +5 -1
  56. package/dist/distributions/hypergeometric.js +93 -6
  57. package/dist/distributions/invgamma.js +2 -1
  58. package/dist/distributions/laplace.js +27 -6
  59. package/dist/distributions/logistic.js +4 -1
  60. package/dist/distributions/lognormal.js +8 -2
  61. package/dist/distributions/multinomial.js +54 -11
  62. package/dist/distributions/nbeta.js +62 -11
  63. package/dist/distributions/nchisq.js +30 -6
  64. package/dist/distributions/negbinomial.js +94 -17
  65. package/dist/distributions/normal.js +9 -4
  66. package/dist/distributions/nt.js +392 -17
  67. package/dist/distributions/pareto.js +4 -1
  68. package/dist/distributions/poisson.js +28 -3
  69. package/dist/distributions/signrank.js +7 -4
  70. package/dist/distributions/summary.js +450 -60
  71. package/dist/distributions/triangular.js +10 -5
  72. package/dist/distributions/tukey.js +5 -2
  73. package/dist/distributions/weibull.js +10 -0
  74. package/dist/distributions/wilcox.d.ts +9 -3
  75. package/dist/distributions/wilcox.js +155 -26
  76. package/dist/distributions.js +2 -2
  77. package/dist/htest/agreement.d.ts +3 -2
  78. package/dist/htest/agreement.js +76 -14
  79. package/dist/htest/ansariTest.d.ts +6 -1
  80. package/dist/htest/ansariTest.js +75 -8
  81. package/dist/htest/aov.d.ts +1 -1
  82. package/dist/htest/aov.js +48 -34
  83. package/dist/htest/binomTest.d.ts +5 -0
  84. package/dist/htest/binomTest.js +41 -17
  85. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  86. package/dist/htest/brunnerMunzelTest.js +7 -5
  87. package/dist/htest/chisqTest.d.ts +2 -1
  88. package/dist/htest/chisqTest.js +130 -43
  89. package/dist/htest/cor.d.ts +2 -1
  90. package/dist/htest/cor.js +17 -19
  91. package/dist/htest/core/ansari.d.ts +9 -0
  92. package/dist/htest/core/ansari.js +21 -1
  93. package/dist/htest/core/kolmogorov.d.ts +25 -0
  94. package/dist/htest/core/kolmogorov.js +123 -0
  95. package/dist/htest/core/mantelhaen.js +6 -4
  96. package/dist/htest/core/shapiro.d.ts +1 -1
  97. package/dist/htest/core/shapiro.js +5 -1
  98. package/dist/htest/dunnett.js +14 -5
  99. package/dist/htest/effectSize.d.ts +2 -0
  100. package/dist/htest/effectSize.js +91 -29
  101. package/dist/htest/fisherTest.d.ts +2 -2
  102. package/dist/htest/fisherTest.js +36 -18
  103. package/dist/htest/groups.d.ts +7 -0
  104. package/dist/htest/groups.js +21 -4
  105. package/dist/htest/ksTest.d.ts +3 -1
  106. package/dist/htest/ksTest.js +23 -2
  107. package/dist/htest/leveneTest.js +19 -3
  108. package/dist/htest/mantelhaenTest.js +125 -25
  109. package/dist/htest/mcnemarTest.js +32 -11
  110. package/dist/htest/multipleComparisons.d.ts +8 -1
  111. package/dist/htest/multipleComparisons.js +44 -21
  112. package/dist/htest/normalityTests.js +44 -10
  113. package/dist/htest/onewayTest.js +96 -5
  114. package/dist/htest/pAdjust.d.ts +3 -2
  115. package/dist/htest/pAdjust.js +38 -6
  116. package/dist/htest/pairwise.d.ts +1 -1
  117. package/dist/htest/pairwise.js +17 -15
  118. package/dist/htest/poissonTest.d.ts +1 -1
  119. package/dist/htest/poissonTest.js +111 -59
  120. package/dist/htest/polycor.js +27 -7
  121. package/dist/htest/power.d.ts +11 -1
  122. package/dist/htest/power.js +112 -8
  123. package/dist/htest/propTest.js +21 -4
  124. package/dist/htest/pwr.js +121 -24
  125. package/dist/htest/rankTests.js +29 -5
  126. package/dist/htest/tTest.js +44 -21
  127. package/dist/htest/trendTests.d.ts +7 -3
  128. package/dist/htest/trendTests.js +114 -20
  129. package/dist/htest/types.d.ts +5 -0
  130. package/dist/htest/types.js +7 -0
  131. package/dist/htest/varTest.js +45 -14
  132. package/dist/htest/wilcoxTest.js +114 -21
  133. package/dist/integrate/quadpack.js +27 -5
  134. package/dist/internal/covmat.d.ts +5 -0
  135. package/dist/internal/covmat.js +20 -0
  136. package/dist/internal/ddexp.d.ts +15 -1
  137. package/dist/internal/ddexp.js +59 -6
  138. package/dist/internal/discrete.d.ts +14 -0
  139. package/dist/internal/discrete.js +78 -5
  140. package/dist/internal/extremes.d.ts +9 -0
  141. package/dist/internal/extremes.js +24 -0
  142. package/dist/internal/fround.js +13 -4
  143. package/dist/internal/integer.d.ts +9 -0
  144. package/dist/internal/integer.js +12 -0
  145. package/dist/internal/invert.js +15 -2
  146. package/dist/internal/scaledInverse.d.ts +10 -0
  147. package/dist/internal/scaledInverse.js +22 -0
  148. package/dist/internal/seq.js +15 -2
  149. package/dist/internal/summary.d.ts +90 -0
  150. package/dist/internal/summary.js +458 -39
  151. package/dist/internal/uniroot.d.ts +7 -0
  152. package/dist/internal/uniroot.js +28 -3
  153. package/dist/linalg/basic.d.ts +3 -1
  154. package/dist/linalg/basic.js +51 -7
  155. package/dist/linalg/chol.js +4 -1
  156. package/dist/linalg/dot.d.ts +29 -0
  157. package/dist/linalg/dot.js +132 -0
  158. package/dist/linalg/eigen.d.ts +6 -1
  159. package/dist/linalg/eigen.js +71 -14
  160. package/dist/linalg/expm.d.ts +3 -2
  161. package/dist/linalg/expm.js +109 -15
  162. package/dist/linalg/kappa.js +58 -10
  163. package/dist/linalg/lu.d.ts +2 -1
  164. package/dist/linalg/lu.js +35 -5
  165. package/dist/linalg/matrix.d.ts +14 -0
  166. package/dist/linalg/matrix.js +24 -0
  167. package/dist/linalg/ops.js +60 -13
  168. package/dist/linalg/qr.d.ts +2 -1
  169. package/dist/linalg/qr.js +91 -23
  170. package/dist/linalg/schur.js +11 -3
  171. package/dist/linalg/solve.d.ts +6 -1
  172. package/dist/linalg/solve.js +147 -26
  173. package/dist/linalg/svd.d.ts +9 -2
  174. package/dist/linalg/svd.js +29 -11
  175. package/dist/linalg.js +2 -2
  176. package/dist/mixed.js +4 -4
  177. package/dist/models/anovaSequential.d.ts +16 -1
  178. package/dist/models/anovaSequential.js +124 -25
  179. package/dist/models/aovEz.js +140 -30
  180. package/dist/models/aovStrata.js +55 -22
  181. package/dist/models/carAnova.d.ts +1 -1
  182. package/dist/models/carAnova.js +83 -32
  183. package/dist/models/coxph.js +148 -66
  184. package/dist/models/estimable.d.ts +15 -0
  185. package/dist/models/estimable.js +68 -0
  186. package/dist/models/formula.d.ts +1 -1
  187. package/dist/models/formula.js +26 -8
  188. package/dist/models/glm.d.ts +35 -5
  189. package/dist/models/glm.js +398 -55
  190. package/dist/models/glmAnova.js +84 -13
  191. package/dist/models/glmConfint.d.ts +1 -1
  192. package/dist/models/glmConfint.js +115 -27
  193. package/dist/models/glmFamily.d.ts +10 -0
  194. package/dist/models/glmFamily.js +244 -40
  195. package/dist/models/lm.d.ts +12 -1
  196. package/dist/models/lm.js +235 -36
  197. package/dist/models/lmer.d.ts +20 -1
  198. package/dist/models/lmer.js +109 -27
  199. package/dist/models/lmerAnova.js +37 -4
  200. package/dist/models/lmerHypotheses.d.ts +6 -2
  201. package/dist/models/lmerHypotheses.js +14 -2
  202. package/dist/models/lmerTest.d.ts +9 -2
  203. package/dist/models/lmerTest.js +64 -19
  204. package/dist/models/mauchly.d.ts +4 -1
  205. package/dist/models/mauchly.js +34 -13
  206. package/dist/models/mixedStructure.js +6 -0
  207. package/dist/models/modelFrame.js +8 -2
  208. package/dist/models/modelMatrix.d.ts +3 -1
  209. package/dist/models/modelMatrix.js +40 -15
  210. package/dist/models/scaledTables.d.ts +8 -0
  211. package/dist/models/scaledTables.js +6 -0
  212. package/dist/models/survival.d.ts +6 -1
  213. package/dist/models/survival.js +67 -27
  214. package/dist/models/tiedTimes.d.ts +2 -0
  215. package/dist/models/tiedTimes.js +34 -0
  216. package/dist/numerics/deriv.d.ts +1 -1
  217. package/dist/numerics/deriv.js +64 -8
  218. package/dist/numerics/integrate.d.ts +9 -1
  219. package/dist/numerics/integrate.js +103 -16
  220. package/dist/numerics/interp.d.ts +8 -2
  221. package/dist/numerics/interp.js +352 -50
  222. package/dist/numerics/ode.js +55 -1
  223. package/dist/numerics.js +2 -2
  224. package/dist/optim/localmin.js +4 -0
  225. package/dist/optim/optim.d.ts +3 -1
  226. package/dist/optim/optim.js +80 -8
  227. package/dist/random/beta.js +53 -4
  228. package/dist/random/binomial.d.ts +14 -3
  229. package/dist/random/binomial.js +59 -24
  230. package/dist/random/continuous.js +33 -5
  231. package/dist/random/extra.js +42 -9
  232. package/dist/random/gamma.d.ts +4 -1
  233. package/dist/random/gamma.js +36 -8
  234. package/dist/random/hyper.js +9 -6
  235. package/dist/random/mt.js +17 -2
  236. package/dist/random/poisson.js +26 -3
  237. package/dist/random/r2dtable.d.ts +8 -1
  238. package/dist/random/r2dtable.js +24 -3
  239. package/dist/random/rank.d.ts +2 -0
  240. package/dist/random/rank.js +44 -4
  241. package/dist/random/sample.d.ts +12 -2
  242. package/dist/random/sample.js +57 -20
  243. package/dist/random/streams.js +4 -2
  244. package/dist/rstats.js +14 -14
  245. package/dist/special/besselIK.d.ts +12 -0
  246. package/dist/special/besselIK.js +168 -23
  247. package/dist/special/besselJY.d.ts +11 -1
  248. package/dist/special/besselJY.js +127 -19
  249. package/dist/special/besselSeries.d.ts +27 -0
  250. package/dist/special/besselSeries.js +45 -2
  251. package/dist/special/beta.js +4 -1
  252. package/dist/special/choose.js +17 -8
  253. package/dist/special/dd.js +122 -18
  254. package/dist/special/extra.js +14 -2
  255. package/dist/special/gamma.js +11 -2
  256. package/dist/special/incbet.js +30 -4
  257. package/dist/special/incbetTemme.d.ts +7 -0
  258. package/dist/special/incbetTemme.js +45 -12
  259. package/dist/special/loader.d.ts +1 -1
  260. package/dist/special/loader.js +117 -20
  261. package/dist/special/log1pmx.js +4 -0
  262. package/dist/special.js +2 -2
  263. package/dist/tests.js +11 -11
  264. package/llms.txt +12 -6
  265. package/package.json +1 -1
  266. package/dist/chunks/chunk-3THFTB36.js +0 -2
  267. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  268. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  269. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  270. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  271. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  272. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  273. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  274. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  275. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  276. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  277. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  278. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  279. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  280. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  281. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  282. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  283. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  284. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  285. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
@@ -8,6 +8,7 @@
8
8
  // (src/models/ddMatrix.ts).
9
9
  import { pgamma1 } from "../distributions/gamma.js";
10
10
  import { levelText } from "../internal/levels.js";
11
+ import { scaleToUnit } from "../internal/summary.js";
11
12
  import { qr } from "../linalg/qr.js";
12
13
  import { ddAdd, ddDiv, ddDivNum, ddMul, ddSub } from "../special/dd.js";
13
14
  import { ddLeastSquaresMulti } from "./ddLeastSquares.js";
@@ -15,15 +16,14 @@ import { ddDet, ddTrace } from "./ddMatrix.js";
15
16
  import { compareCodePoints } from "./modelFrame.js";
16
17
  import { modelMatrix } from "./modelMatrix.js";
17
18
  const upperChisq = (q, df) => pgamma1(q, df / 2, 2, false, false);
18
- /** W = det(U) / (trace(U)/p)^p of a p x p matrix U */
19
+ /**
20
+ * W = det(U) / (trace(U)/p)^p of a p x p matrix U, as det(U / (trace(U)/p)): the scaled matrix has trace p, so
21
+ * neither the determinant nor the power overflows or underflows when W itself is in range
22
+ */
19
23
  export function sphericityW(U) {
20
24
  const p = U.length;
21
- let m = ddDivNum(ddTrace(U), p);
22
- let pow = [1, 0];
23
- for (let i = 0; i < p; i++)
24
- pow = ddMul(pow, m);
25
- m = ddDiv(ddDet(U), pow);
26
- return m[0];
25
+ const m = ddDivNum(ddTrace(U), p);
26
+ return ddDet(U.map((r) => r.map((v) => ddDiv(v, m))))[0];
27
27
  }
28
28
  /**
29
29
  * The p-value of Mauchly's W by the asymptotic expansion: pp the dimension tested, n the degrees of freedom of the
@@ -82,15 +82,22 @@ export function contrastCrossprod(S, mcols, xcols) {
82
82
  * @category Linear models and ANOVA
83
83
  */
84
84
  export function mauchlyTest(y, options = {}) {
85
- const rows = y.map((r) => Array.from(r));
86
- const nsub = rows.length;
87
- const k = rows[0]?.length ?? 0;
88
- if (k === 0 || rows.some((r) => r.length !== k))
85
+ const all = y.map((r) => Array.from(r));
86
+ const k = all[0]?.length ?? 0;
87
+ if (k === 0 || all.some((r) => r.length !== k))
89
88
  throw new TypeError("y must be a matrix with at least one column");
90
89
  const group = options.group;
91
- if (group !== undefined && group.length !== nsub)
90
+ if (group !== undefined && group.length !== all.length)
92
91
  throw new RangeError("'group' must have one label per row of y");
93
- const labels = group?.map(levelText) ?? rows.map(() => "");
92
+ // as for lm(y ~ group): rows with a missing value (NaN or null) in y or a missing group are dropped
93
+ const isMissing = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
94
+ const keep = all.map((r, i) => !r.some(isMissing) && (group === undefined || !isMissing(group[i])));
95
+ if (all.some((r, i) => keep[i] && r.some((v) => !Number.isFinite(v))))
96
+ throw new RangeError("y must not contain infinite values");
97
+ // scaled by a power of 2 (exact) so that the cross-products stay in range; W does not depend on the units
98
+ const rows = scaleToUnit(all.filter((_, i) => keep[i])).groups;
99
+ const nsub = rows.length;
100
+ const labels = group?.filter((_, i) => keep[i]).map(levelText) ?? rows.map(() => "");
94
101
  const levels = [...new Set(labels)].sort(compareCodePoints);
95
102
  // residuals from the group means (double-double), and their cross-products
96
103
  const res = rows.map((r) => r.map(() => [0, 0]));
@@ -106,6 +113,8 @@ export function mauchlyTest(y, options = {}) {
106
113
  }
107
114
  }
108
115
  const n = nsub - levels.length;
116
+ if (n <= 0)
117
+ throw new RangeError(`no residual degrees of freedom: ${nsub} complete row(s) for ${levels.length} group(s)`);
109
118
  const S = Array.from({ length: k }, (_, a) => Array.from({ length: k }, (_, b) => {
110
119
  let s = [0, 0];
111
120
  for (const r of res)
@@ -123,6 +132,18 @@ export function mauchlyTest(y, options = {}) {
123
132
  const xcols = design(options.X ?? "~0");
124
133
  const U = contrastCrossprod(S, mcols, xcols);
125
134
  const pp = U.length;
135
+ // X spanning M leaves nothing to test (W was 1 and the p-value NaN; R stops with "'a' is 0-diml")
136
+ if (pp === 0)
137
+ throw new RangeError("X spans M: the test has no dimensions");
138
+ // one dimension is spherical whatever the data: W is 1 and the chi-squared df pp (pp + 1) / 2 - 1 is 0, so there is
139
+ // nothing to test (R returns W 1 and p 1, #342)
140
+ if (pp === 1)
141
+ throw new RangeError("one tested dimension: sphericity holds trivially and the test has no degrees of freedom");
142
+ // with fewer residual degrees of freedom than dimensions the covariance is singular whatever the data, and the test
143
+ // is not defined (W was rounding noise, even negative, and p NaN or 1, as R's); n >= pp also keeps the correction's
144
+ // rho positive
145
+ if (n < pp)
146
+ throw new RangeError(`too few residual degrees of freedom for the test: ${n} for ${pp} dimension(s)`);
126
147
  const W = sphericityW(U);
127
148
  return { statistic: W, statisticName: "W", pValue: mauchlyPValue(W, pp, n, k), method: "Mauchly's test of sphericity" };
128
149
  }
@@ -228,6 +228,12 @@ export function mixedModelStructure(formula, data, options = {}) {
228
228
  "the random-effects parameters and the residual variance (or scale parameter) are probably unidentifiable");
229
229
  }
230
230
  }
231
+ // a column of a random-effects term not finite (#298: an infinite x in (x | g) reached the factorisation; R stops
232
+ // with "objective in x0 returns NA")
233
+ for (const t of terms) {
234
+ if (t.matrix.some((row) => row.some((v) => !Number.isFinite(v))))
235
+ throw new RangeError(`NA/NaN/Inf in the random-effects term (${t.label})`);
236
+ }
231
237
  // Z (level-major within each term), and Λ_θ, θ and its bounds
232
238
  const z = [];
233
239
  const zColLevels = [];
@@ -45,8 +45,12 @@ function convert(name, col, levels) {
45
45
  const str = (x) => x === null || (typeof x === "number" && Number.isNaN(x)) ? null : typeof x === "boolean" ? (x ? "TRUE" : "FALSE") : levelText(x);
46
46
  const labels = vals.map(str);
47
47
  let lev;
48
- if (levels !== undefined)
48
+ if (levels !== undefined) {
49
49
  lev = Array.from(levels, String);
50
+ const dup = lev.findIndex((l, i) => lev.indexOf(l) !== i);
51
+ if (dup >= 0)
52
+ throw new RangeError(`factor level [${dup + 1}] is duplicated`);
53
+ }
50
54
  else if (kind === "boolean")
51
55
  lev = ["FALSE", "TRUE"];
52
56
  else
@@ -110,7 +114,9 @@ export function modelFrame(data, names, options = {}) {
110
114
  });
111
115
  if (w !== undefined && w.length !== n)
112
116
  throw new RangeError("variable lengths differ (found for '(weights)')");
113
- const conv = names.map((v, i) => convert(v, cols[i], options.levels?.[v]));
117
+ // own properties only: a column named toString has no given levels unless they are given
118
+ const { levels } = options;
119
+ const conv = names.map((v, i) => convert(v, cols[i], levels !== undefined && Object.hasOwn(levels, v) ? levels[v] : undefined));
114
120
  let weights;
115
121
  if (w !== undefined) {
116
122
  weights = Array.from(w, (x) => {
@@ -89,6 +89,8 @@ export interface DesignOptions extends Omit<ModelMatrixOptions, "contrasts"> {
89
89
  * of the formula without the Error() term)
90
90
  */
91
91
  contrastVariables?: readonly string[];
92
+ /** Accept a response of any type, without `y` unless it is numeric (modelMatrix, as R's model.matrix) */
93
+ anyResponse?: boolean;
92
94
  }
93
95
  /**
94
96
  * The model matrix of a parsed formula on the data.
@@ -103,7 +105,7 @@ export declare function design(parsed: ParsedFormula, data: DataFrame, options?:
103
105
  * Rows with a missing value (`null`, or `NaN` in a numeric column) in any variable of the formula are dropped first.
104
106
  * Strings are factors of the values in the rows kept (sorted by code point), unless `levels` gives the levels, which
105
107
  * are then all kept even without a row (their columns are 0); booleans are factors with always the two levels FALSE
106
- * and TRUE; numbers are numeric.
108
+ * and TRUE; numbers are numeric. The response may be of any type: it only drops its rows with a missing value.
107
109
  *
108
110
  * @param formula A formula such as `"y ~ A * B"`, `"y ~ x + A - 1"` or `"~ A"`.
109
111
  * @param data The data frame: an object of columns.
@@ -7,19 +7,40 @@
7
7
  // indicators.
8
8
  import { parseFormula, termsOf } from "./formula.js";
9
9
  import { modelFrame } from "./modelFrame.js";
10
- import { qr, qrQ, qrR } from "../linalg/qr.js";
11
10
  /**
12
- * contr.poly for k levels (scores 1..k): the orthonormal polynomials of degrees 1..k-1 in the scores, the columns
13
- * of Q of the QR decomposition of the powers 0..k-1 of the centred scores, each signed so that its coefficient of
14
- * the highest power is positive (Q diag(R), normalised).
11
+ * The orthonormal polynomials of degrees 1..k-1 in the centred scores, as columns (one row per level): P_0 = 1/sqrt(k)
12
+ * and P_d from x P_(d-1) orthogonalised twice against every earlier P (the Stieltjes three-term recurrence spans the
13
+ * same space; the full re-orthogonalisation keeps its rounding from accumulating), normalised. The coefficient of the
14
+ * highest power stays positive (x P_(d-1) has P_(d-1)'s positive leading coefficient), as for the QR.
15
15
  */
16
- function polyContrasts(k) {
16
+ function polyRecurrence(k) {
17
17
  const mean = (k + 1) / 2;
18
- const powers = Array.from({ length: k }, (_, i) => Array.from({ length: k }, (__, j) => (i + 1 - mean) ** j));
19
- const d = qr(powers);
20
- const q = qrQ(d);
21
- const r = qrR(d);
22
- return q.map((row) => row.slice(1).map((v, j) => (r[j + 1][j + 1] < 0 ? -v : v)));
18
+ const x = Array.from({ length: k }, (_, i) => i + 1 - mean);
19
+ const cols = [new Array(k).fill(1 / Math.sqrt(k))];
20
+ const dot = (a, b) => a.reduce((s, ai, i) => s + ai * b[i], 0);
21
+ for (let d = 1; d < k; d++) {
22
+ const v = cols[d - 1].map((c, i) => c * x[i]);
23
+ for (let pass = 0; pass < 2; pass++) {
24
+ for (const q of cols) {
25
+ const c = dot(q, v);
26
+ for (let i = 0; i < k; i++)
27
+ v[i] -= c * q[i];
28
+ }
29
+ }
30
+ const norm = Math.sqrt(dot(v, v));
31
+ cols.push(v.map((vi) => vi / norm));
32
+ }
33
+ return x.map((_, i) => cols.slice(1).map((c) => c[i]));
34
+ }
35
+ /**
36
+ * contr.poly for k levels (scores 1..k): the orthonormal polynomials of degrees 1..k-1 in the scores, each signed so
37
+ * that its coefficient of the highest power is positive. R takes Q of the QR of the powers 0..k-1 of the centred
38
+ * scores, which is ill-conditioned in doubles (elements off by 3e-13 at 14 levels, 1e-10 at 20, and from 23 levels
39
+ * the high-degree columns are other vectors altogether); this uses {@link polyRecurrence} for every k, within 1e-15
40
+ * of the exact values (issue #351).
41
+ */
42
+ function polyContrasts(k) {
43
+ return polyRecurrence(k);
23
44
  }
24
45
  /** A contrast matrix (one row per level) and its column names */
25
46
  export function contrastMatrix(levels, contrast) {
@@ -133,7 +154,9 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
133
154
  const name = terms.variables[v];
134
155
  if (fv.kind === "numeric")
135
156
  return [{ name, values: fv.values }];
136
- const contrast = code === 2 ? "indicators" : (options.allContrasts ?? options.contrasts?.[name] ?? "contr.treatment");
157
+ // own properties only: a factor named toString has the default contrast unless one is given
158
+ const given = options.contrasts !== undefined && Object.hasOwn(options.contrasts, name) ? options.contrasts[name] : undefined;
159
+ const contrast = code === 2 ? "indicators" : (options.allContrasts ?? given ?? "contr.treatment");
137
160
  const { m, names } = contrastMatrix(fv.levels, contrast);
138
161
  return names.map((cn, j) => ({ name: name + cn, values: fv.codes.map((c) => m[c][j]) }));
139
162
  };
@@ -162,9 +185,10 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
162
185
  const out = { terms, frame, x, colNames, assign, warnings };
163
186
  if (terms.response >= 0) {
164
187
  const r = vars[terms.response];
165
- if (r.kind !== "numeric")
188
+ if (r.kind === "numeric")
189
+ out.y = r.values;
190
+ else if (options.anyResponse !== true)
166
191
  throw new TypeError("the response must be numeric");
167
- out.y = r.values;
168
192
  }
169
193
  return out;
170
194
  }
@@ -175,7 +199,7 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
175
199
  * Rows with a missing value (`null`, or `NaN` in a numeric column) in any variable of the formula are dropped first.
176
200
  * Strings are factors of the values in the rows kept (sorted by code point), unless `levels` gives the levels, which
177
201
  * are then all kept even without a row (their columns are 0); booleans are factors with always the two levels FALSE
178
- * and TRUE; numbers are numeric.
202
+ * and TRUE; numbers are numeric. The response may be of any type: it only drops its rows with a missing value.
179
203
  *
180
204
  * @param formula A formula such as `"y ~ A * B"`, `"y ~ x + A - 1"` or `"~ A"`.
181
205
  * @param data The data frame: an object of columns.
@@ -190,7 +214,8 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
190
214
  * @category Linear models and ANOVA
191
215
  */
192
216
  export function modelMatrix(formula, data, options = {}) {
193
- const d = design(parseFormula(formula), data, options);
217
+ // the response only drops the rows where it is missing: any type, as R's model.matrix (#453)
218
+ const d = design(parseFormula(formula), data, { ...options, anyResponse: true });
194
219
  return {
195
220
  colNames: d.colNames,
196
221
  assign: d.assign,
@@ -0,0 +1,8 @@
1
+ /** A table with the columns of the returned one, its sums of squares in the units of the fit */
2
+ export interface ScaledTable {
3
+ colNames: string[];
4
+ rowNames: string[];
5
+ table: number[][];
6
+ }
7
+ /** The scaled table of anova(), aovSummary() and aovEz() results; the scaled strata of aov() with Error() and its summary */
8
+ export declare const scaledTables: WeakMap<object, ScaledTable[] | ScaledTable>;
@@ -0,0 +1,6 @@
1
+ // Tables of sums of squares in the units of the response as fitted (divided by 2^k, so that 2^2k scales the tables
2
+ // that the functions return), kept by result object for the effect sizes: those are ratios of sums of squares, which
3
+ // the returned tables can no longer give where their sums of squares overflow (data around 1e154). Written for
4
+ // rStats.js.
5
+ /** The scaled table of anova(), aovSummary() and aovEz() results; the scaled strata of aov() with Error() and its summary */
6
+ export const scaledTables = new WeakMap();
@@ -26,7 +26,12 @@ export interface SurvdiffResult {
26
26
  var: number[][];
27
27
  /** Chi-squared statistic */
28
28
  chisq: number;
29
- /** Upper chi-squared tail on (number of groups with a positive expected count) - 1 degrees of freedom */
29
+ /**
30
+ * Degrees of freedom: (number of groups with a positive expected count) - 1, or the rank of the variance matrix of
31
+ * those groups (all but the first) when it is singular
32
+ */
33
+ df: number;
34
+ /** Upper chi-squared tail on `df` degrees of freedom (NaN for df = 0: the data carry no information on the groups) */
30
35
  pvalue: number;
31
36
  }
32
37
  /**
@@ -9,7 +9,10 @@
9
9
  import { pchisq } from "../distributions/chisq.js";
10
10
  import { qnorm } from "../distributions/normal.js";
11
11
  import { levelText, numberLevels } from "../internal/levels.js";
12
+ import { eigen } from "../linalg/eigen.js";
12
13
  import { solve } from "../linalg/solve.js";
14
+ import { midpoint } from "../internal/extremes.js";
15
+ import { mergeTiedTimes } from "./tiedTimes.js";
13
16
  const isMissing = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
14
17
  /** Observations with no missing value, the sorted labels and the group index of each */
15
18
  function prepare(time, status, group) {
@@ -24,6 +27,10 @@ function prepare(time, status, group) {
24
27
  const s = status[i];
25
28
  if (s !== 0 && s !== 1)
26
29
  throw new RangeError("'status' must be 0 (censored) or 1 (event)");
30
+ // a subject censored at Infinity is at risk throughout (R stops on any infinite time); an event cannot happen at an
31
+ // infinite time, nor anything at -Infinity
32
+ if (time[i] === -Infinity || (time[i] === Infinity && s === 1))
33
+ throw new RangeError("event times must be finite");
27
34
  keep.push(i);
28
35
  }
29
36
  if (keep.length === 0)
@@ -37,8 +44,11 @@ function prepare(time, status, group) {
37
44
  labels = Array.from(new Set(keep.map((i) => group[i]))).sort((a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0);
38
45
  labels.forEach((l, k) => index.set(l, k));
39
46
  }
40
- const obs = keep.map((i) => ({
41
- time: time[i],
47
+ // times within rounding error are one time, as R's timefix = TRUE (1 and 1 + 1e-9 were two times, so a subject
48
+ // censored at 1 left the risk set before the event at 1 + 1e-9)
49
+ const merged = mergeTiedTimes(keep.map((i) => time[i]));
50
+ const obs = keep.map((i, k) => ({
51
+ time: merged[k],
42
52
  event: status[i] === 1,
43
53
  group: group === undefined ? 0 : index.get(group[i]),
44
54
  }));
@@ -71,6 +81,8 @@ export function survdiff(time, status, group, options = {}) {
71
81
  throw new RangeError("'rho' must be a finite number");
72
82
  const { obs, labels } = prepare(time, status, group);
73
83
  const k = labels.length;
84
+ if (k < 2)
85
+ throw new RangeError("there is only 1 group");
74
86
  const n = new Array(k).fill(0);
75
87
  for (const o of obs)
76
88
  n[o.group]++;
@@ -120,35 +132,62 @@ export function survdiff(time, status, group, options = {}) {
120
132
  // chi-squared on the groups with a positive expected count, dropping the first of them
121
133
  const used = expected.map((e, g) => (e > 0 ? g : -1)).filter((g) => g >= 0);
122
134
  let chisq = 0;
135
+ let df = Math.max(used.length - 1, 0);
123
136
  if (used.length >= 2) {
124
137
  const r = used.slice(1);
125
138
  const u = r.map((g) => observed[g] - expected[g]);
126
- const x = solve(r.map((g) => r.map((h) => V[g][h])), u);
127
- chisq = u.reduce((s, ui, a) => s + ui * x[a], 0);
139
+ const Vr = r.map((g) => r.map((h) => V[g][h]));
140
+ try {
141
+ const x = solve(Vr, u);
142
+ chisq = u.reduce((s, ui, a) => s + ui * x[a], 0);
143
+ }
144
+ catch {
145
+ // A singular variance matrix (all at risk failing at once, or groups that carry no information): u' V^- u with
146
+ // the generalized inverse, on rank(V) degrees of freedom, which is the chi-squared statistic of the contrasts
147
+ // the data inform (R stops: "system is exactly singular")
148
+ ({ chisq, df } = pseudoQuadratic(Vr, u));
149
+ }
128
150
  }
129
- const pvalue = pchisq(chisq, used.length - 1, { lowerTail: false });
130
- return { n, groups: labels, obs: observed, exp: expected, var: V, chisq, pvalue };
151
+ const pvalue = df === 0 ? NaN : pchisq(chisq, df, { lowerTail: false });
152
+ return { n, groups: labels, obs: observed, exp: expected, var: V, chisq, df, pvalue };
131
153
  }
132
154
  /**
133
- * The median of a curve over the rows of a stratum: the first time at which it falls below 0.5, or, if it equals 0.5
134
- * (within sqrt(eps)) there, the midpoint between that time and the next event time. NaN if it never goes below
135
- * 0.5 + sqrt(eps).
155
+ * u' V^- u for a symmetric positive semi-definite V by its eigen decomposition, over the eigenvalues above 1e-10 of the
156
+ * largest (rank 0, chisq 0 when there are none), and that rank
136
157
  */
137
- function curveMedian(time, nEvent, curve) {
158
+ function pseudoQuadratic(V, u) {
159
+ const e = eigen(V, { symmetric: true });
160
+ const values = e.values;
161
+ const top = values.reduce((a, b) => Math.max(a, b), 0);
162
+ let chisq = 0;
163
+ let df = 0;
164
+ values.forEach((l, k) => {
165
+ if (!(top > 0 && l > 1e-10 * top))
166
+ return;
167
+ const q = u.reduce((s, ui, i) => s + ui * e.vectors[i][k], 0);
168
+ chisq += (q * q) / l;
169
+ df++;
170
+ });
171
+ return { chisq, df };
172
+ }
173
+ /**
174
+ * The median of a curve over the rows of a stratum, as survival's survmean (minmin): of the points that are not NaN
175
+ * and lie below 0.5 + sqrt(eps), the first time, or, if the curve equals 0.5 (within sqrt(eps)) there and a later such
176
+ * point is lower, the midpoint between that time and the time of the first lower point. NaN if there is no such point.
177
+ */
178
+ function curveMedian(time, curve) {
138
179
  const tol = Math.sqrt(Number.EPSILON);
139
- for (let i = 0; i < curve.length; i++) {
140
- const c = curve[i];
141
- if (!(c < 0.5 + tol))
142
- continue;
143
- if (c > 0.5 - tol) {
144
- for (let j = i + 1; j < curve.length; j++)
145
- if (nEvent[j] > 0)
146
- return (time[i] + time[j]) / 2;
147
- return time[i];
148
- }
149
- return time[i];
180
+ const first = curve.findIndex((c) => c < 0.5 + tol);
181
+ if (first < 0)
182
+ return NaN;
183
+ const c1 = curve[first];
184
+ if (Math.abs(c1 - 0.5) < tol) {
185
+ // a NaN point compares false and is skipped, as R drops it before looking for a lower one
186
+ for (let j = first + 1; j < curve.length; j++)
187
+ if (curve[j] < c1)
188
+ return midpoint(time[first], time[j]);
150
189
  }
151
- return NaN;
190
+ return time[first];
152
191
  }
153
192
  /**
154
193
  * Kaplan-Meier estimate of the survival function with Greenwood's standard error and pointwise confidence intervals.
@@ -177,7 +216,9 @@ export function survfit(time, status, options = {}) {
177
216
  throw new RangeError("'confInt' must be between 0 and 1");
178
217
  const { obs, labels } = prepare(time, status, group);
179
218
  const names = group === undefined ? ["all"] : labels;
180
- const z = qnorm(1 - (1 - confInt) / 2);
219
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
220
+ const a2 = (1 - confInt) / 2;
221
+ const z = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - (1 - confInt) / 2);
181
222
  const out = {
182
223
  strata: [], time: [], nRisk: [], nEvent: [], nCensor: [], surv: [], stdErr: [], lower: [], upper: [],
183
224
  median: [], medianRows: names,
@@ -237,11 +278,10 @@ export function survfit(time, status, options = {}) {
237
278
  i = j;
238
279
  }
239
280
  const tt = out.time.slice(start);
240
- const ev = out.nEvent.slice(start);
241
281
  out.median.push([
242
- curveMedian(tt, ev, out.surv.slice(start)),
243
- curveMedian(tt, ev, out.lower.slice(start)),
244
- curveMedian(tt, ev, out.upper.slice(start)),
282
+ curveMedian(tt, out.surv.slice(start)),
283
+ curveMedian(tt, out.lower.slice(start)),
284
+ curveMedian(tt, out.upper.slice(start)),
245
285
  ]);
246
286
  });
247
287
  return out;
@@ -0,0 +1,2 @@
1
+ /** Times within sqrt(eps) (absolutely or relative to the mean absolute distinct time) merged to the smaller one */
2
+ export declare function mergeTiedTimes(time: readonly number[]): number[];
@@ -0,0 +1,34 @@
1
+ // Times that differ by rounding error only, merged as R's survival does by default (timefix = TRUE, aeqSurv): coxph and
2
+ // survfit / survdiff (survival.ts).
3
+ import { mean } from "../internal/summary.js";
4
+ /** Times within sqrt(eps) (absolutely or relative to the mean absolute distinct time) merged to the smaller one */
5
+ export function mergeTiedTimes(time) {
6
+ const tol = Math.sqrt(2 ** -52);
7
+ const distinct = Array.from(new Set(time.filter((t) => Number.isFinite(t)))).sort((a, b) => a - b);
8
+ if (distinct.length < 2)
9
+ return time.slice();
10
+ // the mean of |time| without overflow (a plain sum of times near 1e308 was Infinity, so every relative gap was 0 and
11
+ // distinct times were merged: coxph gave a coefficient of 0); a gap that overflows is Infinity, a distinct time
12
+ const meanAbs = mean(distinct.map(Math.abs));
13
+ const cuts = [distinct[0]];
14
+ for (let k = 0; k + 1 < distinct.length; k++) {
15
+ const gap = distinct[k + 1] - distinct[k];
16
+ if (!(gap <= tol || gap / meanAbs <= tol))
17
+ cuts.push(distinct[k + 1]);
18
+ }
19
+ return time.map((t) => {
20
+ if (!Number.isFinite(t))
21
+ return t;
22
+ // the largest cut point not above t
23
+ let lo = 0;
24
+ let hi = cuts.length - 1;
25
+ while (lo < hi) {
26
+ const mid = Math.floor((lo + hi + 1) / 2); // not >> 1, which wraps beyond 2^31 times (issue #352)
27
+ if (cuts[mid] <= t)
28
+ lo = mid;
29
+ else
30
+ hi = mid - 1;
31
+ }
32
+ return cuts[lo];
33
+ });
34
+ }
@@ -12,7 +12,7 @@ export interface DerivOptions {
12
12
  d?: number;
13
13
  /** Coordinates with |x| below this get the step `eps`. Default `sqrt(2.220446e-16 / 7e-7)`. */
14
14
  zeroTol?: number;
15
- /** Number of halvings of the step (Richardson iterations). Default `4`. */
15
+ /** Number of halvings of the step (Richardson iterations), at most 512. Default `4`. */
16
16
  r?: number;
17
17
  }
18
18
  /**
@@ -7,14 +7,42 @@
7
7
  // diagonal from second central differences, the off-diagonal entries from differences along e_i + e_j less the
8
8
  // diagonal terms, each extrapolated the same way (with d = 0.1). "simple" is the forward difference with step eps.
9
9
  // numDeriv's "complex" (complex-step) method needs a function of a complex argument and is not offered.
10
+ function checkEps(eps) {
11
+ if (!(Number.isFinite(eps) && eps !== 0))
12
+ throw new RangeError("'eps' must be a finite nonzero number");
13
+ }
14
+ /** The step of method "simple" */
15
+ function simpleEps(options) {
16
+ const eps = options.eps ?? 1e-4;
17
+ checkEps(eps);
18
+ return eps;
19
+ }
10
20
  function steps(x, options, d0) {
11
21
  const eps = options.eps ?? 1e-4;
12
22
  const d = options.d ?? d0;
13
23
  const zeroTol = options.zeroTol ?? Math.sqrt(Number.EPSILON / 7e-7);
24
+ // a step of 0 or a non-finite step defines no difference quotient (numDeriv: an error for d = 0, NaN for eps = 0);
25
+ // negative steps are differences taken the other way, as in numDeriv
26
+ if (!(Number.isFinite(d) && d !== 0))
27
+ throw new RangeError("'d' must be a finite nonzero number");
28
+ checkEps(eps);
29
+ if (!(Number.isFinite(zeroTol) && zeroTol >= 0))
30
+ throw new RangeError("'zeroTol' must be a non-negative finite number");
14
31
  const r = options.r ?? 4;
15
32
  if (!(Number.isInteger(r) && r >= 1))
16
33
  throw new RangeError("'r' must be a positive integer");
17
- return { eps, r, h0: x.map((v) => Math.abs(d * v) + (Math.abs(v) < zeroTol ? eps : 0)) };
34
+ // from r = 513 on the extrapolation's 4^m overflows (m = 512) and every result is NaN, as in numDeriv; its O(r^2)
35
+ // steps would not end for a huge r
36
+ if (r > 512)
37
+ throw new RangeError("'r' must be at most 512");
38
+ const h0 = x.map((v) => Math.abs(d * v) + (Math.abs(v) < zeroTol ? eps : 0));
39
+ // a step of 0 or a non-finite step defines no difference quotient: d abs(x[i]) overflowing (#213), or 0 for
40
+ // x[i] = 0 with zeroTol 0 (#246) (numDeriv: NaN from jacobian and hessian, an error from grad's check of f)
41
+ h0.forEach((h, i) => {
42
+ if (!(Math.abs(h) > 0 && Math.abs(h) < Infinity))
43
+ throw new RangeError(`the step for x[${i}] is ${h}: not a nonzero finite number`);
44
+ });
45
+ return { eps, r, h0 };
18
46
  }
19
47
  /** Richardson extrapolation of approximations at steps h, h/2, h/4, ... (errors in even powers of h) */
20
48
  function extrapolate(a) {
@@ -51,7 +79,7 @@ export function grad(func, x, options = {}) {
51
79
  const xs = [...x];
52
80
  const n = xs.length;
53
81
  if (method(options) === "simple") {
54
- const eps = options.eps ?? 1e-4;
82
+ const eps = simpleEps(options);
55
83
  const f0 = func([...xs]);
56
84
  return xs.map((_, i) => (func(shifted(xs, i, eps)) - f0) / eps);
57
85
  }
@@ -90,10 +118,17 @@ export function jacobian(func, x, options = {}) {
90
118
  const n = xs.length;
91
119
  const f0 = Array.from(func([...xs]));
92
120
  const J = f0.map(() => new Array(n).fill(NaN));
121
+ // every evaluation must return as many values as f0: shorter ones gave NaN rows, longer ones were cut (issue #356)
122
+ const evaluate = (at) => {
123
+ const v = func(at);
124
+ if (v.length !== f0.length)
125
+ throw new RangeError(`jacobian: func returned ${v.length} values at a shifted x, but ${f0.length} at x`);
126
+ return v;
127
+ };
93
128
  if (method(options) === "simple") {
94
- const eps = options.eps ?? 1e-4;
129
+ const eps = simpleEps(options);
95
130
  for (let j = 0; j < n; j++) {
96
- const f1 = func(shifted(xs, j, eps));
131
+ const f1 = evaluate(shifted(xs, j, eps));
97
132
  f0.forEach((v, i) => (J[i][j] = (f1[i] - v) / eps));
98
133
  }
99
134
  return J;
@@ -103,8 +138,8 @@ export function jacobian(func, x, options = {}) {
103
138
  const a = f0.map(() => []);
104
139
  let h = h0[j];
105
140
  for (let k = 0; k < r; k++) {
106
- const fp = func(shifted(xs, j, h));
107
- const fm = func(shifted(xs, j, -h));
141
+ const fp = evaluate(shifted(xs, j, h));
142
+ const fm = evaluate(shifted(xs, j, -h));
108
143
  f0.forEach((_, i) => a[i].push((fp[i] - fm[i]) / (2 * h)));
109
144
  h /= 2;
110
145
  }
@@ -135,7 +170,16 @@ export function hessian(func, x, options = {}) {
135
170
  const a = [];
136
171
  let h = h0[i];
137
172
  for (let k = 0; k < r; k++) {
138
- a.push((func(shifted(xs, i, h)) - 2 * f0 + func(shifted(xs, i, -h))) / h ** 2);
173
+ const fp = func(shifted(xs, i, h));
174
+ const fm = func(shifted(xs, i, -h));
175
+ const num = fp - 2 * f0 + fm;
176
+ // where h^2 overflows (h beyond 1.3e154), divided by h twice: a finite curvature was 0 or NaN (issue #214)
177
+ const h2 = h ** 2;
178
+ // where the sum of finite values overflows (f(+-1e200) near 1e308), every term divided by h first (issue #504)
179
+ if (!Number.isFinite(num) && Number.isFinite(fp) && Number.isFinite(fm) && Number.isFinite(f0))
180
+ a.push((fp / h - 2 * (f0 / h) + fm / h) / h);
181
+ else
182
+ a.push(Number.isFinite(h2) ? num / h2 : num / h / h);
139
183
  h /= 2;
140
184
  }
141
185
  diag.push(extrapolate(a));
@@ -150,7 +194,19 @@ export function hessian(func, x, options = {}) {
150
194
  for (let k = 0; k < r; k++) {
151
195
  const up = shifted(shifted(xs, i, hi), j, hj);
152
196
  const down = shifted(shifted(xs, i, -hi), j, -hj);
153
- a.push((func(up) - 2 * f0 + func(down) - diag[i] * hi ** 2 - diag[j] * hj ** 2) / (2 * hi * hj));
197
+ const fu = func(up);
198
+ const fd = func(down);
199
+ const num = fu - 2 * f0 + fd;
200
+ const den = 2 * hi * hj;
201
+ // where the sum of finite values overflows, every term divided by hi hj first (issue #504)
202
+ if (!Number.isFinite(num) && Number.isFinite(fu) && Number.isFinite(fd) && Number.isFinite(f0)) {
203
+ a.push((fu / hi / hj - 2 * (f0 / hi / hj) + fd / hi / hj - diag[i] * (hi / hj) - diag[j] * (hj / hi)) / 2);
204
+ }
205
+ else if (Number.isFinite(den) && Number.isFinite(hi ** 2) && Number.isFinite(hj ** 2))
206
+ a.push((num - diag[i] * hi ** 2 - diag[j] * hj ** 2) / den);
207
+ // where a squared step or 2 hi hj overflows, every term divided by hi hj first (issue #214)
208
+ else
209
+ a.push((num / hi / hj - diag[i] * (hi / hj) - diag[j] * (hj / hi)) / 2);
154
210
  hi /= 2;
155
211
  hj /= 2;
156
212
  }
@@ -83,7 +83,7 @@ export interface UnirootOptions {
83
83
  maxiter?: number;
84
84
  /**
85
85
  * Extend the interval when f has the same sign at both ends: `"yes"` (both ways), `"downX"` (f decreasing),
86
- * `"upX"` (f increasing) or `"no"` (default).
86
+ * `"upX"` (f increasing) or `"no"` (default). A unique prefix is accepted and anything else is an error, as in R.
87
87
  */
88
88
  extendInt?: "no" | "yes" | "downX" | "upX";
89
89
  /** f(lower), when already known. */
@@ -119,3 +119,11 @@ export interface UnirootResult {
119
119
  * @category Numerical methods
120
120
  */
121
121
  export declare function uniroot(f: (x: number) => number, lower: number, upper: number, options?: UnirootOptions): UnirootResult;
122
+ /**
123
+ * {@link uniroot} without the check of tol > 0: the internal callers that run Brent's method until the bracket is as
124
+ * narrow as the doubles allow (tol = 0, the noncentrality roots of src/htest/effectSize.ts) or whose tolerance is
125
+ * scaled by a standard error (src/internal/uniroot.ts)
126
+ *
127
+ * @internal
128
+ */
129
+ export declare function unirootCore(f: (x: number) => number, lower: number, upper: number, options?: UnirootOptions): UnirootResult;