@numero-uno-jpn/rstats 1.19.0 → 1.20.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 (135) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.ja.md +6 -6
  3. package/README.md +6 -6
  4. package/dist/causal.js +2 -2
  5. package/dist/chunks/chunk-33ODAPMR.js +2 -0
  6. package/dist/chunks/chunk-3ST6RZXG.js +2 -0
  7. package/dist/chunks/{chunk-FAKOND5W.js → chunk-4EQN74JN.js} +2 -2
  8. package/dist/chunks/chunk-5RRFO4NU.js +2 -0
  9. package/dist/chunks/{chunk-ILQ4VWSD.js → chunk-64DDDGJU.js} +2 -2
  10. package/dist/chunks/chunk-66TEOHPF.js +2 -0
  11. package/dist/chunks/chunk-6ISDROPG.js +2 -0
  12. package/dist/chunks/{chunk-OTETSONJ.js → chunk-6LAKI2QG.js} +2 -2
  13. package/dist/chunks/{chunk-SJJJ7Y4X.js → chunk-6QCH4LAL.js} +2 -2
  14. package/dist/chunks/{chunk-FCGTZ6BD.js → chunk-6RA73LXX.js} +2 -2
  15. package/dist/chunks/{chunk-MPBFXHXT.js → chunk-7C2ECGT6.js} +1 -1
  16. package/dist/chunks/{chunk-QH4GK3JN.js → chunk-7KPFNJBE.js} +2 -2
  17. package/dist/chunks/chunk-ARPXG2PG.js +2 -0
  18. package/dist/chunks/chunk-AWXW4WSX.js +2 -0
  19. package/dist/chunks/{chunk-WWRKCRTZ.js → chunk-B5GSH3AK.js} +1 -1
  20. package/dist/chunks/{chunk-XHHDBEHB.js → chunk-BLDLJHUG.js} +2 -2
  21. package/dist/chunks/{chunk-ANFN3X2M.js → chunk-BU4I544S.js} +2 -2
  22. package/dist/chunks/{chunk-LWFKGF43.js → chunk-CAUNJ7S6.js} +2 -2
  23. package/dist/chunks/chunk-DFGW4QWU.js +2 -0
  24. package/dist/chunks/{chunk-MOYWWJP4.js → chunk-DPCCSFCG.js} +1 -1
  25. package/dist/chunks/chunk-EXS5QD7V.js +2 -0
  26. package/dist/chunks/chunk-FOCHNNP3.js +2 -0
  27. package/dist/chunks/{chunk-VNLSP22M.js → chunk-HEPGGURG.js} +2 -2
  28. package/dist/chunks/chunk-INNFAVT3.js +2 -0
  29. package/dist/chunks/chunk-JEELIABM.js +2 -0
  30. package/dist/chunks/chunk-KNF2GPJV.js +2 -0
  31. package/dist/chunks/chunk-L4ZS7MAX.js +2 -0
  32. package/dist/chunks/{chunk-7D7FBLWD.js → chunk-LZAB4M7P.js} +2 -2
  33. package/dist/chunks/chunk-LZTDYQRS.js +3 -0
  34. package/dist/chunks/{chunk-AS2XTRHH.js → chunk-MTSU2QHB.js} +2 -2
  35. package/dist/chunks/{chunk-5NW4WT4F.js → chunk-MXRN2G7O.js} +2 -2
  36. package/dist/chunks/chunk-OFDD4GTZ.js +2 -0
  37. package/dist/chunks/chunk-OOHFFLMY.js +2 -0
  38. package/dist/chunks/chunk-OOO5AAM7.js +2 -0
  39. package/dist/chunks/chunk-PJJJR3H6.js +2 -0
  40. package/dist/chunks/chunk-PVRNAOO7.js +2 -0
  41. package/dist/chunks/chunk-Q2JLU5YD.js +2 -0
  42. package/dist/chunks/{chunk-SAFH76DR.js → chunk-QCQBK5AC.js} +2 -2
  43. package/dist/chunks/chunk-RXK4KSKH.js +2 -0
  44. package/dist/chunks/chunk-UC3YYJHM.js +4 -0
  45. package/dist/chunks/chunk-UPACHZ4F.js +2 -0
  46. package/dist/chunks/{chunk-DXSVV47D.js → chunk-VCXPGCA4.js} +2 -2
  47. package/dist/chunks/chunk-VFL4GGYT.js +2 -0
  48. package/dist/chunks/chunk-VL72MQOQ.js +2 -0
  49. package/dist/chunks/chunk-VSV5QGXX.js +2 -0
  50. package/dist/chunks/{chunk-U6RXYALO.js → chunk-WMEF5XWO.js} +2 -2
  51. package/dist/chunks/chunk-X6JS6ZZB.js +2 -0
  52. package/dist/chunks/chunk-YEDVOX5V.js +2 -0
  53. package/dist/chunks/chunk-ZCTB4N5J.js +3 -0
  54. package/dist/descriptive.js +2 -2
  55. package/dist/distributions.js +2 -2
  56. package/dist/entries/tests.d.ts +5 -0
  57. package/dist/entries/tests.js +5 -0
  58. package/dist/entries/timeseries.d.ts +11 -0
  59. package/dist/entries/timeseries.js +11 -0
  60. package/dist/linalg.js +2 -2
  61. package/dist/meta/metabin.d.ts +32 -0
  62. package/dist/meta/metabin.js +137 -0
  63. package/dist/meta/metaextra.d.ts +153 -0
  64. package/dist/meta/metaextra.js +290 -0
  65. package/dist/meta/metagen.d.ts +124 -0
  66. package/dist/meta/metagen.js +263 -0
  67. package/dist/meta/metaother.d.ts +87 -0
  68. package/dist/meta/metaother.js +342 -0
  69. package/dist/meta/netmeta.d.ts +256 -0
  70. package/dist/meta/netmeta.js +547 -0
  71. package/dist/mixed.js +3 -4
  72. package/dist/models/glmFamily.js +4 -1
  73. package/dist/models/metaAnalysis.d.ts +4 -0
  74. package/dist/models/metaAnalysis.js +100 -18
  75. package/dist/multivariate.js +2 -2
  76. package/dist/numerics.js +2 -2
  77. package/dist/regression.js +2 -2
  78. package/dist/rstats.js +20 -18
  79. package/dist/special.js +2 -2
  80. package/dist/tests.js +15 -15
  81. package/dist/timeseries/acf.js +5 -2
  82. package/dist/timeseries/arima.d.ts +154 -0
  83. package/dist/timeseries/arima.js +1007 -0
  84. package/dist/timeseries/autoArima.d.ts +70 -0
  85. package/dist/timeseries/autoArima.js +191 -0
  86. package/dist/timeseries/ets.d.ts +158 -0
  87. package/dist/timeseries/ets.js +883 -0
  88. package/dist/timeseries/forecastArima.d.ts +136 -0
  89. package/dist/timeseries/forecastArima.js +432 -0
  90. package/dist/timeseries/forecastDispatch.d.ts +83 -0
  91. package/dist/timeseries/forecastDispatch.js +130 -0
  92. package/dist/timeseries/forecastSimple.d.ts +177 -0
  93. package/dist/timeseries/forecastSimple.js +371 -0
  94. package/dist/timeseries/forecastUtils.d.ts +260 -0
  95. package/dist/timeseries/forecastUtils.js +619 -0
  96. package/dist/timeseries/holtWinters.d.ts +65 -0
  97. package/dist/timeseries/holtWinters.js +193 -0
  98. package/dist/timeseries/input.d.ts +8 -0
  99. package/dist/timeseries/input.js +27 -0
  100. package/dist/timeseries/ocsbCritical.d.ts +2 -0
  101. package/dist/timeseries/ocsbCritical.js +6 -0
  102. package/dist/timeseries/scale.d.ts +16 -0
  103. package/dist/timeseries/scale.js +48 -0
  104. package/dist/timeseries/statsTs.d.ts +128 -0
  105. package/dist/timeseries/statsTs.js +456 -0
  106. package/dist/timeseries/stl.d.ts +131 -0
  107. package/dist/timeseries/stl.js +489 -0
  108. package/dist/timeseries/tseries.d.ts +110 -0
  109. package/dist/timeseries/tseries.js +369 -0
  110. package/dist/timeseries.js +2 -2
  111. package/package.json +1 -1
  112. package/dist/chunks/chunk-2S45NNTL.js +0 -2
  113. package/dist/chunks/chunk-4JFGT4PN.js +0 -2
  114. package/dist/chunks/chunk-4JRJU5F5.js +0 -2
  115. package/dist/chunks/chunk-6ZGEYAFC.js +0 -2
  116. package/dist/chunks/chunk-BJ5WAL2C.js +0 -2
  117. package/dist/chunks/chunk-CEOSH3H2.js +0 -2
  118. package/dist/chunks/chunk-CMNKXRZF.js +0 -3
  119. package/dist/chunks/chunk-CNJLPH6W.js +0 -2
  120. package/dist/chunks/chunk-FELX2TZZ.js +0 -2
  121. package/dist/chunks/chunk-G4B2SQR6.js +0 -4
  122. package/dist/chunks/chunk-HPIZAWMT.js +0 -2
  123. package/dist/chunks/chunk-I5XUWUEV.js +0 -2
  124. package/dist/chunks/chunk-JLFRYDYO.js +0 -2
  125. package/dist/chunks/chunk-JXKHFSGK.js +0 -2
  126. package/dist/chunks/chunk-LBU73UMS.js +0 -2
  127. package/dist/chunks/chunk-LSZTDKIB.js +0 -2
  128. package/dist/chunks/chunk-M5J3DHXB.js +0 -2
  129. package/dist/chunks/chunk-NWNJEAKI.js +0 -2
  130. package/dist/chunks/chunk-QVE7V5UG.js +0 -2
  131. package/dist/chunks/chunk-RMGEIU4Z.js +0 -2
  132. package/dist/chunks/chunk-TVU4N6BA.js +0 -2
  133. package/dist/chunks/chunk-W4EITKLJ.js +0 -2
  134. package/dist/chunks/chunk-XJMBX6A2.js +0 -2
  135. package/dist/chunks/chunk-YZ6SBFFG.js +0 -2
package/CHANGELOG.md CHANGED
@@ -7,6 +7,44 @@ While the version is 0.x, a minor release (0.y.0) may contain breaking changes;
7
7
  they are listed under **Breaking** for each release. From 1.0.0 the project follows
8
8
  [Semantic Versioning](https://semver.org/).
9
9
 
10
+ ## 1.20.0 - 2026-11-28
11
+
12
+ ### Added
13
+
14
+ - **Time series** in `/timeseries` (after stats, forecast and tseries; values only, no plots): `arima`, `predictArima`,
15
+ `arima0`, `forecastArima` (forecast's `Arima`, with drift and Box-Cox), `forecastFromArima`, `autoArima`, `ets`,
16
+ `forecastEts`, `holtWinters`, `predictHoltWinters`, `stl`, `mstl`, `stlm`, `forecastStlm`, `forecast` (a dispatcher),
17
+ `decompose`, `tsFilter` (stats' `filter`), `diffinv`, `ar`, `predictAr`, `boxTest`, `supsmu`; the simple methods `meanf`,
18
+ `rwf`, `naive`, `snaive`, `ses`, `holt`, `hw`, `thetaf`, `croston`, `stlf`, `tslm`; `boxCox`, `invBoxCox`,
19
+ `boxCoxLambda`, `ndiffs`, `nsdiffs`, `ocsbTest`, `ocsbCritical`, `kpssStatistic`, `kpssPValue`, `minRootModulus`,
20
+ `accuracy`, `ma`, `fourier`, `seasonaldummy`, `monthdays`, `easter`, `easterSunday`, `bizdays`, `dmTest`, `cvLm`,
21
+ `checkresiduals`, `tsCV`, `arimaorder`, `specAr`, `findfrequency`, `naInterp`, `tsoutliers`, `tsclean`, `seasadj`,
22
+ `seasonalComponent`, `trendcycle`, `remainder`; tseries' `adfTest`, `kpssTest`, `ppTest`, `poTest`, `jarqueBeraTest`,
23
+ `runsTest`, `terasvirtaTest`, `whiteTest`. Fits and tests are exact from 1e-300 to 2^1000 times a series, short and
24
+ degenerate series and missing values are handled as R handles them, and infinite values are errors
25
+ ([the differences](docs/differences-from-r.md#time-series-and-meta-analysis-1200)).
26
+ - **Meta-analysis** in `/tests` (after meta): `metagen`, `metabin`, `metacont`, `metainc`, `metacor`, `metamean`,
27
+ `metarate`, `metaprop`, `metapropGlmm`, `metaSubgroup`, `metabias`, `metareg`, `metainf`, `metacum`, `baujat`,
28
+ `trimfill`, `heterogeneityIntervals`, `genqInterval`, `pWeightedChisq`; **network meta-analysis** (after netmeta):
29
+ `netmeta`, `netrank`, `netsplit`, `netleague`, `decompDesign`, `netmeasures`, `netconnection`, `pairwise`, `netcomb`,
30
+ `discomb`, `netposet`.
31
+
32
+ ### Fixed
33
+
34
+ - `rma` with `method: "PM"` or `"EB"` returned NaN when Q(0) <= k - p; it now gives tau2 = 0, as metafor.
35
+ - `confintRma`'s Q-profile (and profile-likelihood) bounds for tau2 were off away from unit scale (from 2e-6 at study
36
+ variances 1e-8 to wrong values at 1e±150); they are now exact at any scale.
37
+ - `rma` is faster with many studies (k = 1000: 0.15 s instead of 22 s), with the same results.
38
+ - `arima`'s likelihood is faster (the stationary covariance of the ARMA in closed form): seasonal `autoArima` searches
39
+ take about half the time.
40
+ - `rma` and `metareg` with moderators of very different scales (1e±150 and beyond) or with a large common value
41
+ (x + 1e8) reported the model matrix as not of full rank; they now fit, with the same coefficients. Effects beyond
42
+ 1e±60 are fitted on a standardised scale (they were off or failed, also through `metabias` and `trimfill`).
43
+ - `acf` and `ccf` of a series with a large common value (x + 1e8) are exact (R's lose about 1e-9 to the mean).
44
+ - `glmer` with a binomial response of rare events (proportions about 1e-5 with prior weights 1e5 and beyond) failed
45
+ ("the minimisation of the deviance did not converge"; R fits): the binomial deviance lost digits there. `glm`'s
46
+ binomial deviance is more accurate there too.
47
+
10
48
  ## 1.19.0 - 2026-11-26
11
49
 
12
50
  ### Added
package/README.ja.md CHANGED
@@ -16,7 +16,7 @@ JavaScript とブラウザで使える、R と互換の統計関数のライブ
16
16
  - **どこでも動きます。** ESM のみで、依存パッケージはなく、Node 専用の API も使っていません。
17
17
  tree-shaking が効きます (`pnorm` だけなら gzip で 1.6 KB)。
18
18
 
19
- 状態: **1.19.0。** R の stats パッケージの数値計算の中心
19
+ 状態: **1.20.0。** R の stats パッケージの数値計算の中心
20
20
  (分布・記述統計・検定・線形モデル・特殊関数・数値計算・線形代数の基本) を、R と同じ結果でカバーすることを目指しています。残っている作業は
21
21
  [ROADMAP.ja.md](ROADMAP.ja.md)、変更履歴は [CHANGELOG.md](CHANGELOG.md) (英語) にあります。
22
22
 
@@ -218,14 +218,14 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
218
218
  | 特殊関数 | `gamma`, `lgamma`, `beta`, `lbeta`, `choose`, `lchoose`, `factorial`, `lfactorial`, `digamma`, `trigamma`, `psigamma`, `besselI`, `besselK`, `besselJ`, `besselY`。R にはない `erf`, `erfc`, `erfinv`, `erfcinv`, `gammainc`, `perm` と、R の C API (Rmath.h) の `log1pmx`, `lgamma1p`, `log1mexp`, `log1pexp` も |
219
219
  | 分布 (d/p/q) | 正規、t、カイ二乗、F、ベータ、ガンマ、二項、ポアソン、一様、指数、対数正規、ロジスティック、コーシー、ワイブル、幾何、負の二項、超幾何、Wilcoxon の符号付き順位と順位和、スチューデント化された範囲 (`ptukey`, `qtukey`)、非心カイ二乗・t・F・ベータ (`ncp`)。多項分布の確率 (`dmultinom`)。逆ガンマ、Kumaraswamy、Pareto、三角、Laplace (extraDistr) と逆正弦。`distSummary` (平均・分散・標準偏差・中央値・最頻値・歪度・尖度) |
220
220
  | 乱数 | `setSeed` (`set.seed`), `RNGkind` (Mersenne-Twister と L'Ecuyer-CMRG、`sample.kind` の Rejection と Rounding), `getRandomSeed`/`setRandomSeed` (`.Random.seed`), `nextRNGStream`/`nextRNGSubStream` (`parallel`), 26 個の `r*` 関数, `sample`, `sampleInt` (`sample.int`), `r2dtable`, `mvrnorm` (`MASS::mvrnorm`) |
221
- | 時系列 | `acf`、`pacf`、`ccf` (`stats::acf`、`stats::pacf`、`stats::ccf`)、`@numero-uno-jpn/rstats/timeseries` |
221
+ | 時系列 | `@numero-uno-jpn/rstats/timeseries` から: `acf`、`pacf`、`ccf`。`arima`、`predictArima`、`arima0`、`ar`、`holtWinters`、`stl`、`decompose`、`tsFilter` (`filter`)、`diffinv`、`boxTest` (`Box.test`)、`supsmu` (stats)。`forecastArima` (`Arima`)、`autoArima` (`auto.arima`)、`ets`、`forecast`、`meanf`、`naive`、`snaive`、`rwf`、`ses`、`holt`、`hw`、`thetaf`、`croston`、`stlf`、`stlm`、`mstl`、`tslm`、`boxCox`、`boxCoxLambda`、`ndiffs`、`nsdiffs`、`ocsbTest`、`accuracy`、`dmTest`、`tsCV`、`naInterp`、`tsoutliers`、`tsclean`、`fourier`、`easter`、`bizdays` などの補助関数 (forecast)。`adfTest`、`kpssTest`、`ppTest`、`poTest`、`jarqueBeraTest`、`runsTest`、`terasvirtaTest`、`whiteTest` (tseries) |
222
222
  | 因果推論 | `match` (傾向スコアのマッチング: `ties = FALSE`・`replace = FALSE` の `Matching::Match`。ATT・ATE・ATC、1:M、キャリパー)、`matchWeights` (`cobalt::get.w`)、`weightit` (逆確率重み: glm・cbps・ipt・ebal の `WeightIt::weightit`。ATE・ATT・ATC・ATO)、`trimWeights`・`weightSummary`、`balTab` (マッチング・重み付けの前後の標準化平均差と分散比: `cobalt::bal.tab`)、`tableOneSmd` (`tableone::ExtractSmd`)、`mediate` (因果媒介分析: `mediation::mediate`、準ベイズ近似とブートストラップ)、`simSlopes`・`johnsonNeyman` (`interactions::sim_slopes`)、`sobelTest`・`mediationMonteCarlo`・`moderatedMediation` (index of moderated mediation)、`@numero-uno-jpn/rstats/causal` |
223
223
  | 記述統計 | `sum`, `prod`, `mean`, `weightedMean` (`weighted.mean`), `variance` (`var`), `sd`, `median`, `range`, `cumsum`, `cumprod`, `cummax`, `cummin`, `diff`, `quantile`, `IQR`, `fivenum`, `mad`, `rank`, `cov`, `cor`, `tabulate`, `table`, `unique`, `cut`, `findInterval`, `pretty`, `hist`, `ecdf`, `scale`, `skewness`, `kurtosis`, `geometricMean`, `modes`, `meanAD`, `cv`。管理図 (qcc): `qcc` (xbar・R・S・個別値・p・np・c・u・g)、`shewhartRules`、`cusum`、`ewma`、`ewmaSmooth`、`ocCurves`、`processCapability`、`mqcc` (Hotelling の T2)、`qccOverdispersionTest`、`paretoChart`、`qccGroups`、メディアン管理図 `medianChart` |
224
224
  | 検定 | `tTest`, `chisqTest`, `fisherTest`, `wilcoxTest`, `corTest`, `binomTest`, `poissonTest`, `propTest`, `mcnemarTest`, `varTest`, `bartlettTest`, `kruskalTest`, `friedmanTest`, `quadeTest`, `flignerTest`, `moodTest`, `onewayTest`, `shapiroTest`, `mantelhaenTest`, `ansariTest`, `ksTest`, `pairwiseTTest`, `pairwiseWilcoxTest`, `pairwisePropTest`, `aov` (一元配置。表は当てはめの `aovSummary`), `TukeyHSD`, `zTest`, `brunnerMunzelTest`, `tamhaneT2Test` (Tamhane の T2 と T2')、`pageTest`、`grubbsTest`・`pgrubbs`・`qgrubbs`、`pAdjust` (`p.adjust`) |
225
225
  | 分散分析 | formula で呼ぶ `aov` と `aovSummary` (多元、交互作用、共変量、`Error()` の層), `anova` (`anova.lm`。逐次の表とモデルの比較), `Anova` (car の Type II と III), `aovEz` (afex。反復測定と混合計画、Greenhouse-Geisser と Huynh-Feldt の補正、一般化 η² と偏 η²), `mauchlyTest` (`mauchly.test`) |
226
226
  | 効果量と検出力 | `cohensD`, `hedgesG` (effectsize。信頼区間は厳密な限界), `etaSquared`, `omegaSquared`, `epsilonSquared` (偏・一般化。`anova` と `Anova` の表から), `powerTTest`, `powerPropTest`, `powerAnovaTest` (`power.*.test`), `pwrTTest`, `pwrT2nTest`, `pwr2pTest`, `pwr2p2nTest`, `pwrPTest`, `pwrNormTest`, `pwrRTest`, `pwrChisqTest`, `pwrAnovaTest`, `pwrF2Test`, `esH`, `esW1`, `esW2`, `cohenES` (pwr) |
227
227
  | 試験デザインの標本サイズと検出力 | `epiSsequb`・`epiSsequc`・`epiSsninfb`・`epiSsninfc`・`epiSssupb`・`epiSssupc` (epiR: 比率と平均の同等性・非劣性・優越性)、`powerPaired2x2` (対応のある 2 × 2 表の正確な McNemar 検定の検出力)、`ssizeCT`・`powerCT`・`ssizeEpi`・`powerEpi`・`numDEpi` (生存時間の標本サイズと検出力)、`ph2simon` (Simon の 2 段階デザイン) |
228
- | メタアナリシス | `escalc` (効果量と標本分散)、`rma` (等効果・ランダム効果のメタアナリシスとメタ回帰)、`confintRma`・`predictRma`・`regtest` (metafor) |
228
+ | メタアナリシス | `escalc` (効果量と標本分散)、`rma` (等効果・ランダム効果のメタアナリシスとメタ回帰)、`confintRma`・`predictRma`・`regtest` (metafor)。`metagen`・`metabin`・`metacont`・`metainc`・`metacor`・`metamean`・`metarate`・`metaprop`・`metapropGlmm`・`metaSubgroup`・`metabias`・`metareg`・`metainf`・`metacum`・`baujat`・`trimfill` (meta)。ネットワークメタアナリシス: `netmeta`・`netrank`・`netsplit`・`netleague`・`decompDesign`・`netmeasures`・`netconnection`・`pairwise`・`netcomb`・`discomb`・`netposet` (netmeta) |
229
229
  | 線形モデル | `lm` (formula とデータフレーム、または行列で渡す。`summary` の値も返す), `modelMatrix` (`model.matrix`), `confint`, `predict`。`glm` (formula とデータフレーム、または行列で渡す。R の `stats` のすべての族とリンク) と `glmSummary` (`summary.glm`)、`svyglm` (逆確率重みに対する `survey::svyglm`: デザインに基づく標準誤差)、`glmResiduals` (4 種類)、`glmHatvalues`、`glmRstandard`、`glmCooksDistance`、`glmPredict` (標準誤差つき)、`glmConfint` (プロファイル尤度、厳密な限界)、`glmAnova` (`anova.glm`)。`vcovHC`、`vcovCL` (sandwich: HC0〜HC5、一元と多元のクラスター)、`coeftest`、`coefci` (lmtest)。`step`、`stepAIC` (lm と glm の AIC・BIC による段階的な変数選択)、`drop1`、`add1`、`extractAIC` |
230
230
  | 回帰 | `tobit`・`tobitSummary` (AER: `survreg` の上の Tobit 回帰、下限・上限、survreg のどの分布でも)、`betareg`・`betaregSummary`・`betaregConfint`・`betaregPredict`・`betaregResiduals` (betareg: 精度が定数か回帰のベータ回帰、平均のリンク 6 つ、最尤・バイアス補正・バイアス減少)、`loglin`・`loglm`・`loglmResiduals`・`loglmAnova` (反復比例当てはめによる対数線形モデル)、`multinom`・`multinomSummary`・`multinomConfint`・`multinomPredict`・`multinomAnova`・`multinomVcov` (nnet: 重みと decay つきの多項ロジスティック回帰)、`polr`・`polrSummary`・`polrVcov`・`polrPredict`・`polrConfint`・`polrAnova` (MASS: logistic・probit・cloglog・loglog・cauchit のリンクによる順序ロジスティック回帰)、`rlm`・`rlmSummary`・`rlmVcov`・`psiHuber`・`psiHampel`・`psiBisquare` (MASS: M 推定と MM 推定によるロバスト回帰)、`nls`・`nlsSummary`・`nlsVcov`・`nlsPredict`・`nlsConfint`・`nlsAnova` (非線形最小二乗法: 既定・`plinear`・`port` のアルゴリズムと 10 個の自己開始モデル)、`rq`・`rqSummary`・`rqPredict`・`rqPredictInterval`・`rqAnova` (分位点回帰)、`geeglm`・`geeSummary`・`geeVcov`・`geePredict`・`geeAnova`・`geeQIC` (一般化推定方程式)、`glmnet`・`glmnetCoef`・`glmnetPredict`・`cvGlmnet` (Gaussian・binomial・Poisson・multinomial の正則化回帰)、`btm`・`btAbilities`・`countsToBinomial` (BradleyTerry2: 一対比較、対象の共変量と変量効果の PQL も)、`qvcalc`・`worstErrors` (準分散)。`@numero-uno-jpn/rstats/regression` から import します |
231
231
  | 多変量解析 | `manova`・`manovaSummary` (逐次 MANOVA: Pillai・Wilks・Hotelling-Lawley・Roy)、`lda`・`ldaPredict` (線形判別分析)、`cancor` (正準相関)、`dist`・`asDist`・`hclust`・`cutree`・`kmeans` (クラスタ分析)、`cmdscale` (古典的多次元尺度法)、`ca`・`caSummary`・`caCoord` (対応分析)、`mjca` (多重対応分析)、`sammon`・`isoMDS` (非計量多次元尺度法)。`@numero-uno-jpn/rstats/multivariate` から import します |
@@ -302,7 +302,7 @@ double-double 演算で計算しているためです。詳しくは [docs/ja/ac
302
302
  | `lmer` (`/mixed` から) / `lmerSummary`・`lmerContest`・`lmerAnova` も | 19.4 / 70.0 KB |
303
303
  | `glmer` (`/mixed` から) / `glmerSummary`・`glmerAnova`・`glmerPredict` も | 47.2 / 66.1 KB |
304
304
  | `polr` / `rlm` / `nls` (`/regression` から) | 25.0 / 14.6 / 8.0 KB |
305
- | すべて (`/mixed` と `/regression` を除く) | 348.2 KB |
305
+ | すべて (`/mixed` と `/regression` を除く) | 379.9 KB |
306
306
 
307
307
  (`npm run size` で測れます。)
308
308
 
@@ -312,12 +312,12 @@ double-double 演算で計算しているためです。詳しくは [docs/ja/ac
312
312
  `/regression` の `polr`・`rlm`・`nls` とその関数は、この方法でしか import できません。メインの入口には含めていません)。
313
313
 
314
314
  バンドラを使わない場合は、1 ファイルにまとめたビルド `dist/rstats.js` (`/mixed` と `/regression` 以外のすべての関数を含む
315
- minify 済みの ES モジュール、gzip で 348 KB) を jsDelivr から読み込めます。jsDelivr は、npm のリリースを
315
+ minify 済みの ES モジュール、gzip で 380 KB) を jsDelivr から読み込めます。jsDelivr は、npm のリリースを
316
316
  そのまま配信します。
317
317
 
318
318
  ```html
319
319
  <script type="module">
320
- import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.19.0/dist/rstats.js";
320
+ import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.20.0/dist/rstats.js";
321
321
  console.log(pnorm(1.96)); // ≈ 0.9750021049
322
322
  </script>
323
323
  ```
package/README.md CHANGED
@@ -14,7 +14,7 @@ R-compatible statistical functions for JavaScript and the browser, written in Ty
14
14
  - **Runs anywhere.** ESM only, no dependencies, no Node-specific APIs, tree-shakable
15
15
  (`pnorm` alone is 1.6 KB gzipped).
16
16
 
17
- Status: **1.19.0.** The goal is to cover the numerical core of R's
17
+ Status: **1.20.0.** The goal is to cover the numerical core of R's
18
18
  `stats` package (distributions, descriptive statistics, hypothesis tests, linear models, special
19
19
  functions, numerical methods and the basics of linear algebra) with R-compatible results; see [ROADMAP.md](ROADMAP.md) for what remains. See [CHANGELOG.md](CHANGELOG.md).
20
20
 
@@ -216,14 +216,14 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
216
216
  | Special functions | `gamma`, `lgamma`, `beta`, `lbeta`, `choose`, `lchoose`, `factorial`, `lfactorial`, `digamma`, `trigamma`, `psigamma`, `besselI`, `besselK`, `besselJ`, `besselY`; also `erf`, `erfc`, `erfinv`, `erfcinv`, `gammainc` and `perm`, which R lacks, and `log1pmx`, `lgamma1p`, `log1mexp`, `log1pexp` from R's C API (Rmath.h) |
217
217
  | Distributions (d/p/q) | normal, t, chi-squared, F, beta, gamma, binomial, Poisson, uniform, exponential, log-normal, logistic, Cauchy, Weibull, geometric, negative binomial, hypergeometric, Wilcoxon signed rank and rank sum, studentized range (`ptukey`, `qtukey`), non-central chi-squared, t, F and beta (`ncp`); the multinomial probability (`dmultinom`); inverse gamma, Kumaraswamy, Pareto, triangular, Laplace (extraDistr) and arcsine; `distSummary` (mean, variance, sd, median, mode, skewness, kurtosis) |
218
218
  | Random numbers | `setSeed` (`set.seed`), `RNGkind` (Mersenne-Twister and L'Ecuyer-CMRG, `sample.kind` Rejection and Rounding), `getRandomSeed`/`setRandomSeed` (`.Random.seed`), `nextRNGStream`/`nextRNGSubStream` (`parallel`), 26 `r*` functions, `sample`, `sampleInt` (`sample.int`), `r2dtable`, `mvrnorm` (`MASS::mvrnorm`) |
219
- | Time series | `acf`, `pacf`, `ccf` (`stats::acf`, `stats::pacf`, `stats::ccf`) from `@numero-uno-jpn/rstats/timeseries` |
219
+ | Time series | From `@numero-uno-jpn/rstats/timeseries`: `acf`, `pacf`, `ccf`; `arima`, `predictArima`, `arima0`, `ar`, `holtWinters`, `stl`, `decompose`, `tsFilter` (`filter`), `diffinv`, `boxTest` (`Box.test`), `supsmu` (stats); `forecastArima` (`Arima`), `autoArima` (`auto.arima`), `ets`, `forecast`, `meanf`, `naive`, `snaive`, `rwf`, `ses`, `holt`, `hw`, `thetaf`, `croston`, `stlf`, `stlm`, `mstl`, `tslm`, `boxCox`, `boxCoxLambda`, `ndiffs`, `nsdiffs`, `ocsbTest`, `accuracy`, `dmTest`, `tsCV`, `naInterp`, `tsoutliers`, `tsclean`, `fourier`, `easter`, `bizdays` and the other helpers (forecast); `adfTest`, `kpssTest`, `ppTest`, `poTest`, `jarqueBeraTest`, `runsTest`, `terasvirtaTest`, `whiteTest` (tseries) |
220
220
  | Causal inference | `match` (propensity score matching: `Matching::Match` with `ties = FALSE`, `replace = FALSE`; ATT, ATE and ATC, 1:M, caliper), `matchWeights` (`cobalt::get.w`), `weightit` (inverse probability weights: `WeightIt::weightit` with glm, cbps, ipt and ebal; ATE, ATT, ATC and ATO), `trimWeights` and `weightSummary`, `balTab` (standardized mean differences and variance ratios before and after: `cobalt::bal.tab`) and `tableOneSmd` (`tableone::ExtractSmd`); `mediate` (causal mediation analysis: `mediation::mediate`, quasi-Bayesian and bootstrap), `simSlopes` and `johnsonNeyman` (`interactions::sim_slopes`), `sobelTest`, `mediationMonteCarlo` and `moderatedMediation` (the index of moderated mediation), from `@numero-uno-jpn/rstats/causal` |
221
221
  | Descriptive statistics | `sum`, `prod`, `mean`, `weightedMean` (`weighted.mean`), `variance` (`var`), `sd`, `median`, `range`, `cumsum`, `cumprod`, `cummax`, `cummin`, `diff`, `quantile`, `IQR`, `fivenum`, `mad`, `rank`, `cov`, `cor`, `tabulate`, `table`, `unique`, `cut`, `findInterval`, `pretty`, `hist`, `ecdf`, `scale`, `skewness`, `kurtosis`, `geometricMean`, `modes`, `meanAD`, `cv`; control charts (qcc): `qcc` (xbar, R, S, individual values, p, np, c, u, g), `shewhartRules`, `cusum`, `ewma`, `ewmaSmooth`, `ocCurves`, `processCapability`, `mqcc` (Hotelling's T2), `qccOverdispersionTest`, `paretoChart`, `qccGroups`, and the median chart `medianChart` |
222
222
  | Hypothesis tests | `tTest`, `chisqTest`, `fisherTest`, `wilcoxTest`, `corTest`, `binomTest`, `poissonTest`, `propTest`, `mcnemarTest`, `varTest`, `bartlettTest`, `kruskalTest`, `friedmanTest`, `quadeTest`, `flignerTest`, `moodTest`, `onewayTest`, `shapiroTest`, `mantelhaenTest`, `ansariTest`, `ksTest`, `pairwiseTTest`, `pairwiseWilcoxTest`, `pairwisePropTest`, `aov` (one way, a fit whose table is `aovSummary`), `TukeyHSD`, `zTest`, `brunnerMunzelTest`, `tamhaneT2Test` (Tamhane's T2/T2'), `pageTest`, `grubbsTest`, `pgrubbs`, `qgrubbs`, `pAdjust` (`p.adjust`) |
223
223
  | Analysis of variance | `aov` and `aovSummary` with a formula (several factors, interactions, covariates, `Error()` strata), `anova` (`anova.lm`, sequential and model comparison), `Anova` (car: types II and III), `aovEz` (afex: repeated-measures and mixed designs, Greenhouse-Geisser and Huynh-Feldt corrections, generalized and partial eta squared), `mauchlyTest` (`mauchly.test`) |
224
224
  | Effect sizes and power | `cohensD`, `hedgesG` (effectsize, with exact confidence limits), `etaSquared`, `omegaSquared`, `epsilonSquared` (partial, generalized, from `anova` and `Anova` tables); `powerTTest`, `powerPropTest`, `powerAnovaTest` (`power.*.test`); `pwrTTest`, `pwrT2nTest`, `pwr2pTest`, `pwr2p2nTest`, `pwrPTest`, `pwrNormTest`, `pwrRTest`, `pwrChisqTest`, `pwrAnovaTest`, `pwrF2Test`, `esH`, `esW1`, `esW2`, `cohenES` (pwr) |
225
225
  | Sample size and power for trial designs | `epiSsequb`, `epiSsequc`, `epiSsninfb`, `epiSsninfc`, `epiSssupb`, `epiSssupc` (epiR: equivalence, non-inferiority and superiority for proportions and means), `powerPaired2x2` (exact paired McNemar power), `ssizeCT`, `powerCT`, `ssizeEpi`, `powerEpi`, `numDEpi` (survival sample size and power), `ph2simon` (Simon two-stage designs) |
226
- | Meta-analysis | `escalc` (effect sizes and sampling variances), `rma` (equal- and random-effects meta-analysis and meta-regression), `confintRma`, `predictRma`, `regtest` (metafor) |
226
+ | Meta-analysis | `escalc` (effect sizes and sampling variances), `rma` (equal- and random-effects meta-analysis and meta-regression), `confintRma`, `predictRma`, `regtest` (metafor); `metagen`, `metabin`, `metacont`, `metainc`, `metacor`, `metamean`, `metarate`, `metaprop`, `metapropGlmm`, `metaSubgroup`, `metabias`, `metareg`, `metainf`, `metacum`, `baujat`, `trimfill` (meta); network meta-analysis: `netmeta`, `netrank`, `netsplit`, `netleague`, `decompDesign`, `netmeasures`, `netconnection`, `pairwise`, `netcomb`, `discomb`, `netposet` (netmeta) |
227
227
  | Linear models | `lm` (a formula and a data frame, or a matrix, with the `summary` quantities), `modelMatrix` (`model.matrix`), `confint`, `predict`; `glm` (a formula and a data frame, or a matrix; every family and link of R's `stats`) with `glmSummary` (`summary.glm`), `svyglm` (`survey::svyglm` for inverse probability weights: design-based standard errors), `glmResiduals` (the four kinds), `glmHatvalues`, `glmRstandard`, `glmCooksDistance`, `glmPredict` (with standard errors), `glmConfint` (profile likelihood, exact limits), `glmAnova` (`anova.glm`); `vcovHC`, `vcovCL` (sandwich: HC0 to HC5, one-way and multi-way clustered), `coeftest`, `coefci` (lmtest); `step`, `stepAIC` (stepwise selection by AIC or BIC for lm and glm), `drop1`, `add1`, `extractAIC` |
228
228
  | Regression | `tobit`, `tobitSummary` (AER: tobit regression on `survreg`, left and right limits, any survreg distribution); `betareg`, `betaregSummary`, `betaregConfint`, `betaregPredict`, `betaregResiduals` (betareg: beta regression with a constant or modelled precision, six mean links, maximum likelihood, bias-corrected and bias-reduced); `loglin`, `loglm`, `loglmResiduals`, `loglmAnova` (log-linear models by iterative proportional fitting); `multinom`, `multinomSummary`, `multinomConfint`, `multinomPredict`, `multinomAnova`, `multinomVcov` (nnet: multinomial logistic regression with weights and decay), `polr`, `polrSummary`, `polrVcov`, `polrPredict`, `polrConfint`, `polrAnova` (MASS: ordinal logistic regression with logistic, probit, cloglog, loglog and cauchit links); `rlm`, `rlmSummary`, `rlmVcov`, `psiHuber`, `psiHampel`, `psiBisquare` (MASS: robust M and MM regression); `nls`, `nlsSummary`, `nlsVcov`, `nlsPredict`, `nlsConfint`, `nlsAnova` (nonlinear least squares: default, `plinear` and `port` algorithms, and 10 self-starting models); `rq`, `rqSummary`, `rqPredict`, `rqPredictInterval`, `rqAnova` (quantile regression); `geeglm`, `geeSummary`, `geeVcov`, `geePredict`, `geeAnova`, `geeQIC` (generalized estimating equations); `glmnet`, `glmnetCoef`, `glmnetPredict`, `cvGlmnet` (penalized Gaussian, binomial, Poisson and multinomial regression); `btm`, `btAbilities`, `countsToBinomial` (BradleyTerry2: paired comparisons, with player covariates and random effects by PQL), `qvcalc`, `worstErrors` (quasi variances), from `@numero-uno-jpn/rstats/regression` |
229
229
  | Multivariate analysis | `manova`, `manovaSummary` (sequential MANOVA: Pillai, Wilks, Hotelling-Lawley and Roy); `lda`, `ldaPredict` (linear discriminant analysis); `cancor` (canonical correlation); `dist`, `asDist`, `hclust`, `cutree`, `kmeans` (cluster analysis); `cmdscale` (classical multidimensional scaling); `ca`, `caSummary`, `caCoord` (correspondence analysis); `mjca` (multiple correspondence analysis); `sammon` and `isoMDS` (non-metric multidimensional scaling), from `@numero-uno-jpn/rstats/multivariate` |
@@ -301,7 +301,7 @@ removed. Approximate sizes after minification and gzip:
301
301
  | `lmer` (from `/mixed`) / with `lmerSummary`, `lmerContest`, `lmerAnova` | 19.4 / 70.0 KB |
302
302
  | `glmer` (from `/mixed`) / with `glmerSummary`, `glmerAnova`, `glmerPredict` | 47.2 / 66.1 KB |
303
303
  | `polr` / `rlm` / `nls` (from `/regression`) | 25.0 / 14.6 / 8.0 KB |
304
- | everything (except `/mixed` and `/regression`) | 348.2 KB |
304
+ | everything (except `/mixed` and `/regression`) | 379.9 KB |
305
305
 
306
306
  (`npm run size` measures these.)
307
307
 
@@ -312,11 +312,11 @@ Each area is also a subpath export, for importing one area without the rest:
312
312
  areas are only available this way, not from the main entry point.
313
313
 
314
314
  Without a bundler, load the single-file build `dist/rstats.js` (one minified ES module with every
315
- function except those of `/mixed` and `/regression`, 348 KB gzipped) from jsDelivr, which serves each npm release:
315
+ function except those of `/mixed` and `/regression`, 380 KB gzipped) from jsDelivr, which serves each npm release:
316
316
 
317
317
  ```html
318
318
  <script type="module">
319
- import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.19.0/dist/rstats.js";
319
+ import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.20.0/dist/rstats.js";
320
320
  console.log(pnorm(1.96)); // ≈ 0.9750021049
321
321
  </script>
322
322
  ```
package/dist/causal.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! rStats.js 1.19.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
- import{a as Fe,b as Ne}from"./chunks/chunk-ILQ4VWSD.js";import{p as Pe,x as ne,y as re}from"./chunks/chunk-CEOSH3H2.js";import{a as Ie}from"./chunks/chunk-OTETSONJ.js";import{a as ae}from"./chunks/chunk-DXSVV47D.js";import{h as ke}from"./chunks/chunk-LSZTDKIB.js";import{a as ge}from"./chunks/chunk-YZ6SBFFG.js";import{b as Xe}from"./chunks/chunk-W4EITKLJ.js";import{f as Ue,h as ve,j as Be}from"./chunks/chunk-FELX2TZZ.js";import"./chunks/chunk-SAFH76DR.js";import"./chunks/chunk-MOYWWJP4.js";import"./chunks/chunk-U6RXYALO.js";import"./chunks/chunk-G4B2SQR6.js";import{a as Ge}from"./chunks/chunk-7D7FBLWD.js";import{d as te}from"./chunks/chunk-FCGTZ6BD.js";import"./chunks/chunk-QVE7V5UG.js";import"./chunks/chunk-NWNJEAKI.js";import{a as Ke}from"./chunks/chunk-5NW4WT4F.js";import{C as ue,w as He,x as Ce}from"./chunks/chunk-HPIZAWMT.js";import"./chunks/chunk-2S45NNTL.js";import"./chunks/chunk-ANFN3X2M.js";import{a as Re}from"./chunks/chunk-VNLSP22M.js";import{e as De,f as Ve,g as ze,m as We,n as we,o as be}from"./chunks/chunk-AS2XTRHH.js";import"./chunks/chunk-WWRKCRTZ.js";import"./chunks/chunk-MPBFXHXT.js";import"./chunks/chunk-XJMBX6A2.js";import"./chunks/chunk-BJ5WAL2C.js";import{t as qe,u as Z,v as fe}from"./chunks/chunk-CNJLPH6W.js";import{h as ee,k as B,l as Te}from"./chunks/chunk-LBU73UMS.js";import{l as K}from"./chunks/chunk-JXKHFSGK.js";function Ye(e){let s=0;for(let n of e)Math.abs(n)>s&&(s=Math.abs(n));return s>0&&Number.isFinite(s)?Math.floor(Math.log2(s)):0}function ie(e){let s=Ye(e),n=e.map(o=>ee(o,-s)),t=n[0]??0,r=n.map(o=>o-t),m=Ye(r);return{values:r.map(o=>ee(o,-m)),unitExp:s+m}}var Et=["estimand","M","caliper"];function Mt(e,s,n={}){K(n,Et,"match");let{estimand:t="ATT",M:r=1,caliper:m}=n,o=e.length;if(s.length!==o)throw new RangeError("length(Tr) != nrow(X)");if(t!=="ATT"&&t!=="ATE"&&t!=="ATC")throw new RangeError(`invalid 'estimand': ${String(t)}`);if(!Number.isInteger(r)||r<1)throw new RangeError("'M' must be a positive integer");if(m!==void 0&&!(m>0&&Number.isFinite(m)))throw new RangeError("'caliper' must be a positive number");let l=[];for(let g=0;g<o;g++){let A=e[g];if(A===!0||A===1)l.push(!0);else if(A===!1||A===0)l.push(!1);else throw typeof A=="number"&&Number.isNaN(A)?new RangeError("Match(): input includes NAs"):new RangeError("Treatment indicator ('Tr') must be a logical variable---i.e., TRUE (1) or FALSE (0)");if(!Number.isFinite(s[g]))throw new RangeError("Match(): input includes NAs")}if(!l.includes(!0)||!l.includes(!1))throw new RangeError("Treatment indicator ('Tr') must contain both treatment and control observations");let i=0;for(let g of s)i=Math.max(i,Math.abs(g));let c=i>0?Math.floor(Math.log2(i)):0,a=s.map(g=>ee(g,-c)),u=null,E=1/0;if(m!==void 0){let{values:g,unitExp:A}=ie(a),S=0;for(let O of g)S+=O;S/=o;let C=0;for(let O of g)C+=(O-S)*(O-S);let $=ee(Math.sqrt(C/o),A);E=m*$,u=ee(E,c)}let b=[new Array(o).fill(!1),new Array(o).fill(!1)],f=[],d=[],y=[],M=[],v=0,p=0;for(let g=0;g<o;g++){let A=l[g];if(A?t==="ATC":t==="ATT")continue;let S=b[A?0:1],C=[];for(let x=0;x<o;x++){if(l[x]===A)continue;let F=Math.abs(a[g]-a[x]);F>E||S[x]||C.push({j:x,d:F})}if(C.length<r){p++,y.push(g+1);continue}let O=C.map(x=>x.d).sort((x,F)=>x-F)[r-1],j=C.filter(x=>x.d<=O).map(x=>x.j),V;if(j.length===r)V=j;else{M.push(j.length),V=[],j=j.slice();for(let x=0;x<r;x++){let F=j.length,D=Math.min(F-1,Math.floor(F*(1-ze())));V.push(j[D]),j.splice(D,1)}V.sort((x,F)=>x-F)}for(let x of V)S[x]=!0,f.push((A?g:x)+1),d.push((A?x:g)+1);v++}let h=new Set([...f,...d]),T=u===null?[]:y.filter(g=>!h.has(g)),w=[];return f.length===0&&w.push("'Match' object contains no valid matches (probably because of the caliper or the exact option)."),{indexTreated:f,indexControl:d,weights:f.map(()=>1/r),indexDropped:T.length>0?T:null,caliper:m??null,ecaliper:u,nobs:o,wnobs:v,ndrops:p,estimand:t,M:r,tieSizes:M,warnings:w}}var At=["match","weightit","weights","estimand","levels","binary"],Tt=["factor"];function Je(e){let s=new Array(e.nobs).fill(0);return e.indexTreated.forEach((n,t)=>{s[n-1]+=e.weights[t],s[e.indexControl[t]-1]+=e.weights[t]}),s}function Nt(e,s){if(e===!0||e===1)return!0;if(e===!1||e===0)return!1;throw new RangeError(`'tr' must be 0 or 1 (element ${s+1})`)}function he(e,s,n,t){let r=0,m=0,o=0;for(let c=0;c<e.length;c++){if(n[c]!==t)continue;let a=s===null?1:s[c];r+=a,m+=a*a,o+=a*e[c]}let l=o/r,i=0;for(let c=0;c<e.length;c++){if(n[c]!==t)continue;let a=s===null?1:s[c];i+=a*(e[c]-l)*(e[c]-l)}return[l,i/(r-m/r)]}function Rt(e,s,n={}){K(n,At,"balTab");let{match:t,weightit:r,binary:m="raw",levels:o={}}=n;if(t!==void 0&&r!==void 0)throw new RangeError("give 'match' or 'weightit', not both");let l=t!==void 0?Je(t):r!==void 0?r.weights:n.weights,i=t?.estimand??r?.estimand??n.estimand??"ATT",c=new Set(t?.indexDropped??[]),a=t!==void 0&&t.caliper!==null,u=e.length,E=e.map(Nt);if(!E.includes(!0)||!E.includes(!1))throw new RangeError("'tr' must contain both groups");if(l!==void 0&&l.length!==u)throw new RangeError("'weights' must have the length of 'tr'");if(i==="ATO"&&l===void 0)throw new RangeError("estimand 'ATO' needs the weights");let b=[];r?.ps&&b.push(["prop.score",r.ps,"Distance"]);for(let[M,v]of Object.entries(s)){if(v.length!==u)throw new RangeError(`covariate '${M}' must have the length of 'tr'`);if(v.every(h=>typeof h=="number")){b.push([M,v,null]);continue}if(!v.every(h=>typeof h=="string"))throw new TypeError(`covariate '${M}' must be all numbers or all strings`);let p=o[M]??[...new Set(v)].sort(Re);if(v.some(h=>!p.includes(h)))throw new RangeError(`covariate '${M}' has values not among its levels`);for(let h of p.length===2?p.slice(1):p)b.push([`${M}_${h}`,v.map(T=>T===h?1:0),null])}let f=E.map(()=>!0),d=r!==void 0,y={rows:b.map(([M])=>M),type:[],diffUn:[],diffAdj:[],vRatioUn:[],vRatioAdj:[],observations:{rows:d?["Unadjusted","Adjusted"]:["All (ESS)","All (Unweighted)","Matched (ESS)","Matched (Unweighted)","Unmatched",...a?["Discarded"]:[]],control:[],treated:[]}};for(let[M,v,p]of b){if(v.some(D=>!Number.isFinite(D)))throw new RangeError(`covariate '${M}' has missing or infinite values`);let h=p===null&&new Set(v).size<=2&&v.every(D=>D===0||D===1),T=h?null:ie(v),w=T===null?v:T.values,[g,A]=he(w,null,E,!0),[S,C]=he(w,null,E,!1),$;if(i==="ATO"){let[D,Q]=he(w,l,f,!0);$=Math.sqrt(h?D*(1-D):Q)}else{let D=h?[g*(1-g),S*(1-S)]:[A,C];if($=Math.sqrt(i==="ATT"?D[0]:i==="ATC"?D[1]:(D[0]+D[1])/2),ee($,T?.unitExp??0)<Math.sqrt(Number.EPSILON)){let[Q,z]=he(w,null,f,!0);$=Math.sqrt(h?Q*(1-Q):z)}}let O=h&&m==="raw"?1:$;if(y.type.push(p??(h?"Binary":"Contin.")),y.diffUn.push(g===S?0:(g-S)/O),y.vRatioUn.push(h||C===0?NaN:A/C),l===void 0){y.diffAdj.push(NaN),y.vRatioAdj.push(NaN);continue}let[j,V]=he(w,l,E,!0),[x,F]=he(w,l,E,!1);y.diffAdj.push(j===x?0:(j-x)/O),y.vRatioAdj.push(h||F===0?NaN:V/F)}for(let M of[!1,!0]){let v=0,p=0,h=0,T=0,w=0;for(let S=0;S<u;S++){if(E[S]!==M||(v++,c.has(S+1)&&w++,l===void 0))continue;let C=l[S];p+=C,h+=C*C,C>0&&T++}let g=M?y.observations.treated:y.observations.control;if(d){g.push(v,p*p/h);continue}let A=l===void 0?[NaN,NaN,NaN]:[p*p/h,T,v-T-w];a&&A.push(w),g.push(v,v,...A)}return y}function St(e,s,n={}){K(n,Tt,"tableOneSmd");let{factor:t=!1}=n;if(e.length!==s.length)throw new RangeError("'x' and 'group' must have the same length");let r=[...new Set(s)].sort((f,d)=>f<d?-1:f>d?1:0);if(r.length!==2)throw new RangeError("'group' must have exactly two levels");let m=f=>f!==null&&!(typeof f=="number"&&Number.isNaN(f)),o=r.map(f=>e.filter((d,y)=>s[y]===f&&m(d)));if(!t){if(o.flat().some(p=>typeof p!="number"))throw new TypeError("'x' must be numeric unless factor: true");let f=ie(o.flat()).values,y=[f.slice(0,o[0].length),f.slice(o[0].length)].map(p=>{let h=p.reduce((T,w)=>T+w,0)/p.length;return[h,p.reduce((T,w)=>T+(w-h)*(w-h),0)/(p.length-1)]}),M=y[1][0]-y[0][0],v=Math.sqrt((y[0][1]+y[1][1])/2);return M===0?0:Math.abs(M)/v}let l=[...new Set(o.flat())].sort((f,d)=>typeof f=="number"&&typeof d=="number"?f-d:String(f)<String(d)?-1:String(f)>String(d)?1:0),i=o.map(f=>l.slice(1).map(d=>f.filter(y=>y===d).length/f.length)),c=i[1].map((f,d)=>f-i[0][d]);if(c.every(f=>f===0))return 0;let a=c.length,u=Array.from({length:a},(f,d)=>Array.from({length:a},(y,M)=>{let v=p=>d===M?p[d]*(1-p[d]):-p[d]*p[M];return(v(i[0])+v(i[1]))/2}));if(u.every(f=>f.every(d=>d===0)))return NaN;let E=Xe(u),b=0;for(let f=0;f<a;f++)for(let d=0;d<a;d++)b+=c[f]*E[f][d]*c[d];return Math.sqrt(b)}var Ot=["method","link","estimand","stabilize"],xt=["at","lower","treat"],oe=Number.EPSILON;function Ct(e){return e.map((s,n)=>{if(s===!0||s===1)return 1;if(s===!1||s===0)return 0;throw new RangeError(`'tr' must be 0 or 1 (element ${n+1})`)})}function kt(e,s){let n=[],t=[],r={};for(let[m,o]of Object.entries(e)){if(o.length!==s)throw new RangeError(`covariate '${m}' must have the length of 'tr'`);if(o.every(c=>typeof c=="number")){let c=o;if(c.some(a=>!Number.isFinite(a)))throw new RangeError(`covariate '${m}' has missing or infinite values`);n.push(m),t.push(c.slice());continue}if(!o.every(c=>typeof c=="string"))throw new TypeError(`covariate '${m}' must be all numbers or all strings`);let l=o,i=[...new Set(l)].sort(Re);r[m]=i;for(let c of i.slice(1))n.push(m+c),t.push(l.map(a=>a===c?1:0))}return{names:n,columns:t,factors:r}}function Qe(e){return e.map(s=>{let n=s.reduce((r,m)=>r+m,0)/s.length,t=s.reduce((r,m)=>Math.max(r,Math.abs(m-n)),0);return s.map(r=>t>0?(r-n)/t:0)})}function $t(e){let s=e[0]?.length??0,n=[new Array(s).fill(1/Math.sqrt(s))],t=[];for(let r of e){let m=Math.sqrt(r.reduce((i,c)=>i+c*c,0)),o=r.slice();for(let i=0;i<2;i++)for(let c of n){let a=o.reduce((u,E,b)=>u+E*c[b],0);for(let u=0;u<s;u++)o[u]-=a*c[u]}let l=Math.sqrt(o.reduce((i,c)=>i+c*c,0));l>1e-7*m&&(n.push(o.map(i=>i/l)),t.push(r))}return t}function st(e,s){let n=s.length,t=e.map((o,l)=>[...o,s[l]]),r=0;for(let o of e)for(let l of o)r=Math.max(r,Math.abs(l));for(let o=0;o<n;o++){let l=o;for(let i=o+1;i<n;i++)Math.abs(t[i][o])>Math.abs(t[l][o])&&(l=i);if(!(Math.abs(t[l][o])>1e-13*r))return null;[t[o],t[l]]=[t[l],t[o]];for(let i=o+1;i<n;i++){let c=t[i][o]/t[o][o];if(c!==0)for(let a=o;a<=n;a++)t[i][a]-=c*t[o][a]}}let m=new Array(n).fill(0);for(let o=n-1;o>=0;o--){let l=t[o][n];for(let i=o+1;i<n;i++)l-=t[o][i]*m[i];m[o]=l/t[o][o]}return m}function $e(e,s){return Array.from({length:s},(n,t)=>[1,...e.map(r=>r[t])])}function Ze(e,s,n){let t=n.length,r=new Array(t).fill(0);r[0]=Math.log(n[0]/s.length);let m=c=>{let a=0;for(let u of s)a+=Math.exp(e[u].reduce((E,b,f)=>E+b*c[f],0));return a-n.reduce((u,E,b)=>u+E*c[b],0)},o=m(r),l=!1,i=1e-13*Math.max(1,Math.abs(n[0]));for(let c=0;c<200;c++){let a=n.map(p=>-p),u=Array.from({length:t},()=>new Array(t).fill(0));for(let p of s){let h=e[p],T=Math.exp(h.reduce((w,g,A)=>w+g*r[A],0));for(let w=0;w<t;w++){a[w]+=T*h[w];for(let g=0;g<=w;g++)u[w][g]+=T*h[w]*h[g]}}for(let p=0;p<t;p++)for(let h=p+1;h<t;h++)u[p][h]=u[h][p];let E=Math.max(...a.map(Math.abs));if(E<=i){l=!0;break}let b=st(u,a.map(p=>-p));if(b===null||b.some(p=>!Number.isFinite(p)))break;let f=1e-12*(Math.abs(o)+1),d=1,y=r.map((p,h)=>p+b[h]),M=m(y);for(;!(M<=o+f)&&d>1e-10;)d/=2,y=r.map((p,h)=>p+d*b[h]),M=m(y);if(!(M<=o+f))break;let v=b.some((p,h)=>Math.abs(d*p)>1e-15*Math.max(1,Math.abs(r[h])));if(r.splice(0,t,...y),o=M,!v){l=E<=1e-9*Math.max(1,Math.abs(n[0]));break}}return{eta:e.map(c=>c.reduce((a,u,E)=>a+u*r[E],0)),converged:l}}var Lt={logit:{p:e=>te(e),q:e=>te(-e),d:e=>te(e)*te(-e)},probit:{p:e=>Z(e),q:e=>Z(-e),d:e=>qe(e)}};function _t(e,s,n,t,r){let m=s.length,o=r.length,l=r.slice(),i=d=>{let y=new Array(o).fill(0),M=Array.from({length:o},()=>new Array(o).fill(0));for(let v=0;v<m;v++){let p=e[v],h=p.reduce(($,O,j)=>$+O*d[j],0),T=t.p(h),w=t.q(h),g=t.d(h),A=s[v],S,C;n==="ATE"?(S=A?1/T:-1/w,C=A?-g/(T*T):-g/(w*w)):n==="ATT"?(S=A?1:-T/w,C=A?0:-g/(w*w)):n==="ATC"?(S=A?w/T:-1,C=A?-g/(T*T):0):(S=A?w:-T,C=-g);for(let $=0;$<o;$++){y[$]+=S*p[$];for(let O=0;O<o;O++)M[$][O]+=C*p[$]*p[O]}}return{g:y,J:M}},c=d=>d.reduce((y,M)=>y+M*M,0),{g:a,J:u}=i(l),E=c(a),b=!1,f=1e-12*m;for(let d=0;d<200;d++){if(Math.max(...a.map(Math.abs))<=f){b=!0;break}let y=st(u,a.map(T=>-T));if(y===null||y.some(T=>!Number.isFinite(T)))break;let M=1,v=l.map((T,w)=>T+y[w]),p=i(v),h=c(p.g);for(;!(h<E)&&M>1e-10;)M/=2,v=l.map((T,w)=>T+M*y[w]),p=i(v),h=c(p.g);if(!(h<E)){b=Math.max(...a.map(Math.abs))<=1e-8*m;break}l=v,a=p.g,u=p.J,E=h}return{eta:e.map(d=>d.reduce((y,M,v)=>y+M*l[v],0)),converged:b}}function et(e,s,n,t){switch(e){case"ATE":return s?1/n:1/t;case"ATT":return s?1:n/t;case"ATC":return s?t/n:1;default:return s?t:n}}var jt={glm:"glm.fit: algorithm did not converge",cbps:"The covariate balancing conditions could not be solved, so the covariates will not be exactly balanced.",ipt:"The optimization failed to converge; consider using fewer covariates or a different link function.",ebal:"The estimated weights do not balance the covariates, indicating the optimization arrived at a degenerate solution. Try decreasing the number of variables supplied to the optimization."},tt={cbps:"covariate balancing propensity score weighting",ipt:"inverse probability tilting",ebal:"entropy balancing"};function qt(e,s,n={}){K(n,Ot,"weightit");let{method:t="glm",estimand:r="ATE",stabilize:m=!1}=n,o=t==="ps"?"glm":t;if(!["glm","cbps","ipt","ebal"].includes(o))throw new RangeError(`unknown method '${String(t)}'`);if(!["ATE","ATT","ATC","ATO"].includes(r))throw new RangeError(`unknown estimand '${String(r)}'`);let l=o==="ebal"?null:n.link??"logit";if(l!==null&&!{glm:["logit","probit","cauchit","cloglog"],cbps:["logit","probit"],ipt:["logit"]}[o].includes(l))throw new RangeError(`link '${l}' is not available for method '${o}'`);if((o==="ipt"||o==="ebal")&&r==="ATO")throw new RangeError(`"ATO" is not an allowable estimand for ${tt[o]} with a binary treatment. Only "ATE", "ATT", and "ATC" are allowed.`);let c=[];if(m&&o==="glm"&&r!=="ATE")throw new RangeError('`stabilize` can only be supplied when `estimand = "ATE"`.');m&&o!=="glm"&&c.push(`\`stabilize\` cannot be used with ${tt[o]} and will be ignored.`);let a=Ct(e),u=a.length;if(!a.includes(0)||!a.includes(1))throw new RangeError("The treatment must have at least two unique values.");let{names:E,columns:b}=kt(s,u);if(b.length===0)throw new RangeError("'covariates' must have at least one column");let f=$t(b.map(w=>ie(w).values)),d=a.flatMap((w,g)=>w?[g]:[]),y=a.flatMap((w,g)=>w?[]:[g]),M=a.map((w,g)=>g),v=r==="ATT"?1:r==="ATC"?0:null,p=null,h,T=!0;if(o==="glm"){let w=be(()=>ve($e(f,u).map(g=>g.slice(1)),a,{family:"binomial",link:l}));T=w.converged,p=w.fittedValues.map((g,A)=>l==="logit"&&Math.abs(w.linearPredictors[A])>30?w.linearPredictors[A]>0?1-oe:oe:Math.min(Math.max(g,oe),1-oe)),h=a.map((g,A)=>et(r,g,p[A],1-p[A])),p.some(g=>g<=10*oe||g>=1-10*oe)&&c.push("Propensity scores numerically equal to 0 or 1 were estimated, indicating perfect separation. These may yield problems with inference. See `?method_glm` (`?WeightIt::method_glm()`) for details.")}else if(o==="cbps"){let w=Qe(f),g=$e(w,u),A=be(()=>ve(g.map(O=>O.slice(1)),a,{family:"binomial",link:l})).coefficients.map(O=>Number.isFinite(O)?O:0),S=Lt[l],C=_t(g,a,r,S,A);T=C.converged;let $=O=>Math.min(Math.max(O,oe),1-oe);p=C.eta.map(O=>$(S.p(O))),h=a.map((O,j)=>et(r,O,p[j],$(S.q(C.eta[j]))))}else{let w=Qe(f),g=$e(w,u),A=j=>g[0].map((V,x)=>j.reduce((F,D)=>F+g[D][x],0)),S={C:r!=="ATC",T:r!=="ATT"},C=o==="ebal"&&r==="ATE"?{C:A(M),T:A(M)}:{C:A(d),T:A(y)},$=S.C?Ze(g,y,C.C):null,O=S.T?Ze(g,d,C.T):null;if(T=($?.converged??!0)&&(O?.converged??!0),o==="ebal")h=a.map((j,V)=>j?O?Math.exp(O.eta[V]):1:$?Math.exp($.eta[V]):1);else{let j=r==="ATE"?1:0;h=a.map((V,x)=>V?O?j+Math.exp(O.eta[x]):1:$?j+Math.exp($.eta[x]):1),p=a.map((V,x)=>r==="ATT"?te($.eta[x]):r==="ATC"?te(-O.eta[x]):V?te(-O.eta[x]):te($.eta[x]))}}if(T||c.push(jt[o]),m&&o==="glm"){let w=[y.length/u,d.length/u];h=h.map((g,A)=>g*w[a[A]])}return h.every(w=>Math.abs(w-1)<Math.sqrt(oe))&&c.push("All weights are 1, possibly indicating an estimation failure."),we("weightit",{weights:h,ps:p,treat:a,estimand:r,method:o,link:l,stabilized:m&&o==="glm",focal:v,columnNames:E,converged:T,warnings:c})}function nt(e,s,n,t){let r=e.slice();if(s.length===0)return r;let m=s.map(i=>e[i]),o,l;if(n<1){let i=n<.5?1-n:n;o=ae(m,i,{type:3}),l=ae(m,1-i,{type:3})}else{if(!Number.isInteger(n))throw new RangeError("'at' must be below 1 or a whole number");if(n>=m.length)return null;let i=n>m.length/2?m.length-n:n,c=m.slice().sort((a,u)=>a-u);o=c[c.length-1-i],l=c[i]}for(let i of s)e[i]>o&&(r[i]=o),t&&e[i]<l&&(r[i]=l);return r}var ot=e=>`\`at\` must be less than ${e}, the number of units. Weights will not be trimmed.`;function Ht(e,s){K(s,xt,"trimWeights");let{at:n,lower:t=!1}=s;if(!(n>0)||!Number.isFinite(n))throw new RangeError("'at' must be a positive number");if(Array.isArray(e)||ArrayBuffer.isView(e)){let l=Array.from(e);if(s.treat!==void 0&&s.treat.length!==l.length)throw new RangeError("'treat' must have the length of 'w'");let i=nt(l,l.map((c,a)=>a),n,t);return i===null?(We("trimWeights",[ot(l.length)]),l):i}let r=e,m=r.treat.flatMap((l,i)=>r.focal===null||l!==r.focal?[i]:[]),o=nt(r.weights,m,n,t);return o===null?we("trimWeights",{...r,weights:r.weights.slice(),warnings:[ot(m.length)]}):{...r,weights:o,warnings:r.warnings.slice()}}function rt(e,s){let n=s.map(a=>e[a]),t=n.length,r=0,m=0;for(let a of n)r+=a,m+=a*a;let o=r/t,l=n.reduce((a,u)=>a+(u-o)*(u-o),0),i=n.map(a=>o>0?a/o:NaN),c=n.map((a,u)=>u).sort((a,u)=>n[u]-n[a]||a-u).slice(0,5).reverse();return{range:[Math.min(...n),Math.max(...n)],top:{index:c.map(a=>s[a]+1),weights:c.map(a=>n[a])},mean:o,coefOfVar:Math.sqrt(l/(t-1))/o,scaledMad:i.reduce((a,u)=>a+Math.abs(u-1),0)/t,negativeEntropy:i.reduce((a,u)=>a+(Number.isNaN(u)?NaN:u>0?u*Math.log(u):0),0)/t,numZeros:n.filter(a=>Math.abs(a)<1e-10).length,n:t,ess:r*r/m}}function Dt(e){let s=e.treat.flatMap((t,r)=>t?[r]:[]),n=e.treat.flatMap((t,r)=>t?[]:[r]);return{treated:rt(e.weights,s),control:rt(e.weights,n),stabilized:e.stabilized}}var Vt=new Set(["treat","mediator","treatValue","controlValue","covariates","sims","boot","bootCiType","confLevel","robustSE"]);function at(e,s,n){let t=Ue(e);if(t===void 0||typeof e.formula!="string")throw new TypeError(`the ${n} model must be a formula fit of lm or glm`);if(t.weights!==void 0||t.offset!==void 0)throw new RangeError(`weights and offsets are not supported (the ${n} model)`);let r="family"in e,m=a=>a;if(r){let a=e;if(a.family==="binomial"&&(a.link==="logit"||a.link==="probit"))m=Be(a).linkinv;else if(!(a.family==="gaussian"&&a.link==="identity"))throw new RangeError(`the ${n} model's family is not supported (binomial with logit or probit, or gaussian)`)}if(e.coefficients.some(a=>Number.isNaN(a)))throw new RangeError(`the ${n} model has aliased coefficients`);let o=e.formula,l=Ge(Ke(o,!1,!1,!0),s,{...t.contrasts===void 0?{}:{contrasts:t.contrasts},...t.levels===void 0?{}:{levels:t.levels},dropUnusedLevels:!0,anyResponse:!0}),i=r?e.model.rows:e.rows,c=r?e.model.columnNames:e.coefNames;if(l.frame.rows.length!==i.length||l.frame.rows.some((a,u)=>a!==i[u])||l.colNames.join("\0")!==c.join("\0"))throw new RangeError(`the data do not give the ${n} model's rows and columns (pass the data it was fitted on)`);return{fit:e,isGlm:r,formula:o,options:t,coef:e.coefficients.slice(),names:c,linkinv:m,d:l,rows:i}}function ye(e,s,n,t){let r=e.d.terms.variables.indexOf(s);if(r<0){if(t)throw new RangeError(`'${s}' is not a variable of the ${n} model`);return-1}if(e.d.frame.variables[r].kind!=="numeric")throw new RangeError(`'${s}' must be numeric in the ${n} model`);return r}function ut(e,s,n){let t=e.d.frame.variables.map((r,m)=>{let o=s.get(m);return o===void 0?r:{kind:"numeric",values:typeof o=="number"?new Array(n).fill(o):o.slice()}});return e.d.rowsOf(t,n)}var ce=(e,s)=>{let n=0;for(let t=0;t<e.length;t++)n+=e[t]*s[t];return n};function it(e,s,n,t){let r=e.length,m=2**-1022,o=Number.MAX_VALUE;if(s.some((a,u)=>a.some(E=>!Number.isFinite(E))||!(a[u]>=m&&a[u]<=o)))throw new RangeError(`the ${t} model's coefficient covariance is out of the double range (rescale the variables, or use boot: true)`);let l=Fe(s),i=ue(n*r),c=[];for(let a=0;a<n;a++){let u=[];for(let E=0;E<r;E++){let b=0;for(let f=0;f<r;f++)b+=i[a*r+f]*l[f][E];u.push(e[E]+b)}c.push(u)}return c}function Oe(e,s){let n=new Map(e.mCov);return n.set(e.mTreat,s),ut(e.m,n,e.n)}function Me(e,s,n){let t=new Map(e.yCov);return t.set(e.yTreat,s),t.set(e.yMed,n),ut(e.y,t,e.n)}function Se(e,s,n,t){return Me(e,s,n).map(r=>e.y.linkinv(ce(r,t)))}var Ee=(e,s)=>B(e.map((n,t)=>n-s[t]));function ht(e,s,n,t){if(xe(e.y)){let i=Me(e,e.t0,s),c=Me(e,e.t0,n),a=Me(e,e.t1,s),u=Me(e,e.t1,n),E=(b,f)=>B(b.map((d,y)=>{let M=0;for(let v=0;v<d.length;v++)M+=(d[v]-f[y][v])*t[v];return M}));return[E(i,c),E(a,u),E(u,c),E(a,i),E(a,c)]}let r=Se(e,e.t0,s,t),m=Se(e,e.t0,n,t),o=Se(e,e.t1,s,t),l=Se(e,e.t1,n,t);return[Ee(r,m),Ee(o,l),Ee(l,m),Ee(o,r),Ee(o,m)]}function Le(e,s,n,t){let r=e.n,m=Oe(e,e.t1).map(c=>ce(c,s)),o=Oe(e,e.t0).map(c=>ce(c,s)),l,i;if(xe(e.m)){let c=ue(r,{sd:n});l=m.map((a,u)=>a+c[u]),i=o.map((a,u)=>a+c[u])}else l=m.map(c=>ge(1,e.m.linkinv(c))),i=o.map(c=>ge(1,e.m.linkinv(c)));return ht(e,l,i,t)}var xe=e=>!e.isGlm||e.fit.family==="gaussian",_e=e=>e.isGlm?Math.sqrt(zt(e.fit)):e.fit.sigma;function zt(e){let s=0;for(let n=0;n<e.residuals.length;n++)s+=e.weights[n]*e.residuals[n]**2;return s/e.dfResidual}var ct=(e,s,n)=>{let t=ae(e,[s,n],{type:7});return[t[0],t[1]]};function je(e,s,n,t){K(t,Vt,"mediate");let{treat:r,mediator:m}=t;if(typeof r!="string"||typeof m!="string")throw new TypeError("'treat' and 'mediator' are required");let o=t.treatValue??1,l=t.controlValue??0;if(!Number.isFinite(o)||!Number.isFinite(l))throw new RangeError("treatValue and controlValue must be finite");let i=Math.trunc(t.sims??1e3),c=t.boot??!1,a=t.bootCiType??"perc";if(a!=="perc"&&a!=="bca")throw new RangeError('bootCiType must be "perc" or "bca"');let u=t.confLevel??.95;if(!(u>0&&u<1))throw new RangeError("confLevel must be in (0, 1)");let E=t.robustSE??!1;if(!(i>=2))throw new RangeError("sims must be at least 2");let b=[];c&&E&&b.push("'robustSE' is ignored for nonparametric bootstrap");let f=at(e,n,"mediator"),d=at(s,n,"outcome");if(!xe(f)&&e.family!=="binomial")throw new RangeError("unsupported mediator model");if(f.d.terms.variables[0]!==m)throw new RangeError(`the mediator model's response must be '${m}'`);if(f.rows.length!==d.rows.length||f.rows.some((N,k)=>N!==d.rows[k]))throw new RangeError("number of observations do not match between mediator and outcome models");let y=f.rows.length,M=Object.entries(t.covariates??{});for(let[,N]of M)if(!Number.isFinite(N))throw new RangeError("covariate values must be finite");let v={m:f,y:d,treat:r,mediator:m,t1:o,t0:l,n:y,mTreat:ye(f,r,"mediator",!0),yTreat:ye(d,r,"outcome",!0),yMed:ye(d,m,"outcome",!0),mCov:M.map(([N,k])=>[ye(f,N,"mediator",!1),k]).filter(([N])=>N>=0),yCov:M.map(([N,k])=>[ye(d,N,"outcome",!1),k]).filter(([N])=>N>=0)};if(M.some(([N])=>!f.d.terms.variables.includes(N)&&!d.d.terms.variables.includes(N)))throw new RangeError("covariates must be variables of the models");let p=xe(f),h,T;if(c){let N=Ie(y,{size:y*i,replace:!0}),k=[...new Set([...f.d.terms.variables,...d.d.terms.variables])],I=p?_e(f):NaN;Le(v,f.coef,I,d.coef),h=[];for(let P=0;P<i;P++){let G=Array.from({length:y},(H,L)=>f.rows[N[P+L*i]]),X=Object.fromEntries(k.map(H=>{let L=n[H];return[H,G.map(R=>L[R])]})),Y=lt(f,X),J=lt(d,X);h.push(Le(v,ft(Y,f,b),p?_e({...f,fit:Y,isGlm:"family"in Y}):NaN,ft(J,d,b)))}T=Le(v,f.coef,I,d.coef)}else{let N=E?re(e,{type:"HC3"}).vcov:ne(e).vcov,k=E?re(s,{type:"HC3"}).vcov:ne(s).vcov,I=it(f.coef,N,i,"mediator"),P=it(d.coef,k,i,"outcome"),G=Oe(v,o),X=Oe(v,l),Y=Array.from({length:i},()=>new Array(y)),J=Array.from({length:i},()=>new Array(y));if(p){let H=ue(i*y,{sd:_e(f)});for(let L=0;L<y;L++)for(let R=0;R<i;R++)Y[R][L]=ce(G[L],I[R])+H[L*i+R],J[R][L]=ce(X[L],I[R])+H[L*i+R]}else{for(let H=0;H<y;H++)for(let L=0;L<i;L++)Y[L][H]=ge(1,f.linkinv(ce(G[H],I[L])));for(let H=0;H<y;H++)for(let L=0;L<i;L++)J[L][H]=ge(1,f.linkinv(ce(X[H],I[L])))}h=I.map((H,L)=>ht(v,Y[L],J[L],P[L]))}let w=N=>h.map(k=>k[N]),g=w(0),A=w(1),S=w(2),C=w(3),$=w(4),O=g.map((N,k)=>N/$[k]),j=A.map((N,k)=>N/$[k]),V=g.map((N,k)=>(N+A[k])/2),x=S.map((N,k)=>(N+C[k])/2),F=O.map((N,k)=>(N+j[k])/2),D=(1-u)/2,Q=(1+u)/2,z=(N,k)=>{let I;if(c&&a==="bca"){let X=B(N),Y=0,J=0,H=0;for(let q of N){let W=X-q;Y+=W*W,J+=W*W*W,q<X&&H++}let L=J/(6*Y**1.5),R=fe(H/N.length),_=q=>Z(R+(R+q)/(1-L*(R+q)));I=ct(N,_(fe(D)),_(fe(Q)))}else I=ct(N,D,Q);let P=0,G=0;for(let X of N)X>0?P++:X<0&&G++;return{estimate:k,ci:I,p:2*Math.min(P/N.length,G/N.length),sims:N}},U;if(T===void 0){let N=ke(O),k=ke(j);U=[B(g),B(A),B(S),B(C),B($),N,k,B(V),B(x),(N+k)/2]}else{let[N,k,I,P,G]=T;U=[N,k,I,P,G,N/G,k/G,(N+k)/2,(I+P)/2,(N/G+k/G)/2]}let le=d.d.terms.termLabels.some(N=>{let k=N.split(":");return k.length>1&&k.includes(r)&&k.includes(m)});return we("mediate",{d0:z(g,U[0]),d1:z(A,U[1]),z0:z(S,U[2]),z1:z(C,U[3]),tau:z($,U[4]),n0:z(O,U[5]),n1:z(j,U[6]),dAvg:z(V,U[7]),zAvg:z(x,U[8]),nAvg:z(F,U[9]),treatValue:o,controlValue:l,nobs:y,sims:i,boot:c,bootCiType:a,confLevel:u,robustSE:E&&!c,INT:le,warnings:b})}function lt(e,s){let n={...e.options};return be(()=>e.isGlm?ve(e.formula,s,n):Pe(e.formula,s,n))}var mt='prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases';function ft(e,s,n){let t="family"in e?e.model.columnNames:e.coefNames;return s.names.map(r=>{let m=t.indexOf(r);return m<0||Number.isNaN(e.coefficients[m])?(n.includes(mt)||n.push(mt),0):e.coefficients[m]})}var It=["pred","modx","modxValues","johnsonNeyman","jnAlpha","ciWidth","robust"],Ft=["pred","modx","alpha","robust"];function dt(e,s,n,t,r){if(typeof n!="string"||typeof t!="string")throw new TypeError("'pred' and 'modx' are required");if(r!==!1&&r!=="HC3")throw new RangeError('robust must be false or "HC3"');let m="family"in e,o=m?e.model.columnNames:e.coefNames;if(o===void 0)throw new TypeError("the model must be a formula fit of lm or glm");if(m&&e.family!=="binomial"&&e.family!=="gaussian")throw new RangeError("the model's family is not supported (binomial or gaussian)");let l=[`${n}:${t}`,`${t}:${n}`].find(d=>o.includes(d));if(!o.includes(n)||l===void 0)throw new RangeError(`the model has no coefficients '${n}' and '${n}:${t}'`);let i=r==="HC3"?re(e,{type:"HC3"}):ne(e),c=i.names.indexOf(n),a=i.names.indexOf(l);if(c<0||a<0)throw new RangeError("the predictor's or the interaction's coefficient is aliased");let u=e.coefficients,E=m?e.model.rows:e.rows,b=s[t];if(b===void 0)throw new RangeError(`object '${t}' not found`);let f=E.map(d=>Number(b[d]));if(f.some(d=>!Number.isFinite(d)))throw new RangeError(`'${t}' must be numeric`);return{b1:u[o.indexOf(n)],b3:u[o.indexOf(l)],v11:i.vcov[c][c],v13:i.vcov[c][a],v33:i.vcov[a][a],df:e.dfResidual,isGlm:m&&e.family==="binomial",w:f}}function pt(e,s){if(!(s>0&&s<1))throw new RangeError("alpha must be in (0, 1)");let n=Ce(1-s/2,e.df),t=n*n,r=2**-1022,m=Number.MAX_VALUE;if(![e.v11,e.v33].every(A=>A>=r&&A<=m)||!Number.isFinite(e.v13))throw new RangeError("the model's coefficient covariance is out of the double range (rescale the variables)");let o=2**Math.round(Math.log2(e.v11)/2),l=2**Math.round((Math.log2(e.v11)-Math.log2(e.v33))/2),i=e.b1/o,c=e.b3/o*l,a=e.v11/o/o,u=e.v13/o/o*l,E=e.v33/o/o*l*l,b=c*c-t*E,f=2*(i*c-t*u),d=i*i-t*a,y=f*f-4*b*d,M=Math.min(...e.w),v=Math.max(...e.w),p=[M,v],h,T=!1;if(!(y>=0))h=[-1/0,1/0],T=!0;else{let A=Math.sqrt(y),S=(-f-Math.sign(f||1)*A)/(2*b),C=S===0?(-f+Math.sign(f||1)*A)/(2*b):d/(b*S);h=S<=C?[S*l,C*l]:[C*l,S*l]}let w=!T&&b<0,g=!(h[0]>M&&h[0]<v)&&!(h[1]>M&&h[1]<v);return{bounds:h,inside:w,failed:T,allSig:g,modrange:p,alpha:s}}function Wt(e,s,n){return K(n,Ft,"johnsonNeyman"),pt(dt(e,s,n.pred,n.modx,n.robust??!1),n.alpha??.05)}function Kt(e,s,n){K(n,It,"simSlopes");let t=dt(e,s,n.pred,n.modx,n.robust??!1),r=n.ciWidth??.95;if(!(r>0&&r<1))throw new RangeError("ciWidth must be in (0, 1)");let m=n.modxValues??"mean-plus-minus",o;if(m==="mean-plus-minus"){let b=B(t.w),f=Math.sqrt(Te(t.w));o=[b-f,b,b+f]}else if(Array.isArray(m)&&m.every(b=>Number.isFinite(b)))o=[...m];else throw new RangeError('modxValues must be "mean-plus-minus" or finite numbers');let l=t.isGlm?fe((1+r)/2):Ce((1+r)/2,t.df),i=o.map(b=>t.b1+t.b3*b),c=o.map(b=>Math.sqrt(t.v11+2*b*t.v13+b*b*t.v33)),a=i.map((b,f)=>b/c[f]),u=a.map(b=>2*(t.isGlm?Z(-Math.abs(b)):He(-Math.abs(b),t.df))),E={values:o,estimate:i,se:c,lower:i.map((b,f)=>b-l*c[f]),upper:i.map((b,f)=>b+l*c[f]),statistic:a,statisticName:t.isGlm?"z":"t",p:u};return(n.johnsonNeyman??!0)&&(E.jn=pt(t,n.jnAlpha??.05)),E}var Gt=["treat","mediator"],Ut=["nmc","confLevel","treat","mediator"],Pt=new Set(["moderator","treatValue","controlValue","wLow","wHigh","method","nmc","sims","confLevel","robustSE","treat","mediator"]);function de(e,s){let n=22250738585072014e-324,t=Number.MAX_VALUE;if(e.some((r,m)=>r.some(o=>!Number.isFinite(o))||!(r[m]>=n&&r[m]<=t)))throw new RangeError(`the ${s} model's coefficient covariance is out of the double range (rescale the variables)`)}function Ae(e,s,n){let t=ne(e),r=t.names.indexOf(s);if(r<0)throw new RangeError(`the ${n} model has no coefficient '${s}'`);let m="family"in e?e.model.columnNames:e.coefNames;return{value:e.coefficients[m.indexOf(s)],v:t.vcov[r][r],names:t.names,vcov:t.vcov}}function Bt(e,s,n){K(n,Gt,"sobelTest");let t=Ae(e,n.treat,"mediator"),r=Ae(s,n.mediator,"outcome");de([[t.v]],"mediator"),de([[r.v]],"outcome");let m=t.value,o=r.value,l=Math.sqrt(t.v),i=Math.sqrt(r.v),c=m*o,a=Math.hypot(o*l,m*i),u=c/a;return{a:m,sa:l,b:o,sb:i,ab:c,se:a,z:u,p:2*Z(Math.abs(u),{lowerTail:!1})}}var bt=(e,s)=>{let n=1-s,t=ae(e,[n/2,1-n/2],{type:7});return[t[0],t[1]]};function vt(e){if(!(e>0&&e<1))throw new RangeError("confLevel must be in (0, 1)")}function Xt(e,s,n){K(n,Ut,"mediationMonteCarlo");let t=Math.trunc(n.nmc??2e4),r=n.confLevel??.95;if(vt(r),!(t>=2))throw new RangeError("nmc must be at least 2");let m=Ae(e,n.treat,"mediator"),o=Ae(s,n.mediator,"outcome"),l=Ae(s,n.treat,"outcome"),i=o.names.indexOf(n.mediator),c=o.names.indexOf(n.treat);de([[m.v]],"mediator"),de([[o.vcov[i][i],o.vcov[i][c]],[o.vcov[c][i],o.vcov[c][c]]],"outcome");let a=ue(t,{mean:m.value,sd:Math.sqrt(m.v)}),u=Ne(t,[o.value,l.value],[[o.vcov[i][i],o.vcov[i][c]],[o.vcov[c][i],o.vcov[c][c]]]),E=a.map((p,h)=>p*u[h][0]),b=u.map(p=>p[1]),f=E.map((p,h)=>p+b[h]),d=E.map((p,h)=>p/f[h]),y=m.value*o.value,M=l.value,v=(p,h)=>({estimate:p,ci:bt(h,r),sims:h});return{indirect:v(y,E),direct:v(M,b),total:v(y+M,f),proportion:v(y/(y+M),d)}}function gt(e,s,n){let t=e[n];if(t===void 0)throw new RangeError(`object '${n}' not found`);let r=s.map(i=>Number(t[i]));if(r.some(i=>!Number.isFinite(i)))throw new RangeError(`'${n}' must be numeric`);let m=[...new Set(r)].sort((i,c)=>i-c);if(m.length===2)return[m[0],m[1]];let o=B(r),l=Math.sqrt(Te(r));return[o-l,o+l]}var wt=e=>!("family"in e)||e.family==="gaussian",Yt=e=>"family"in e?e.model.rows:e.rows;function Jt(e,s,n,t){K(t,Pt,"moderatedMediation");let{treat:r,mediator:m,moderator:o}=t;if(typeof r!="string"||typeof m!="string"||typeof o!="string")throw new TypeError("'treat', 'mediator' and 'moderator' are required");let l=t.confLevel??.95;vt(l);let i=Yt(e),[c,a]=gt(n,i,r),[u,E]=gt(n,i,o),b=t.treatValue??a,f=t.controlValue??c,d=t.wLow??u,y=t.wHigh??E,M=t.method??(wt(e)&&wt(s)?"monteCarlo":"mediate"),v=(R,_)=>({estimate:R,ci:bt(_,l),sims:_}),p={method:M,wLow:d,wHigh:y,treatValue:b,controlValue:f};if(M==="mediate"){let R=De(),_=se=>je(e,s,n,{treat:r,mediator:m,treatValue:b,controlValue:f,covariates:{[o]:se},sims:t.sims??1e3,confLevel:l,robustSE:t.robustSE??!1}),q=_(d);Ve(R);let W=_(y),pe=W.dAvg.sims.map((se,yt)=>se-q.dAvg.sims[yt]),me=se=>({estimate:se.estimate,ci:se.ci,sims:se.sims});return{...p,indirectLow:me(q.dAvg),indirectHigh:me(W.dAvg),directLow:me(q.zAvg),directHigh:me(W.zAvg),totalLow:me(q.tau),totalHigh:me(W.tau),index:v(W.dAvg.estimate-q.dAvg.estimate,pe),low:q,high:W}}if(M!=="monteCarlo")throw new RangeError('method must be "monteCarlo" or "mediate"');let h=Math.trunc(t.nmc??2e4);if(!(h>=2))throw new RangeError("nmc must be at least 2");let T=t.robustSE?re(e,{type:"HC3"}):ne(e),w=t.robustSE?re(s,{type:"HC3"}):ne(s),g=(R,_)=>_.map(q=>{let W="family"in R?R.model.columnNames:R.coefNames;return R.coefficients[W.indexOf(q)]});de(T.vcov,"mediator"),de(w.vcov,"outcome");let A=Ne(h,g(e,T.names),T.vcov),S=Ne(h,g(s,w.names),w.vcov),C=g(e,T.names),$=g(s,w.names),O=(R,_,q)=>{let W=q===void 0?R.indexOf(_):[`${_}:${q}`,`${q}:${_}`].map(pe=>R.indexOf(pe)).find(pe=>pe>=0)??-1;if(q===void 0&&W<0)throw new RangeError(`a model has no coefficient '${_}'`);return W},j=O(T.names,r),V=O(T.names,r,o),x=O(w.names,m),F=O(w.names,m,o),D=O(w.names,r),Q=O(w.names,r,o),z=(R,_)=>_<0?0:R[_],U=b-f,le=(R,_,q)=>U*(z(R,j)+z(R,V)*q)*(z(_,x)+z(_,F)*q),N=(R,_)=>U*(z(R,D)+z(R,Q)*_),k=R=>Array.from({length:h},(_,q)=>R(q)),I=k(R=>le(A[R],S[R],d)),P=k(R=>le(A[R],S[R],y)),G=k(R=>N(S[R],d)),X=k(R=>N(S[R],y)),Y=le(C,$,d),J=le(C,$,y),H=N($,d),L=N($,y);return{...p,indirectLow:v(Y,I),indirectHigh:v(J,P),directLow:v(H,G),directHigh:v(L,X),totalLow:v(Y+H,I.map((R,_)=>R+G[_])),totalHigh:v(J+L,P.map((R,_)=>R+X[_])),index:v(J-Y,P.map((R,_)=>R-I[_]))}}export{Rt as balTab,Wt as johnsonNeyman,Mt as match,Je as matchWeights,je as mediate,Xt as mediationMonteCarlo,Jt as moderatedMediation,Kt as simSlopes,Bt as sobelTest,St as tableOneSmd,Ht as trimWeights,Dt as weightSummary,qt as weightit};
1
+ /*! rStats.js 1.20.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{o as ne,p as re}from"./chunks/chunk-5RRFO4NU.js";import{f as Pe}from"./chunks/chunk-VSV5QGXX.js";import{b as Fe,c as Ne}from"./chunks/chunk-64DDDGJU.js";import{a as Ie}from"./chunks/chunk-6LAKI2QG.js";import{a as ae}from"./chunks/chunk-VCXPGCA4.js";import{h as ke}from"./chunks/chunk-3ST6RZXG.js";import{a as ge}from"./chunks/chunk-KNF2GPJV.js";import{b as Xe}from"./chunks/chunk-EXS5QD7V.js";import{b as ve,d as Be}from"./chunks/chunk-OOHFFLMY.js";import{f as Ue}from"./chunks/chunk-AWXW4WSX.js";import"./chunks/chunk-QCQBK5AC.js";import"./chunks/chunk-DPCCSFCG.js";import"./chunks/chunk-WMEF5XWO.js";import"./chunks/chunk-UC3YYJHM.js";import"./chunks/chunk-PVRNAOO7.js";import{a as Ge}from"./chunks/chunk-LZAB4M7P.js";import{d as te}from"./chunks/chunk-6RA73LXX.js";import"./chunks/chunk-OOO5AAM7.js";import"./chunks/chunk-DFGW4QWU.js";import{a as Ke}from"./chunks/chunk-MXRN2G7O.js";import"./chunks/chunk-UPACHZ4F.js";import{e as He,f as Ce,k as ue}from"./chunks/chunk-VFL4GGYT.js";import"./chunks/chunk-INNFAVT3.js";import"./chunks/chunk-BU4I544S.js";import{a as Re}from"./chunks/chunk-HEPGGURG.js";import{e as De,f as Ve,g as ze,m as We,n as we,o as be}from"./chunks/chunk-MTSU2QHB.js";import"./chunks/chunk-B5GSH3AK.js";import"./chunks/chunk-7C2ECGT6.js";import"./chunks/chunk-VL72MQOQ.js";import{s as qe,t as Z,u as fe}from"./chunks/chunk-PJJJR3H6.js";import{l as K,u as ee,x as B,y as Te}from"./chunks/chunk-ARPXG2PG.js";function Ye(e){let s=0;for(let n of e)Math.abs(n)>s&&(s=Math.abs(n));return s>0&&Number.isFinite(s)?Math.floor(Math.log2(s)):0}function ie(e){let s=Ye(e),n=e.map(o=>ee(o,-s)),t=n[0]??0,r=n.map(o=>o-t),m=Ye(r);return{values:r.map(o=>ee(o,-m)),unitExp:s+m}}var Et=["estimand","M","caliper"];function Mt(e,s,n={}){K(n,Et,"match");let{estimand:t="ATT",M:r=1,caliper:m}=n,o=e.length;if(s.length!==o)throw new RangeError("length(Tr) != nrow(X)");if(t!=="ATT"&&t!=="ATE"&&t!=="ATC")throw new RangeError(`invalid 'estimand': ${String(t)}`);if(!Number.isInteger(r)||r<1)throw new RangeError("'M' must be a positive integer");if(m!==void 0&&!(m>0&&Number.isFinite(m)))throw new RangeError("'caliper' must be a positive number");let l=[];for(let g=0;g<o;g++){let A=e[g];if(A===!0||A===1)l.push(!0);else if(A===!1||A===0)l.push(!1);else throw typeof A=="number"&&Number.isNaN(A)?new RangeError("Match(): input includes NAs"):new RangeError("Treatment indicator ('Tr') must be a logical variable---i.e., TRUE (1) or FALSE (0)");if(!Number.isFinite(s[g]))throw new RangeError("Match(): input includes NAs")}if(!l.includes(!0)||!l.includes(!1))throw new RangeError("Treatment indicator ('Tr') must contain both treatment and control observations");let i=0;for(let g of s)i=Math.max(i,Math.abs(g));let c=i>0?Math.floor(Math.log2(i)):0,a=s.map(g=>ee(g,-c)),u=null,E=1/0;if(m!==void 0){let{values:g,unitExp:A}=ie(a),S=0;for(let O of g)S+=O;S/=o;let C=0;for(let O of g)C+=(O-S)*(O-S);let $=ee(Math.sqrt(C/o),A);E=m*$,u=ee(E,c)}let b=[new Array(o).fill(!1),new Array(o).fill(!1)],f=[],d=[],y=[],M=[],v=0,p=0;for(let g=0;g<o;g++){let A=l[g];if(A?t==="ATC":t==="ATT")continue;let S=b[A?0:1],C=[];for(let x=0;x<o;x++){if(l[x]===A)continue;let F=Math.abs(a[g]-a[x]);F>E||S[x]||C.push({j:x,d:F})}if(C.length<r){p++,y.push(g+1);continue}let O=C.map(x=>x.d).sort((x,F)=>x-F)[r-1],j=C.filter(x=>x.d<=O).map(x=>x.j),V;if(j.length===r)V=j;else{M.push(j.length),V=[],j=j.slice();for(let x=0;x<r;x++){let F=j.length,D=Math.min(F-1,Math.floor(F*(1-ze())));V.push(j[D]),j.splice(D,1)}V.sort((x,F)=>x-F)}for(let x of V)S[x]=!0,f.push((A?g:x)+1),d.push((A?x:g)+1);v++}let h=new Set([...f,...d]),T=u===null?[]:y.filter(g=>!h.has(g)),w=[];return f.length===0&&w.push("'Match' object contains no valid matches (probably because of the caliper or the exact option)."),{indexTreated:f,indexControl:d,weights:f.map(()=>1/r),indexDropped:T.length>0?T:null,caliper:m??null,ecaliper:u,nobs:o,wnobs:v,ndrops:p,estimand:t,M:r,tieSizes:M,warnings:w}}var At=["match","weightit","weights","estimand","levels","binary"],Tt=["factor"];function Je(e){let s=new Array(e.nobs).fill(0);return e.indexTreated.forEach((n,t)=>{s[n-1]+=e.weights[t],s[e.indexControl[t]-1]+=e.weights[t]}),s}function Nt(e,s){if(e===!0||e===1)return!0;if(e===!1||e===0)return!1;throw new RangeError(`'tr' must be 0 or 1 (element ${s+1})`)}function he(e,s,n,t){let r=0,m=0,o=0;for(let c=0;c<e.length;c++){if(n[c]!==t)continue;let a=s===null?1:s[c];r+=a,m+=a*a,o+=a*e[c]}let l=o/r,i=0;for(let c=0;c<e.length;c++){if(n[c]!==t)continue;let a=s===null?1:s[c];i+=a*(e[c]-l)*(e[c]-l)}return[l,i/(r-m/r)]}function Rt(e,s,n={}){K(n,At,"balTab");let{match:t,weightit:r,binary:m="raw",levels:o={}}=n;if(t!==void 0&&r!==void 0)throw new RangeError("give 'match' or 'weightit', not both");let l=t!==void 0?Je(t):r!==void 0?r.weights:n.weights,i=t?.estimand??r?.estimand??n.estimand??"ATT",c=new Set(t?.indexDropped??[]),a=t!==void 0&&t.caliper!==null,u=e.length,E=e.map(Nt);if(!E.includes(!0)||!E.includes(!1))throw new RangeError("'tr' must contain both groups");if(l!==void 0&&l.length!==u)throw new RangeError("'weights' must have the length of 'tr'");if(i==="ATO"&&l===void 0)throw new RangeError("estimand 'ATO' needs the weights");let b=[];r?.ps&&b.push(["prop.score",r.ps,"Distance"]);for(let[M,v]of Object.entries(s)){if(v.length!==u)throw new RangeError(`covariate '${M}' must have the length of 'tr'`);if(v.every(h=>typeof h=="number")){b.push([M,v,null]);continue}if(!v.every(h=>typeof h=="string"))throw new TypeError(`covariate '${M}' must be all numbers or all strings`);let p=o[M]??[...new Set(v)].sort(Re);if(v.some(h=>!p.includes(h)))throw new RangeError(`covariate '${M}' has values not among its levels`);for(let h of p.length===2?p.slice(1):p)b.push([`${M}_${h}`,v.map(T=>T===h?1:0),null])}let f=E.map(()=>!0),d=r!==void 0,y={rows:b.map(([M])=>M),type:[],diffUn:[],diffAdj:[],vRatioUn:[],vRatioAdj:[],observations:{rows:d?["Unadjusted","Adjusted"]:["All (ESS)","All (Unweighted)","Matched (ESS)","Matched (Unweighted)","Unmatched",...a?["Discarded"]:[]],control:[],treated:[]}};for(let[M,v,p]of b){if(v.some(D=>!Number.isFinite(D)))throw new RangeError(`covariate '${M}' has missing or infinite values`);let h=p===null&&new Set(v).size<=2&&v.every(D=>D===0||D===1),T=h?null:ie(v),w=T===null?v:T.values,[g,A]=he(w,null,E,!0),[S,C]=he(w,null,E,!1),$;if(i==="ATO"){let[D,Q]=he(w,l,f,!0);$=Math.sqrt(h?D*(1-D):Q)}else{let D=h?[g*(1-g),S*(1-S)]:[A,C];if($=Math.sqrt(i==="ATT"?D[0]:i==="ATC"?D[1]:(D[0]+D[1])/2),ee($,T?.unitExp??0)<Math.sqrt(Number.EPSILON)){let[Q,z]=he(w,null,f,!0);$=Math.sqrt(h?Q*(1-Q):z)}}let O=h&&m==="raw"?1:$;if(y.type.push(p??(h?"Binary":"Contin.")),y.diffUn.push(g===S?0:(g-S)/O),y.vRatioUn.push(h||C===0?NaN:A/C),l===void 0){y.diffAdj.push(NaN),y.vRatioAdj.push(NaN);continue}let[j,V]=he(w,l,E,!0),[x,F]=he(w,l,E,!1);y.diffAdj.push(j===x?0:(j-x)/O),y.vRatioAdj.push(h||F===0?NaN:V/F)}for(let M of[!1,!0]){let v=0,p=0,h=0,T=0,w=0;for(let S=0;S<u;S++){if(E[S]!==M||(v++,c.has(S+1)&&w++,l===void 0))continue;let C=l[S];p+=C,h+=C*C,C>0&&T++}let g=M?y.observations.treated:y.observations.control;if(d){g.push(v,p*p/h);continue}let A=l===void 0?[NaN,NaN,NaN]:[p*p/h,T,v-T-w];a&&A.push(w),g.push(v,v,...A)}return y}function St(e,s,n={}){K(n,Tt,"tableOneSmd");let{factor:t=!1}=n;if(e.length!==s.length)throw new RangeError("'x' and 'group' must have the same length");let r=[...new Set(s)].sort((f,d)=>f<d?-1:f>d?1:0);if(r.length!==2)throw new RangeError("'group' must have exactly two levels");let m=f=>f!==null&&!(typeof f=="number"&&Number.isNaN(f)),o=r.map(f=>e.filter((d,y)=>s[y]===f&&m(d)));if(!t){if(o.flat().some(p=>typeof p!="number"))throw new TypeError("'x' must be numeric unless factor: true");let f=ie(o.flat()).values,y=[f.slice(0,o[0].length),f.slice(o[0].length)].map(p=>{let h=p.reduce((T,w)=>T+w,0)/p.length;return[h,p.reduce((T,w)=>T+(w-h)*(w-h),0)/(p.length-1)]}),M=y[1][0]-y[0][0],v=Math.sqrt((y[0][1]+y[1][1])/2);return M===0?0:Math.abs(M)/v}let l=[...new Set(o.flat())].sort((f,d)=>typeof f=="number"&&typeof d=="number"?f-d:String(f)<String(d)?-1:String(f)>String(d)?1:0),i=o.map(f=>l.slice(1).map(d=>f.filter(y=>y===d).length/f.length)),c=i[1].map((f,d)=>f-i[0][d]);if(c.every(f=>f===0))return 0;let a=c.length,u=Array.from({length:a},(f,d)=>Array.from({length:a},(y,M)=>{let v=p=>d===M?p[d]*(1-p[d]):-p[d]*p[M];return(v(i[0])+v(i[1]))/2}));if(u.every(f=>f.every(d=>d===0)))return NaN;let E=Xe(u),b=0;for(let f=0;f<a;f++)for(let d=0;d<a;d++)b+=c[f]*E[f][d]*c[d];return Math.sqrt(b)}var Ot=["method","link","estimand","stabilize"],xt=["at","lower","treat"],oe=Number.EPSILON;function Ct(e){return e.map((s,n)=>{if(s===!0||s===1)return 1;if(s===!1||s===0)return 0;throw new RangeError(`'tr' must be 0 or 1 (element ${n+1})`)})}function kt(e,s){let n=[],t=[],r={};for(let[m,o]of Object.entries(e)){if(o.length!==s)throw new RangeError(`covariate '${m}' must have the length of 'tr'`);if(o.every(c=>typeof c=="number")){let c=o;if(c.some(a=>!Number.isFinite(a)))throw new RangeError(`covariate '${m}' has missing or infinite values`);n.push(m),t.push(c.slice());continue}if(!o.every(c=>typeof c=="string"))throw new TypeError(`covariate '${m}' must be all numbers or all strings`);let l=o,i=[...new Set(l)].sort(Re);r[m]=i;for(let c of i.slice(1))n.push(m+c),t.push(l.map(a=>a===c?1:0))}return{names:n,columns:t,factors:r}}function Qe(e){return e.map(s=>{let n=s.reduce((r,m)=>r+m,0)/s.length,t=s.reduce((r,m)=>Math.max(r,Math.abs(m-n)),0);return s.map(r=>t>0?(r-n)/t:0)})}function $t(e){let s=e[0]?.length??0,n=[new Array(s).fill(1/Math.sqrt(s))],t=[];for(let r of e){let m=Math.sqrt(r.reduce((i,c)=>i+c*c,0)),o=r.slice();for(let i=0;i<2;i++)for(let c of n){let a=o.reduce((u,E,b)=>u+E*c[b],0);for(let u=0;u<s;u++)o[u]-=a*c[u]}let l=Math.sqrt(o.reduce((i,c)=>i+c*c,0));l>1e-7*m&&(n.push(o.map(i=>i/l)),t.push(r))}return t}function st(e,s){let n=s.length,t=e.map((o,l)=>[...o,s[l]]),r=0;for(let o of e)for(let l of o)r=Math.max(r,Math.abs(l));for(let o=0;o<n;o++){let l=o;for(let i=o+1;i<n;i++)Math.abs(t[i][o])>Math.abs(t[l][o])&&(l=i);if(!(Math.abs(t[l][o])>1e-13*r))return null;[t[o],t[l]]=[t[l],t[o]];for(let i=o+1;i<n;i++){let c=t[i][o]/t[o][o];if(c!==0)for(let a=o;a<=n;a++)t[i][a]-=c*t[o][a]}}let m=new Array(n).fill(0);for(let o=n-1;o>=0;o--){let l=t[o][n];for(let i=o+1;i<n;i++)l-=t[o][i]*m[i];m[o]=l/t[o][o]}return m}function $e(e,s){return Array.from({length:s},(n,t)=>[1,...e.map(r=>r[t])])}function Ze(e,s,n){let t=n.length,r=new Array(t).fill(0);r[0]=Math.log(n[0]/s.length);let m=c=>{let a=0;for(let u of s)a+=Math.exp(e[u].reduce((E,b,f)=>E+b*c[f],0));return a-n.reduce((u,E,b)=>u+E*c[b],0)},o=m(r),l=!1,i=1e-13*Math.max(1,Math.abs(n[0]));for(let c=0;c<200;c++){let a=n.map(p=>-p),u=Array.from({length:t},()=>new Array(t).fill(0));for(let p of s){let h=e[p],T=Math.exp(h.reduce((w,g,A)=>w+g*r[A],0));for(let w=0;w<t;w++){a[w]+=T*h[w];for(let g=0;g<=w;g++)u[w][g]+=T*h[w]*h[g]}}for(let p=0;p<t;p++)for(let h=p+1;h<t;h++)u[p][h]=u[h][p];let E=Math.max(...a.map(Math.abs));if(E<=i){l=!0;break}let b=st(u,a.map(p=>-p));if(b===null||b.some(p=>!Number.isFinite(p)))break;let f=1e-12*(Math.abs(o)+1),d=1,y=r.map((p,h)=>p+b[h]),M=m(y);for(;!(M<=o+f)&&d>1e-10;)d/=2,y=r.map((p,h)=>p+d*b[h]),M=m(y);if(!(M<=o+f))break;let v=b.some((p,h)=>Math.abs(d*p)>1e-15*Math.max(1,Math.abs(r[h])));if(r.splice(0,t,...y),o=M,!v){l=E<=1e-9*Math.max(1,Math.abs(n[0]));break}}return{eta:e.map(c=>c.reduce((a,u,E)=>a+u*r[E],0)),converged:l}}var Lt={logit:{p:e=>te(e),q:e=>te(-e),d:e=>te(e)*te(-e)},probit:{p:e=>Z(e),q:e=>Z(-e),d:e=>qe(e)}};function _t(e,s,n,t,r){let m=s.length,o=r.length,l=r.slice(),i=d=>{let y=new Array(o).fill(0),M=Array.from({length:o},()=>new Array(o).fill(0));for(let v=0;v<m;v++){let p=e[v],h=p.reduce(($,O,j)=>$+O*d[j],0),T=t.p(h),w=t.q(h),g=t.d(h),A=s[v],S,C;n==="ATE"?(S=A?1/T:-1/w,C=A?-g/(T*T):-g/(w*w)):n==="ATT"?(S=A?1:-T/w,C=A?0:-g/(w*w)):n==="ATC"?(S=A?w/T:-1,C=A?-g/(T*T):0):(S=A?w:-T,C=-g);for(let $=0;$<o;$++){y[$]+=S*p[$];for(let O=0;O<o;O++)M[$][O]+=C*p[$]*p[O]}}return{g:y,J:M}},c=d=>d.reduce((y,M)=>y+M*M,0),{g:a,J:u}=i(l),E=c(a),b=!1,f=1e-12*m;for(let d=0;d<200;d++){if(Math.max(...a.map(Math.abs))<=f){b=!0;break}let y=st(u,a.map(T=>-T));if(y===null||y.some(T=>!Number.isFinite(T)))break;let M=1,v=l.map((T,w)=>T+y[w]),p=i(v),h=c(p.g);for(;!(h<E)&&M>1e-10;)M/=2,v=l.map((T,w)=>T+M*y[w]),p=i(v),h=c(p.g);if(!(h<E)){b=Math.max(...a.map(Math.abs))<=1e-8*m;break}l=v,a=p.g,u=p.J,E=h}return{eta:e.map(d=>d.reduce((y,M,v)=>y+M*l[v],0)),converged:b}}function et(e,s,n,t){switch(e){case"ATE":return s?1/n:1/t;case"ATT":return s?1:n/t;case"ATC":return s?t/n:1;default:return s?t:n}}var jt={glm:"glm.fit: algorithm did not converge",cbps:"The covariate balancing conditions could not be solved, so the covariates will not be exactly balanced.",ipt:"The optimization failed to converge; consider using fewer covariates or a different link function.",ebal:"The estimated weights do not balance the covariates, indicating the optimization arrived at a degenerate solution. Try decreasing the number of variables supplied to the optimization."},tt={cbps:"covariate balancing propensity score weighting",ipt:"inverse probability tilting",ebal:"entropy balancing"};function qt(e,s,n={}){K(n,Ot,"weightit");let{method:t="glm",estimand:r="ATE",stabilize:m=!1}=n,o=t==="ps"?"glm":t;if(!["glm","cbps","ipt","ebal"].includes(o))throw new RangeError(`unknown method '${String(t)}'`);if(!["ATE","ATT","ATC","ATO"].includes(r))throw new RangeError(`unknown estimand '${String(r)}'`);let l=o==="ebal"?null:n.link??"logit";if(l!==null&&!{glm:["logit","probit","cauchit","cloglog"],cbps:["logit","probit"],ipt:["logit"]}[o].includes(l))throw new RangeError(`link '${l}' is not available for method '${o}'`);if((o==="ipt"||o==="ebal")&&r==="ATO")throw new RangeError(`"ATO" is not an allowable estimand for ${tt[o]} with a binary treatment. Only "ATE", "ATT", and "ATC" are allowed.`);let c=[];if(m&&o==="glm"&&r!=="ATE")throw new RangeError('`stabilize` can only be supplied when `estimand = "ATE"`.');m&&o!=="glm"&&c.push(`\`stabilize\` cannot be used with ${tt[o]} and will be ignored.`);let a=Ct(e),u=a.length;if(!a.includes(0)||!a.includes(1))throw new RangeError("The treatment must have at least two unique values.");let{names:E,columns:b}=kt(s,u);if(b.length===0)throw new RangeError("'covariates' must have at least one column");let f=$t(b.map(w=>ie(w).values)),d=a.flatMap((w,g)=>w?[g]:[]),y=a.flatMap((w,g)=>w?[]:[g]),M=a.map((w,g)=>g),v=r==="ATT"?1:r==="ATC"?0:null,p=null,h,T=!0;if(o==="glm"){let w=be(()=>ve($e(f,u).map(g=>g.slice(1)),a,{family:"binomial",link:l}));T=w.converged,p=w.fittedValues.map((g,A)=>l==="logit"&&Math.abs(w.linearPredictors[A])>30?w.linearPredictors[A]>0?1-oe:oe:Math.min(Math.max(g,oe),1-oe)),h=a.map((g,A)=>et(r,g,p[A],1-p[A])),p.some(g=>g<=10*oe||g>=1-10*oe)&&c.push("Propensity scores numerically equal to 0 or 1 were estimated, indicating perfect separation. These may yield problems with inference. See `?method_glm` (`?WeightIt::method_glm()`) for details.")}else if(o==="cbps"){let w=Qe(f),g=$e(w,u),A=be(()=>ve(g.map(O=>O.slice(1)),a,{family:"binomial",link:l})).coefficients.map(O=>Number.isFinite(O)?O:0),S=Lt[l],C=_t(g,a,r,S,A);T=C.converged;let $=O=>Math.min(Math.max(O,oe),1-oe);p=C.eta.map(O=>$(S.p(O))),h=a.map((O,j)=>et(r,O,p[j],$(S.q(C.eta[j]))))}else{let w=Qe(f),g=$e(w,u),A=j=>g[0].map((V,x)=>j.reduce((F,D)=>F+g[D][x],0)),S={C:r!=="ATC",T:r!=="ATT"},C=o==="ebal"&&r==="ATE"?{C:A(M),T:A(M)}:{C:A(d),T:A(y)},$=S.C?Ze(g,y,C.C):null,O=S.T?Ze(g,d,C.T):null;if(T=($?.converged??!0)&&(O?.converged??!0),o==="ebal")h=a.map((j,V)=>j?O?Math.exp(O.eta[V]):1:$?Math.exp($.eta[V]):1);else{let j=r==="ATE"?1:0;h=a.map((V,x)=>V?O?j+Math.exp(O.eta[x]):1:$?j+Math.exp($.eta[x]):1),p=a.map((V,x)=>r==="ATT"?te($.eta[x]):r==="ATC"?te(-O.eta[x]):V?te(-O.eta[x]):te($.eta[x]))}}if(T||c.push(jt[o]),m&&o==="glm"){let w=[y.length/u,d.length/u];h=h.map((g,A)=>g*w[a[A]])}return h.every(w=>Math.abs(w-1)<Math.sqrt(oe))&&c.push("All weights are 1, possibly indicating an estimation failure."),we("weightit",{weights:h,ps:p,treat:a,estimand:r,method:o,link:l,stabilized:m&&o==="glm",focal:v,columnNames:E,converged:T,warnings:c})}function nt(e,s,n,t){let r=e.slice();if(s.length===0)return r;let m=s.map(i=>e[i]),o,l;if(n<1){let i=n<.5?1-n:n;o=ae(m,i,{type:3}),l=ae(m,1-i,{type:3})}else{if(!Number.isInteger(n))throw new RangeError("'at' must be below 1 or a whole number");if(n>=m.length)return null;let i=n>m.length/2?m.length-n:n,c=m.slice().sort((a,u)=>a-u);o=c[c.length-1-i],l=c[i]}for(let i of s)e[i]>o&&(r[i]=o),t&&e[i]<l&&(r[i]=l);return r}var ot=e=>`\`at\` must be less than ${e}, the number of units. Weights will not be trimmed.`;function Ht(e,s){K(s,xt,"trimWeights");let{at:n,lower:t=!1}=s;if(!(n>0)||!Number.isFinite(n))throw new RangeError("'at' must be a positive number");if(Array.isArray(e)||ArrayBuffer.isView(e)){let l=Array.from(e);if(s.treat!==void 0&&s.treat.length!==l.length)throw new RangeError("'treat' must have the length of 'w'");let i=nt(l,l.map((c,a)=>a),n,t);return i===null?(We("trimWeights",[ot(l.length)]),l):i}let r=e,m=r.treat.flatMap((l,i)=>r.focal===null||l!==r.focal?[i]:[]),o=nt(r.weights,m,n,t);return o===null?we("trimWeights",{...r,weights:r.weights.slice(),warnings:[ot(m.length)]}):{...r,weights:o,warnings:r.warnings.slice()}}function rt(e,s){let n=s.map(a=>e[a]),t=n.length,r=0,m=0;for(let a of n)r+=a,m+=a*a;let o=r/t,l=n.reduce((a,u)=>a+(u-o)*(u-o),0),i=n.map(a=>o>0?a/o:NaN),c=n.map((a,u)=>u).sort((a,u)=>n[u]-n[a]||a-u).slice(0,5).reverse();return{range:[Math.min(...n),Math.max(...n)],top:{index:c.map(a=>s[a]+1),weights:c.map(a=>n[a])},mean:o,coefOfVar:Math.sqrt(l/(t-1))/o,scaledMad:i.reduce((a,u)=>a+Math.abs(u-1),0)/t,negativeEntropy:i.reduce((a,u)=>a+(Number.isNaN(u)?NaN:u>0?u*Math.log(u):0),0)/t,numZeros:n.filter(a=>Math.abs(a)<1e-10).length,n:t,ess:r*r/m}}function Dt(e){let s=e.treat.flatMap((t,r)=>t?[r]:[]),n=e.treat.flatMap((t,r)=>t?[]:[r]);return{treated:rt(e.weights,s),control:rt(e.weights,n),stabilized:e.stabilized}}var Vt=new Set(["treat","mediator","treatValue","controlValue","covariates","sims","boot","bootCiType","confLevel","robustSE"]);function at(e,s,n){let t=Ue(e);if(t===void 0||typeof e.formula!="string")throw new TypeError(`the ${n} model must be a formula fit of lm or glm`);if(t.weights!==void 0||t.offset!==void 0)throw new RangeError(`weights and offsets are not supported (the ${n} model)`);let r="family"in e,m=a=>a;if(r){let a=e;if(a.family==="binomial"&&(a.link==="logit"||a.link==="probit"))m=Be(a).linkinv;else if(!(a.family==="gaussian"&&a.link==="identity"))throw new RangeError(`the ${n} model's family is not supported (binomial with logit or probit, or gaussian)`)}if(e.coefficients.some(a=>Number.isNaN(a)))throw new RangeError(`the ${n} model has aliased coefficients`);let o=e.formula,l=Ge(Ke(o,!1,!1,!0),s,{...t.contrasts===void 0?{}:{contrasts:t.contrasts},...t.levels===void 0?{}:{levels:t.levels},dropUnusedLevels:!0,anyResponse:!0}),i=r?e.model.rows:e.rows,c=r?e.model.columnNames:e.coefNames;if(l.frame.rows.length!==i.length||l.frame.rows.some((a,u)=>a!==i[u])||l.colNames.join("\0")!==c.join("\0"))throw new RangeError(`the data do not give the ${n} model's rows and columns (pass the data it was fitted on)`);return{fit:e,isGlm:r,formula:o,options:t,coef:e.coefficients.slice(),names:c,linkinv:m,d:l,rows:i}}function ye(e,s,n,t){let r=e.d.terms.variables.indexOf(s);if(r<0){if(t)throw new RangeError(`'${s}' is not a variable of the ${n} model`);return-1}if(e.d.frame.variables[r].kind!=="numeric")throw new RangeError(`'${s}' must be numeric in the ${n} model`);return r}function ut(e,s,n){let t=e.d.frame.variables.map((r,m)=>{let o=s.get(m);return o===void 0?r:{kind:"numeric",values:typeof o=="number"?new Array(n).fill(o):o.slice()}});return e.d.rowsOf(t,n)}var ce=(e,s)=>{let n=0;for(let t=0;t<e.length;t++)n+=e[t]*s[t];return n};function it(e,s,n,t){let r=e.length,m=2**-1022,o=Number.MAX_VALUE;if(s.some((a,u)=>a.some(E=>!Number.isFinite(E))||!(a[u]>=m&&a[u]<=o)))throw new RangeError(`the ${t} model's coefficient covariance is out of the double range (rescale the variables, or use boot: true)`);let l=Fe(s),i=ue(n*r),c=[];for(let a=0;a<n;a++){let u=[];for(let E=0;E<r;E++){let b=0;for(let f=0;f<r;f++)b+=i[a*r+f]*l[f][E];u.push(e[E]+b)}c.push(u)}return c}function Oe(e,s){let n=new Map(e.mCov);return n.set(e.mTreat,s),ut(e.m,n,e.n)}function Me(e,s,n){let t=new Map(e.yCov);return t.set(e.yTreat,s),t.set(e.yMed,n),ut(e.y,t,e.n)}function Se(e,s,n,t){return Me(e,s,n).map(r=>e.y.linkinv(ce(r,t)))}var Ee=(e,s)=>B(e.map((n,t)=>n-s[t]));function ht(e,s,n,t){if(xe(e.y)){let i=Me(e,e.t0,s),c=Me(e,e.t0,n),a=Me(e,e.t1,s),u=Me(e,e.t1,n),E=(b,f)=>B(b.map((d,y)=>{let M=0;for(let v=0;v<d.length;v++)M+=(d[v]-f[y][v])*t[v];return M}));return[E(i,c),E(a,u),E(u,c),E(a,i),E(a,c)]}let r=Se(e,e.t0,s,t),m=Se(e,e.t0,n,t),o=Se(e,e.t1,s,t),l=Se(e,e.t1,n,t);return[Ee(r,m),Ee(o,l),Ee(l,m),Ee(o,r),Ee(o,m)]}function Le(e,s,n,t){let r=e.n,m=Oe(e,e.t1).map(c=>ce(c,s)),o=Oe(e,e.t0).map(c=>ce(c,s)),l,i;if(xe(e.m)){let c=ue(r,{sd:n});l=m.map((a,u)=>a+c[u]),i=o.map((a,u)=>a+c[u])}else l=m.map(c=>ge(1,e.m.linkinv(c))),i=o.map(c=>ge(1,e.m.linkinv(c)));return ht(e,l,i,t)}var xe=e=>!e.isGlm||e.fit.family==="gaussian",_e=e=>e.isGlm?Math.sqrt(zt(e.fit)):e.fit.sigma;function zt(e){let s=0;for(let n=0;n<e.residuals.length;n++)s+=e.weights[n]*e.residuals[n]**2;return s/e.dfResidual}var ct=(e,s,n)=>{let t=ae(e,[s,n],{type:7});return[t[0],t[1]]};function je(e,s,n,t){K(t,Vt,"mediate");let{treat:r,mediator:m}=t;if(typeof r!="string"||typeof m!="string")throw new TypeError("'treat' and 'mediator' are required");let o=t.treatValue??1,l=t.controlValue??0;if(!Number.isFinite(o)||!Number.isFinite(l))throw new RangeError("treatValue and controlValue must be finite");let i=Math.trunc(t.sims??1e3),c=t.boot??!1,a=t.bootCiType??"perc";if(a!=="perc"&&a!=="bca")throw new RangeError('bootCiType must be "perc" or "bca"');let u=t.confLevel??.95;if(!(u>0&&u<1))throw new RangeError("confLevel must be in (0, 1)");let E=t.robustSE??!1;if(!(i>=2))throw new RangeError("sims must be at least 2");let b=[];c&&E&&b.push("'robustSE' is ignored for nonparametric bootstrap");let f=at(e,n,"mediator"),d=at(s,n,"outcome");if(!xe(f)&&e.family!=="binomial")throw new RangeError("unsupported mediator model");if(f.d.terms.variables[0]!==m)throw new RangeError(`the mediator model's response must be '${m}'`);if(f.rows.length!==d.rows.length||f.rows.some((N,k)=>N!==d.rows[k]))throw new RangeError("number of observations do not match between mediator and outcome models");let y=f.rows.length,M=Object.entries(t.covariates??{});for(let[,N]of M)if(!Number.isFinite(N))throw new RangeError("covariate values must be finite");let v={m:f,y:d,treat:r,mediator:m,t1:o,t0:l,n:y,mTreat:ye(f,r,"mediator",!0),yTreat:ye(d,r,"outcome",!0),yMed:ye(d,m,"outcome",!0),mCov:M.map(([N,k])=>[ye(f,N,"mediator",!1),k]).filter(([N])=>N>=0),yCov:M.map(([N,k])=>[ye(d,N,"outcome",!1),k]).filter(([N])=>N>=0)};if(M.some(([N])=>!f.d.terms.variables.includes(N)&&!d.d.terms.variables.includes(N)))throw new RangeError("covariates must be variables of the models");let p=xe(f),h,T;if(c){let N=Ie(y,{size:y*i,replace:!0}),k=[...new Set([...f.d.terms.variables,...d.d.terms.variables])],I=p?_e(f):NaN;Le(v,f.coef,I,d.coef),h=[];for(let P=0;P<i;P++){let G=Array.from({length:y},(H,L)=>f.rows[N[P+L*i]]),X=Object.fromEntries(k.map(H=>{let L=n[H];return[H,G.map(R=>L[R])]})),Y=lt(f,X),J=lt(d,X);h.push(Le(v,ft(Y,f,b),p?_e({...f,fit:Y,isGlm:"family"in Y}):NaN,ft(J,d,b)))}T=Le(v,f.coef,I,d.coef)}else{let N=E?re(e,{type:"HC3"}).vcov:ne(e).vcov,k=E?re(s,{type:"HC3"}).vcov:ne(s).vcov,I=it(f.coef,N,i,"mediator"),P=it(d.coef,k,i,"outcome"),G=Oe(v,o),X=Oe(v,l),Y=Array.from({length:i},()=>new Array(y)),J=Array.from({length:i},()=>new Array(y));if(p){let H=ue(i*y,{sd:_e(f)});for(let L=0;L<y;L++)for(let R=0;R<i;R++)Y[R][L]=ce(G[L],I[R])+H[L*i+R],J[R][L]=ce(X[L],I[R])+H[L*i+R]}else{for(let H=0;H<y;H++)for(let L=0;L<i;L++)Y[L][H]=ge(1,f.linkinv(ce(G[H],I[L])));for(let H=0;H<y;H++)for(let L=0;L<i;L++)J[L][H]=ge(1,f.linkinv(ce(X[H],I[L])))}h=I.map((H,L)=>ht(v,Y[L],J[L],P[L]))}let w=N=>h.map(k=>k[N]),g=w(0),A=w(1),S=w(2),C=w(3),$=w(4),O=g.map((N,k)=>N/$[k]),j=A.map((N,k)=>N/$[k]),V=g.map((N,k)=>(N+A[k])/2),x=S.map((N,k)=>(N+C[k])/2),F=O.map((N,k)=>(N+j[k])/2),D=(1-u)/2,Q=(1+u)/2,z=(N,k)=>{let I;if(c&&a==="bca"){let X=B(N),Y=0,J=0,H=0;for(let q of N){let W=X-q;Y+=W*W,J+=W*W*W,q<X&&H++}let L=J/(6*Y**1.5),R=fe(H/N.length),_=q=>Z(R+(R+q)/(1-L*(R+q)));I=ct(N,_(fe(D)),_(fe(Q)))}else I=ct(N,D,Q);let P=0,G=0;for(let X of N)X>0?P++:X<0&&G++;return{estimate:k,ci:I,p:2*Math.min(P/N.length,G/N.length),sims:N}},U;if(T===void 0){let N=ke(O),k=ke(j);U=[B(g),B(A),B(S),B(C),B($),N,k,B(V),B(x),(N+k)/2]}else{let[N,k,I,P,G]=T;U=[N,k,I,P,G,N/G,k/G,(N+k)/2,(I+P)/2,(N/G+k/G)/2]}let le=d.d.terms.termLabels.some(N=>{let k=N.split(":");return k.length>1&&k.includes(r)&&k.includes(m)});return we("mediate",{d0:z(g,U[0]),d1:z(A,U[1]),z0:z(S,U[2]),z1:z(C,U[3]),tau:z($,U[4]),n0:z(O,U[5]),n1:z(j,U[6]),dAvg:z(V,U[7]),zAvg:z(x,U[8]),nAvg:z(F,U[9]),treatValue:o,controlValue:l,nobs:y,sims:i,boot:c,bootCiType:a,confLevel:u,robustSE:E&&!c,INT:le,warnings:b})}function lt(e,s){let n={...e.options};return be(()=>e.isGlm?ve(e.formula,s,n):Pe(e.formula,s,n))}var mt='prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases';function ft(e,s,n){let t="family"in e?e.model.columnNames:e.coefNames;return s.names.map(r=>{let m=t.indexOf(r);return m<0||Number.isNaN(e.coefficients[m])?(n.includes(mt)||n.push(mt),0):e.coefficients[m]})}var It=["pred","modx","modxValues","johnsonNeyman","jnAlpha","ciWidth","robust"],Ft=["pred","modx","alpha","robust"];function dt(e,s,n,t,r){if(typeof n!="string"||typeof t!="string")throw new TypeError("'pred' and 'modx' are required");if(r!==!1&&r!=="HC3")throw new RangeError('robust must be false or "HC3"');let m="family"in e,o=m?e.model.columnNames:e.coefNames;if(o===void 0)throw new TypeError("the model must be a formula fit of lm or glm");if(m&&e.family!=="binomial"&&e.family!=="gaussian")throw new RangeError("the model's family is not supported (binomial or gaussian)");let l=[`${n}:${t}`,`${t}:${n}`].find(d=>o.includes(d));if(!o.includes(n)||l===void 0)throw new RangeError(`the model has no coefficients '${n}' and '${n}:${t}'`);let i=r==="HC3"?re(e,{type:"HC3"}):ne(e),c=i.names.indexOf(n),a=i.names.indexOf(l);if(c<0||a<0)throw new RangeError("the predictor's or the interaction's coefficient is aliased");let u=e.coefficients,E=m?e.model.rows:e.rows,b=s[t];if(b===void 0)throw new RangeError(`object '${t}' not found`);let f=E.map(d=>Number(b[d]));if(f.some(d=>!Number.isFinite(d)))throw new RangeError(`'${t}' must be numeric`);return{b1:u[o.indexOf(n)],b3:u[o.indexOf(l)],v11:i.vcov[c][c],v13:i.vcov[c][a],v33:i.vcov[a][a],df:e.dfResidual,isGlm:m&&e.family==="binomial",w:f}}function pt(e,s){if(!(s>0&&s<1))throw new RangeError("alpha must be in (0, 1)");let n=Ce(1-s/2,e.df),t=n*n,r=2**-1022,m=Number.MAX_VALUE;if(![e.v11,e.v33].every(A=>A>=r&&A<=m)||!Number.isFinite(e.v13))throw new RangeError("the model's coefficient covariance is out of the double range (rescale the variables)");let o=2**Math.round(Math.log2(e.v11)/2),l=2**Math.round((Math.log2(e.v11)-Math.log2(e.v33))/2),i=e.b1/o,c=e.b3/o*l,a=e.v11/o/o,u=e.v13/o/o*l,E=e.v33/o/o*l*l,b=c*c-t*E,f=2*(i*c-t*u),d=i*i-t*a,y=f*f-4*b*d,M=Math.min(...e.w),v=Math.max(...e.w),p=[M,v],h,T=!1;if(!(y>=0))h=[-1/0,1/0],T=!0;else{let A=Math.sqrt(y),S=(-f-Math.sign(f||1)*A)/(2*b),C=S===0?(-f+Math.sign(f||1)*A)/(2*b):d/(b*S);h=S<=C?[S*l,C*l]:[C*l,S*l]}let w=!T&&b<0,g=!(h[0]>M&&h[0]<v)&&!(h[1]>M&&h[1]<v);return{bounds:h,inside:w,failed:T,allSig:g,modrange:p,alpha:s}}function Wt(e,s,n){return K(n,Ft,"johnsonNeyman"),pt(dt(e,s,n.pred,n.modx,n.robust??!1),n.alpha??.05)}function Kt(e,s,n){K(n,It,"simSlopes");let t=dt(e,s,n.pred,n.modx,n.robust??!1),r=n.ciWidth??.95;if(!(r>0&&r<1))throw new RangeError("ciWidth must be in (0, 1)");let m=n.modxValues??"mean-plus-minus",o;if(m==="mean-plus-minus"){let b=B(t.w),f=Math.sqrt(Te(t.w));o=[b-f,b,b+f]}else if(Array.isArray(m)&&m.every(b=>Number.isFinite(b)))o=[...m];else throw new RangeError('modxValues must be "mean-plus-minus" or finite numbers');let l=t.isGlm?fe((1+r)/2):Ce((1+r)/2,t.df),i=o.map(b=>t.b1+t.b3*b),c=o.map(b=>Math.sqrt(t.v11+2*b*t.v13+b*b*t.v33)),a=i.map((b,f)=>b/c[f]),u=a.map(b=>2*(t.isGlm?Z(-Math.abs(b)):He(-Math.abs(b),t.df))),E={values:o,estimate:i,se:c,lower:i.map((b,f)=>b-l*c[f]),upper:i.map((b,f)=>b+l*c[f]),statistic:a,statisticName:t.isGlm?"z":"t",p:u};return(n.johnsonNeyman??!0)&&(E.jn=pt(t,n.jnAlpha??.05)),E}var Gt=["treat","mediator"],Ut=["nmc","confLevel","treat","mediator"],Pt=new Set(["moderator","treatValue","controlValue","wLow","wHigh","method","nmc","sims","confLevel","robustSE","treat","mediator"]);function de(e,s){let n=22250738585072014e-324,t=Number.MAX_VALUE;if(e.some((r,m)=>r.some(o=>!Number.isFinite(o))||!(r[m]>=n&&r[m]<=t)))throw new RangeError(`the ${s} model's coefficient covariance is out of the double range (rescale the variables)`)}function Ae(e,s,n){let t=ne(e),r=t.names.indexOf(s);if(r<0)throw new RangeError(`the ${n} model has no coefficient '${s}'`);let m="family"in e?e.model.columnNames:e.coefNames;return{value:e.coefficients[m.indexOf(s)],v:t.vcov[r][r],names:t.names,vcov:t.vcov}}function Bt(e,s,n){K(n,Gt,"sobelTest");let t=Ae(e,n.treat,"mediator"),r=Ae(s,n.mediator,"outcome");de([[t.v]],"mediator"),de([[r.v]],"outcome");let m=t.value,o=r.value,l=Math.sqrt(t.v),i=Math.sqrt(r.v),c=m*o,a=Math.hypot(o*l,m*i),u=c/a;return{a:m,sa:l,b:o,sb:i,ab:c,se:a,z:u,p:2*Z(Math.abs(u),{lowerTail:!1})}}var bt=(e,s)=>{let n=1-s,t=ae(e,[n/2,1-n/2],{type:7});return[t[0],t[1]]};function vt(e){if(!(e>0&&e<1))throw new RangeError("confLevel must be in (0, 1)")}function Xt(e,s,n){K(n,Ut,"mediationMonteCarlo");let t=Math.trunc(n.nmc??2e4),r=n.confLevel??.95;if(vt(r),!(t>=2))throw new RangeError("nmc must be at least 2");let m=Ae(e,n.treat,"mediator"),o=Ae(s,n.mediator,"outcome"),l=Ae(s,n.treat,"outcome"),i=o.names.indexOf(n.mediator),c=o.names.indexOf(n.treat);de([[m.v]],"mediator"),de([[o.vcov[i][i],o.vcov[i][c]],[o.vcov[c][i],o.vcov[c][c]]],"outcome");let a=ue(t,{mean:m.value,sd:Math.sqrt(m.v)}),u=Ne(t,[o.value,l.value],[[o.vcov[i][i],o.vcov[i][c]],[o.vcov[c][i],o.vcov[c][c]]]),E=a.map((p,h)=>p*u[h][0]),b=u.map(p=>p[1]),f=E.map((p,h)=>p+b[h]),d=E.map((p,h)=>p/f[h]),y=m.value*o.value,M=l.value,v=(p,h)=>({estimate:p,ci:bt(h,r),sims:h});return{indirect:v(y,E),direct:v(M,b),total:v(y+M,f),proportion:v(y/(y+M),d)}}function gt(e,s,n){let t=e[n];if(t===void 0)throw new RangeError(`object '${n}' not found`);let r=s.map(i=>Number(t[i]));if(r.some(i=>!Number.isFinite(i)))throw new RangeError(`'${n}' must be numeric`);let m=[...new Set(r)].sort((i,c)=>i-c);if(m.length===2)return[m[0],m[1]];let o=B(r),l=Math.sqrt(Te(r));return[o-l,o+l]}var wt=e=>!("family"in e)||e.family==="gaussian",Yt=e=>"family"in e?e.model.rows:e.rows;function Jt(e,s,n,t){K(t,Pt,"moderatedMediation");let{treat:r,mediator:m,moderator:o}=t;if(typeof r!="string"||typeof m!="string"||typeof o!="string")throw new TypeError("'treat', 'mediator' and 'moderator' are required");let l=t.confLevel??.95;vt(l);let i=Yt(e),[c,a]=gt(n,i,r),[u,E]=gt(n,i,o),b=t.treatValue??a,f=t.controlValue??c,d=t.wLow??u,y=t.wHigh??E,M=t.method??(wt(e)&&wt(s)?"monteCarlo":"mediate"),v=(R,_)=>({estimate:R,ci:bt(_,l),sims:_}),p={method:M,wLow:d,wHigh:y,treatValue:b,controlValue:f};if(M==="mediate"){let R=De(),_=se=>je(e,s,n,{treat:r,mediator:m,treatValue:b,controlValue:f,covariates:{[o]:se},sims:t.sims??1e3,confLevel:l,robustSE:t.robustSE??!1}),q=_(d);Ve(R);let W=_(y),pe=W.dAvg.sims.map((se,yt)=>se-q.dAvg.sims[yt]),me=se=>({estimate:se.estimate,ci:se.ci,sims:se.sims});return{...p,indirectLow:me(q.dAvg),indirectHigh:me(W.dAvg),directLow:me(q.zAvg),directHigh:me(W.zAvg),totalLow:me(q.tau),totalHigh:me(W.tau),index:v(W.dAvg.estimate-q.dAvg.estimate,pe),low:q,high:W}}if(M!=="monteCarlo")throw new RangeError('method must be "monteCarlo" or "mediate"');let h=Math.trunc(t.nmc??2e4);if(!(h>=2))throw new RangeError("nmc must be at least 2");let T=t.robustSE?re(e,{type:"HC3"}):ne(e),w=t.robustSE?re(s,{type:"HC3"}):ne(s),g=(R,_)=>_.map(q=>{let W="family"in R?R.model.columnNames:R.coefNames;return R.coefficients[W.indexOf(q)]});de(T.vcov,"mediator"),de(w.vcov,"outcome");let A=Ne(h,g(e,T.names),T.vcov),S=Ne(h,g(s,w.names),w.vcov),C=g(e,T.names),$=g(s,w.names),O=(R,_,q)=>{let W=q===void 0?R.indexOf(_):[`${_}:${q}`,`${q}:${_}`].map(pe=>R.indexOf(pe)).find(pe=>pe>=0)??-1;if(q===void 0&&W<0)throw new RangeError(`a model has no coefficient '${_}'`);return W},j=O(T.names,r),V=O(T.names,r,o),x=O(w.names,m),F=O(w.names,m,o),D=O(w.names,r),Q=O(w.names,r,o),z=(R,_)=>_<0?0:R[_],U=b-f,le=(R,_,q)=>U*(z(R,j)+z(R,V)*q)*(z(_,x)+z(_,F)*q),N=(R,_)=>U*(z(R,D)+z(R,Q)*_),k=R=>Array.from({length:h},(_,q)=>R(q)),I=k(R=>le(A[R],S[R],d)),P=k(R=>le(A[R],S[R],y)),G=k(R=>N(S[R],d)),X=k(R=>N(S[R],y)),Y=le(C,$,d),J=le(C,$,y),H=N($,d),L=N($,y);return{...p,indirectLow:v(Y,I),indirectHigh:v(J,P),directLow:v(H,G),directHigh:v(L,X),totalLow:v(Y+H,I.map((R,_)=>R+G[_])),totalHigh:v(J+L,P.map((R,_)=>R+X[_])),index:v(J-Y,P.map((R,_)=>R-I[_]))}}export{Rt as balTab,Wt as johnsonNeyman,Mt as match,Je as matchWeights,je as mediate,Xt as mediationMonteCarlo,Jt as moderatedMediation,Kt as simSlopes,Bt as sobelTest,St as tableOneSmd,Ht as trimWeights,Dt as weightSummary,qt as weightit};
@@ -0,0 +1,2 @@
1
+ /*! rStats.js 1.20.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{h as F,i as O}from"./chunk-7KPFNJBE.js";import{b as _,c as N}from"./chunk-WMEF5XWO.js";import{a as R}from"./chunk-7C2ECGT6.js";import{l as A,p as v,q as y}from"./chunk-ARPXG2PG.js";var D=["fun"],K=["nrow","ncol"],Y=["nrow","ncol","byrow"],$=["by","lengthOut"];function g(n){return typeof n!="number"&&n.length>0&&Array.isArray(n[0])}function m(n){return typeof n=="number"?[n]:Array.from(n)}function d(n){let t=n[0].length;if(n.some(a=>a.length!==t))throw new TypeError("all rows of the matrix must have the same length");return t}function Q(n,t){let a,r;if(g(n)&&g(t))a=n.map(e=>[...e]),r=t.map(e=>[...e]);else if(g(n)){let e=m(t),i=d(n);a=n.map(c=>[...c]),r=i===e.length?e.map(c=>[c]):i===1?[e]:[]}else if(g(t)){let e=m(n);r=t.map(i=>[...i]),a=t.length===e.length?[e]:t.length===1?e.map(i=>[i]):[]}else{let e=m(n),i=m(t);if(e.length===i.length)a=[e],r=i.map(c=>[c]);else if(e.length===1)a=[e],r=[i];else if(i.length===1)a=e.map(c=>[c]),r=[i];else throw new RangeError("non-conformable arguments")}let u=a[0]?.length??0;if(a.length===0||r.length!==u)throw new RangeError("non-conformable arguments");d(a);let o=r.length>0?d(r):1,f=new Array(o).fill(1/0);for(let e of r)for(let i=0;i<o;i++){let c=Math.abs(e[i]);c!==0&&c<f[i]&&(f[i]=c)}return a.map(e=>{let i=1/0;for(let s of e){let l=Math.abs(s);l!==0&&l<i&&(i=l)}let c=new Array(o).fill(0);for(let s=0;s<o;s++){let l=0;for(let h=0;h<u;h++)l+=e[h]*r[h][s];c[s]=v(l,i*f[s])?y(e,r.map(h=>h[s]),l):l}return c})}function M(n,t,a){let r=g(n),u=g(t);if(r&&u){let i=d(n);if(n.length!==t.length||i!==d(t))throw new RangeError("non-conformable arrays");return n.map((c,s)=>c.map((l,h)=>a(l,t[s][h])))}if(r||u){let i=r?n:t,c=m(r?t:n),s=i.length,l=d(i);if(c.length===0)return i.map(h=>h.map(()=>NaN));if(c.length>s*l)throw new RangeError("dims [product "+s*l+"] do not match the length of object ["+c.length+"]");return i.map((h,b)=>h.map((w,p)=>r?a(w,c[(b+p*s)%c.length]):a(c[(b+p*s)%c.length],w)))}let o=m(n),f=m(t);if(o.length===0||f.length===0)return[];let e=Math.max(o.length,f.length);return Array.from({length:e},(i,c)=>a(o[c%o.length],f[c%f.length]))}function X(n,t){return M(n,t,(a,r)=>a+r)}function z(n,t){return M(n,t,(a,r)=>a-r)}function H(n,t){return M(n,t,(a,r)=>a*r)}function J(n,t){return M(n,t,(a,r)=>a/r)}var P={"*":(n,t)=>n*t,"+":(n,t)=>n+t,"-":(n,t)=>n-t,"/":(n,t)=>n/t,"^":(n,t)=>n**t};function W(n,t,...a){A(N(a),D,"outer");let r=_(["fun"],a).fun??"*",u=typeof r=="function"?r:P[r];if(u===void 0)throw new RangeError(`invalid fun "${String(r)}"`);let o=Array.from(n),f=Array.from(t);return o.map(e=>f.map(i=>u(e,i)))}function k(n){if(!g(n))return[m(n)];let t=d(n);return Array.from({length:t},(a,r)=>n.map(u=>u[r]))}function Z(n,t={}){if(A(t,K,"diag"),g(n)){let e=d(n);return Array.from({length:Math.min(n.length,e)},(i,c)=>n[c][c])}let a=m(n),r,u;if(a.length===1&&t.nrow===void 0&&t.ncol===void 0){if(u=Math.trunc(a[0]),!(u>=0))throw new RangeError("invalid 'nrow' value (< 0)");r=[1]}else r=a,u=E(t.nrow,"nrow")??a.length;let o=E(t.ncol,"ncol")??u;if(r.length===0&&Math.min(u,o)>0)throw new RangeError("'x' must have positive length");let f=Array.from({length:u},()=>new Array(o).fill(0));for(let e=0;e<Math.min(u,o);e++)f[e][e]=r[e%r.length];return u===0?[]:f}function I(n,t){let a=e=>g(e)||m(e).length>0,r=n.some(a)?n.filter(a):n,u=r.map(e=>g(e)?t?k(e):e.map(i=>[...i]):[m(e)]),o=r.filter(g),f=o.length>0?t?o[0].length:d(o[0]):R(u.map(e=>e[0].length));return o.forEach((e,i)=>{if((t?e.length:d(e))!==f)throw new RangeError(`number of ${t?"rows":"columns"} of matrices must match (see arg ${i+2})`)}),u.flatMap(e=>e.map(i=>Array.from({length:f},(c,s)=>i[s%i.length])))}function j(n){return typeof n=="object"&&!Array.isArray(n)&&!ArrayBuffer.isView(n)}function T(n){let t=n.filter(j);if(t.length!==0){if(t.length<n.length)throw new TypeError("cannot combine data frames with vectors or matrices");return t}}function C(...n){let t=T(n);return t===void 0?k(I(n,!0)):O(t)}function x(...n){let t=T(n);return t===void 0?I(n,!1):F(t)}function E(n,t){if(n!==void 0){if(!Number.isFinite(n)||n<=-1)throw new RangeError(`invalid '${t}' value`);return Math.trunc(n)+0}}function nn(n,t={}){A(t,Y,"matrix");let a=m(n),r=a.length,u=E(t.nrow,"nrow"),o=E(t.ncol,"ncol");u===void 0&&o===void 0?(u=r,o=1):u===void 0?u=Math.ceil(r/o):o===void 0&&(o=Math.ceil(r/u));let f=t.byrow??!1;return Array.from({length:u},(e,i)=>Array.from({length:o},(c,s)=>r===0?NaN:a[(f?i*o+s:i+s*u)%r]))}function tn(n,t){if(!g(n)&&!g(t)){let o=m(n),f=m(t);return o.flatMap(e=>f.map(i=>e*i))}let a=g(n)?n:m(n).map(o=>[o]),r=g(t)?t:m(t).map(o=>[o]),u=[];for(let o of a)for(let f of r)u.push(o.flatMap(e=>f.map(i=>e*i)));return u}function en(n,t,a={}){A(a,$,"seq");let{by:r,lengthOut:u}=a;if(t===void 0&&r===void 0&&u===void 0&&n!==void 0){if(!Number.isFinite(n))throw new RangeError("'from' must be a finite number");return S(1,n)}if(n!==void 0&&!Number.isFinite(n))throw new RangeError("'from' must be a finite number");if(t!==void 0&&!Number.isFinite(t))throw new RangeError("'to' must be a finite number");if(u===void 0){if(r===void 0)return S(n??1,t??1);let f=n??1,e=t??1,i=!Number.isFinite(e-f),c=i?.5:1,s=e*c-f*c;if(s===0&&e===0)return[e];let l=s/(r*c);if(!Number.isFinite(l)){if(r===0&&s===0)return[f];throw new RangeError("invalid '(to - from)/by'")}if(l<0||!Number.isFinite(r)&&s!==0&&s>0!=r>0)throw new RangeError("wrong sign in 'by' argument");if(Math.abs(s)/Math.max(Math.abs(e*c),Math.abs(f*c))<100*Number.EPSILON)return[f];let h=Math.trunc(l+1e-10),b=i?w=>2*(f/2+w*(r/2)):w=>f+w*r;return Array.from({length:h+1},(w,p)=>p===0?f:r>0?Math.min(b(p),e):Math.max(b(p),e))}if(!Number.isFinite(u)||u<=-1)throw new RangeError("'length.out' must be a non-negative number");let o=Math.ceil(u);if(o===0)return[];if(r===void 0){let f=t??(n??1)+(o-1),e=n??f-(o-1);if(o<=2)return[e,f].slice(0,o);if(e===f)return new Array(o).fill(e);if(!Number.isFinite(f-e)){let c=e/2,s=(f/2-c)/(o-1);return Array.from({length:o},(l,h)=>h===0?e:h===o-1?f:2*(c+h*s))}let i=(f-e)/(o-1);return Array.from({length:o},(c,s)=>s===0?e:s===o-1?f:e+s*i)}if(t===void 0){let f=n??1;return Array.from({length:o},(e,i)=>f+i*r)}if(n===void 0)return Array.from({length:o},(f,e)=>t-(o-1-e)*r);throw new RangeError("too many arguments")}function S(n,t){let a=Math.trunc(Math.abs(t-n)+1+11920928955078125e-23),r=n<=t?1:-1;return Array.from({length:a},(u,o)=>n+r*o)}export{Q as a,X as b,z as c,H as d,J as e,W as f,k as g,Z as h,C as i,x as j,nn as k,tn as l,en as m};
@@ -0,0 +1,2 @@
1
+ /*! rStats.js 1.20.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{I as p,P as S,g as A,l,n as b,o as _,r as v,s as y,t as I,u as w,w as F,x as E,y as D,z as K}from"./chunk-ARPXG2PG.js";var G=["naRm"],T=["naRm"],U=["trim","naRm"],V=["naRm"],W=["naRm"],j=["naRm"],q=["naRm"],C=["naRm"],H=["lag","differences"];function h(i,t){let n=Array.from(i);return t?n.filter(e=>!Number.isNaN(e)):n.some(Number.isNaN)?void 0:n}function $(i,t={}){l(t,G,"sum");let n=h(i,t.naRm);return n===void 0?NaN:p(n)}function nn(i,t={}){l(t,T,"prod");let n=h(i,t.naRm);if(n===void 0)return NaN;let e=Y();for(let r=0;r<n.length;r++){let o=n[r];if(!Number.isFinite(o)||o===0)return n.slice(r).reduce((a,u)=>a*u,k(e));O(e,o)}return B(e.p,e.e)}function Y(){return{p:[1,0],e:0}}function O(i,t){let n=Math.floor(Math.log2(Math.abs(t)));(n>500||n<-500)&&(t=w(t,-n),i.e+=n);let e=A(i.p,[t,0]);if(n=Math.floor(Math.log2(Math.abs(e[0]))),n>500||n<-500){let r=2**-n;e=[e[0]*r,e[1]*r],i.e+=n}i.p=e}function k(i){return i.p[0]<0?-1:1}function en(i,t={}){l(t,U,"mean");let n=h(i,t.naRm),e=t.trim??0;if(Number.isNaN(e)&&(n===void 0||n.length>0))throw new RangeError("'trim' must be numeric of length one");if(n===void 0)return NaN;let r=n.length;if(r===0)return NaN;if(e>0&&r>0){if(e>=.5)return J(n);e=Math.max(e,0);let o=Math.floor(r*e),a=[...n].sort((u,N)=>u-N);return E(a.slice(o,r-o))}return E(n)}function tn(i,t,n={}){l(n,V,"weightedMean");let e=Array.from(i),r=Array.from(t);if(e.length!==r.length)throw new RangeError("'x' and 'w' must have the same length");if(n.naRm){let s=e.map(f=>!Number.isNaN(f));e=e.filter((f,d)=>s[d]),r=r.filter((f,d)=>s[d])}let o=[],a=!1;for(let s=0;s<e.length;s++){if(r[s]===0)continue;let f=e[s]*r[s];e[s]!==0&&Math.abs(f)<2**-1022&&(a=!0),o.push(f)}let u=p(r),N=p(o)/u;if(Number.isFinite(N)&&Number.isFinite(u)&&!a||!e.every(Number.isFinite)||!r.every(Number.isFinite))return N;let x=z(e,r);if(x!==void 0)return x;let M=e.filter((s,f)=>r[f]!==0),{groups:[R],k:g}=S([M]),{groups:[c]}=S([r]),m=[];for(let s=0,f=0;s<e.length;s++)r[s]!==0&&m.push(R[f++]*c[s]);return w(p(m)/p(c),g)}function z(i,t){let n=[],e=[];for(let c=0;c<i.length;c++){if(t[c]===0)continue;let[m,s]=b(t[c]);if(e.push([m,s]),i[c]===0)continue;let[f,d]=b(i[c]);n.push([f*m,d+s])}let r=c=>{let m=0;for(let[,f]of c)m=Math.min(m,f);let s=0n;for(let[f,d]of c)s+=f<<BigInt(d-m);return[s,m]},[o,a]=r(n),[u,N]=r(e);if(u===0n)return;if(o===0n)return 0;u<0n&&(o=-o,u=-u);let x=o<0n,M=x?-o:o,R=Math.max(0,u.toString(2).length-M.toString(2).length+66),g=(M<<BigInt(R))/u;return g*u!==M<<BigInt(R)&&(g|=1n),_(x?-g:g,a-N-R)}function rn(i,t={}){l(t,W,"variance");let n=h(i,t.naRm);return n===void 0?NaN:D(n)}function on(i,t={}){l(t,j,"sd");let n=h(i,t.naRm);return n===void 0?NaN:K(n)}function J(i,t={}){l(t,q,"median");let n=h(i,t.naRm);if(n===void 0)return NaN;let e=n.length;if(e===0)return NaN;let r=[...n].sort((a,u)=>a-u),o=Math.floor(e/2);return e%2===1?r[o]:F([r[o-1],r[o]])[0]}function un(i,t={}){l(t,C,"range");let n=h(i,t.naRm);if(n===void 0)return[NaN,NaN];let e=1/0,r=-1/0;for(let o of n)o<e&&(e=o),o>r&&(r=o);return[e,r]}function sn(i){let t=Array.from(i),n=[],e=v(),r;for(let o of t){if(r===void 0&&!Number.isFinite(o)&&(r=0),r!==void 0){r+=o,n.push(r);continue}y(e,o,t.length),n.push(I(e))}return n}function fn(i){let t=[],n=Y(),e;for(let r of Array.from(i)){if(e===void 0&&(!Number.isFinite(r)||r===0)&&(e=k(n)),e!==void 0){e*=r,t.push(e);continue}O(n,r),t.push(B(n.p,n.e))}return t}function B(i,t){let n=i[0]+i[1];for(;t>0&&Number.isFinite(n);){let e=Math.min(t,1e3);n*=2**e,t-=e}for(;t<0&&n!==0;){let e=Math.max(t,-1e3);n*=2**e,t-=e}return n}function P(i,t){let n=[],e=NaN,r=!1;for(let o of Array.from(i)){if(r||Number.isNaN(o)){r=!0,n.push(NaN);continue}(n.length===0||t(o,e))&&(e=o),n.push(e)}return n}function an(i){return P(i,(t,n)=>t>n)}function cn(i){return P(i,(t,n)=>t<n)}function mn(i,t={}){l(t,H,"diff");let n=t.lag??1,e=t.differences??1;if(!(Number.isInteger(n)&&n>=1&&Number.isInteger(e)&&e>=1))throw new RangeError("'lag' and 'differences' must be integers >= 1");let r=Array.from(i);if(n*e>=r.length)return[];for(let o=0;o<e;o++){let a=[];for(let u=n;u<r.length;u++)a.push(r[u]-r[u-n]);r=a}return r}export{h as a,$ as b,nn as c,en as d,tn as e,rn as f,on as g,J as h,un as i,sn as j,fn as k,an as l,cn as m,mn as n};
@@ -1,2 +1,2 @@
1
- /*! rStats.js 1.19.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
- import{B as D,y as a}from"./chunk-HPIZAWMT.js";import{g as j}from"./chunk-2S45NNTL.js";import{g as h,j as g,k as x}from"./chunk-AS2XTRHH.js";import{g as X}from"./chunk-CNJLPH6W.js";import{d as G,j as P,k as L,l}from"./chunk-JXKHFSGK.js";var ct=["rate","scale"],at=["ncp"],Nt=["ncp"],mt=["ncp"],pt=5.656854,bt=.36787944117144233,Mt=.04166669,ht=.02083148,lt=.00801191,xt=.00144121,At=-7388e-8,gt=24511e-8,Ft=2424e-7,yt=.3333333,qt=-.250003,It=.2000062,Rt=-.1662921,_t=.1423657,Et=-.1367177,kt=.1233795,H=0,U=0,N=0,F=0,V=0,d=0,I=0,R=0,v=0;function J(t){let r=t/(N+N);return Math.abs(r)<=.25?d+.5*t*t*((((((kt*r+Et)*r+_t)*r+Rt)*r+It)*r+qt)*r+yt)*r:d-N*t+.25*t*t+(F+F)*Math.log(1+r)}function A(t,r){if(Number.isNaN(t)||Number.isNaN(r))return NaN;if(t<0||r<0)return NaN;if(t===0||r===0)return 0;if(!Number.isFinite(t)||!Number.isFinite(r))return 1/0;if(t<1){let i=1+bt*t,s,u;for(;;)if(u=i*h(),u>=1){if(s=-Math.log((i-u)/t),x()>=(1-t)*Math.log(s))break}else if(s=Math.exp(Math.log(u)/t),x()>=s)break;return s<2**-1022&&r>1?X(G(L([r,0]),P(L([u,0]),t)))[0]:r*s}t!==H&&(H=t,F=t-.5,N=Math.sqrt(F),V=pt-N*12);let n=g(),e=N+.5*n,o=e*e;if(n>=0)return r*o;let f=h();if(V*f<=n*n*n)return r*o;if(t!==U){U=t;let i=1/t;d=((((((Ft*i+gt)*i+At)*i+xt)*i+lt)*i+ht)*i+Mt)*i,t<=3.686?(I=.463+N+.178*F,R=1.235,v=.195/N-.079+.16*N):t<=13.022?(I=1.654+.0076*F,R=1.68/N+.275,v=.062/N+.024):(I=1.77,R=.75,v=.1515/N)}if(e>0){let i=J(n);if(Math.log(1-f)<=i)return r*o}for(;;){let i=x();if(f=h(),f=f+f-1,n=f<0?I-R*i:I+R*i,n>=-.71874483771719){let s=J(n);if(s>0){let u=Math.expm1(s);if(v*Math.abs(f)<=u*Math.exp(i-.5*n*n))break}}}return e=N+.5*n,r*e*e}function Zt(t,r,n={}){l(n,ct,"rgamma");let e=j(n);return a(t,()=>A(r,e))}function _(t){return!Number.isFinite(t)||t<0?NaN:A(t/2,2)}function Qt(t,r){if(Number.isNaN(t)||!Number.isFinite(r)||t<0||r<0)return NaN;if(r===0)return t===0?0:A(t/2,2);let n=y(r/2);return n>0&&(n=_(2*n)),t>0&&(n+=A(t/2,2)),n}function w(t,r,n={}){l(n,at,"rchisq");let{ncp:e}=n;return e===void 0?a(t,()=>_(r)):a(t,()=>Qt(r,e))}function $t(t,r,n={}){l(n,Nt,"rt");let{ncp:e}=n;if(e===void 0)return a(t,()=>Number.isNaN(r)||r<=0?NaN:Number.isFinite(r)?g()/Math.sqrt(_(r)/r):g());if(Number.isNaN(e))return a(t,()=>NaN);let o=a(t,()=>D(e,1));if(r===1/0)return o;let f=w(t,r);return o.map((i,s)=>i/Math.sqrt(f[s]/r))}function zt(t,r,n,e={}){l(e,mt,"rf");let{ncp:o}=e;if(o===void 0)return a(t,()=>{if(Number.isNaN(r)||Number.isNaN(n)||r<=0||n<=0)return NaN;let s=Number.isFinite(r)?_(r)/r:1,u=Number.isFinite(n)?_(n)/n:1;return s/u});let f=r===1/0?w(t,r,{ncp:o}).map(s=>Number.isNaN(s)?NaN:1):w(t,r,{ncp:o}).map(s=>s/r),i=n===1/0?a(t,()=>1):w(t,n).map(s=>s/n);return r>0&&n>0?f.map((s,u)=>s/i[u]):f.map(()=>NaN)}var St=["prob","mu"],Ot=-.5,vt=.3333333,wt=-.2500068,Kt=.2000118,Tt=-.1661269,Yt=.1421878,Lt=-.1384794,dt=.125006,Bt=1/7,Ct=1/12,Gt=1/24,W=.3989422804014327,Pt=[1,1,2,6,24,120,720,5040,40320,362880],M=0,Z=0,$=new Float64Array(36),K=0,z=0,B=0,T=0,tt=0,E=0,rt=0,nt=0,et=0,q=0,k=0,it=0,ot=0,st=0,ft=0,Q=0;function y(t){if(!Number.isFinite(t)||t<0)return NaN;if(t<=0)return 0;let r=t>=10,n=!1;if(!(r&&t===K))if(r)n=!0,K=t,E=Math.sqrt(t),rt=6*t*t,et=Math.floor(t-1.1484);else for(t!==K&&(K=t,Z=Math.max(1,Math.trunc(t)),M=0,T=tt=B=Math.exp(-t));;){let m=h();if(m<=tt)return 0;if(M>0){let c=m>.458?Math.min(M,Z):1;for(let p=c;p<=M;p++)if(m<=$[p])return p;if(M===35)continue}M++;for(let c=M;c<=35;c++)if(B*=t/c,T+=B,$[c]=T,m<=T)return M=c,c;M=35}let e=-1,o=0,f=0,i=0,s=t+E*g();if(s>=0&&(e=Math.floor(s),e>=et||(o=e,f=t-o,i=h(),rt*i>=f*f*f)))return e;(n||t!==z)&&(z=t,nt=W/E,q=Gt/t,k=.3*q*q,Q=Bt*q*k,ft=k-15*Q,st=q-6*k+45*Q,ot=1-q+3*k-15*Q,it=.1069/t);let u=0,S=0,Y=0,O=0,C=()=>{if(e<10)u=-t,S=Math.pow(t,e)/Pt[e];else{let p=Ct/o;p=p*(1-4.8*p*p);let b=f/o;Math.abs(b)<=.25?u=o*b*b*(((((((dt*b+Lt)*b+Yt)*b+Tt)*b+Kt)*b+wt)*b+vt)*b+Ot)-p:u=o*Math.log(1+b)-f-p,S=W/Math.sqrt(o)}let m=(.5-f)/E,c=m*m;Y=-.5*c,O=nt*(((Q*c+ft)*c+st)*c+ot)};if(s>=0&&(C(),O-i*O<=S*Math.exp(u-Y)))return e;for(;;){let m=x();i=2*h()-1;let c=1.8+(i>=0?m:-m);if(c>-.6744&&(e=Math.floor(t+E*c),o=e,f=t-o,C(),it*Math.abs(i)<=S*Math.exp(u+m)-O*Math.exp(Y+m)))break}return e}function or(t,r){return a(t,()=>y(r))}function sr(t,r){return a(t,()=>{if(!Number.isFinite(r)||r<=0||r>1)return NaN;let n=(1-r)/r,e=x(),o=Number.isFinite(n)?e*n:e*(1-r)/r;return o===1/0?1/0:y(o)})}function ut(t,r,n){let e=r/n;if(Number.isFinite(e))return y(A(t,e));let o=A(t,1)*r/n;return o===1/0?1/0:y(o)}function fr(t,r,n){l(n,St,"rnbinom");let{prob:e,mu:o}=n;if(e===void 0==(o===void 0))throw new TypeError("specify exactly one of prob and mu");let f=Number.isFinite(r)?r:Number.MAX_VALUE/2;if(o!==void 0)return a(t,()=>!Number.isFinite(o)||Number.isNaN(r)||r<=0||o<0?NaN:o===0?0:ut(f,o,f));let i=e;return a(t,()=>{if(!Number.isFinite(i)||Number.isNaN(r)||r<=0||i<=0||i>1)return NaN;if(i===1)return 0;let s=ut(f,1-i,i);return r===1/0?1/0:s})}export{y as a,or as b,sr as c,fr as d,A as e,Zt as f,w as g,$t as h,zt as i};
1
+ /*! rStats.js 1.20.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{g as a,j as D}from"./chunk-VFL4GGYT.js";import{g as j}from"./chunk-INNFAVT3.js";import{g as h,j as g,k as x}from"./chunk-MTSU2QHB.js";import{f as X}from"./chunk-PJJJR3H6.js";import{d as G,j as P,k as L,l}from"./chunk-ARPXG2PG.js";var ct=["rate","scale"],at=["ncp"],Nt=["ncp"],mt=["ncp"],pt=5.656854,bt=.36787944117144233,Mt=.04166669,ht=.02083148,lt=.00801191,xt=.00144121,At=-7388e-8,gt=24511e-8,Ft=2424e-7,yt=.3333333,qt=-.250003,It=.2000062,Rt=-.1662921,_t=.1423657,Et=-.1367177,kt=.1233795,H=0,U=0,N=0,F=0,V=0,d=0,I=0,R=0,v=0;function J(t){let r=t/(N+N);return Math.abs(r)<=.25?d+.5*t*t*((((((kt*r+Et)*r+_t)*r+Rt)*r+It)*r+qt)*r+yt)*r:d-N*t+.25*t*t+(F+F)*Math.log(1+r)}function A(t,r){if(Number.isNaN(t)||Number.isNaN(r))return NaN;if(t<0||r<0)return NaN;if(t===0||r===0)return 0;if(!Number.isFinite(t)||!Number.isFinite(r))return 1/0;if(t<1){let i=1+bt*t,s,u;for(;;)if(u=i*h(),u>=1){if(s=-Math.log((i-u)/t),x()>=(1-t)*Math.log(s))break}else if(s=Math.exp(Math.log(u)/t),x()>=s)break;return s<2**-1022&&r>1?X(G(L([r,0]),P(L([u,0]),t)))[0]:r*s}t!==H&&(H=t,F=t-.5,N=Math.sqrt(F),V=pt-N*12);let n=g(),e=N+.5*n,o=e*e;if(n>=0)return r*o;let f=h();if(V*f<=n*n*n)return r*o;if(t!==U){U=t;let i=1/t;d=((((((Ft*i+gt)*i+At)*i+xt)*i+lt)*i+ht)*i+Mt)*i,t<=3.686?(I=.463+N+.178*F,R=1.235,v=.195/N-.079+.16*N):t<=13.022?(I=1.654+.0076*F,R=1.68/N+.275,v=.062/N+.024):(I=1.77,R=.75,v=.1515/N)}if(e>0){let i=J(n);if(Math.log(1-f)<=i)return r*o}for(;;){let i=x();if(f=h(),f=f+f-1,n=f<0?I-R*i:I+R*i,n>=-.71874483771719){let s=J(n);if(s>0){let u=Math.expm1(s);if(v*Math.abs(f)<=u*Math.exp(i-.5*n*n))break}}}return e=N+.5*n,r*e*e}function Zt(t,r,n={}){l(n,ct,"rgamma");let e=j(n);return a(t,()=>A(r,e))}function _(t){return!Number.isFinite(t)||t<0?NaN:A(t/2,2)}function Qt(t,r){if(Number.isNaN(t)||!Number.isFinite(r)||t<0||r<0)return NaN;if(r===0)return t===0?0:A(t/2,2);let n=y(r/2);return n>0&&(n=_(2*n)),t>0&&(n+=A(t/2,2)),n}function w(t,r,n={}){l(n,at,"rchisq");let{ncp:e}=n;return e===void 0?a(t,()=>_(r)):a(t,()=>Qt(r,e))}function $t(t,r,n={}){l(n,Nt,"rt");let{ncp:e}=n;if(e===void 0)return a(t,()=>Number.isNaN(r)||r<=0?NaN:Number.isFinite(r)?g()/Math.sqrt(_(r)/r):g());if(Number.isNaN(e))return a(t,()=>NaN);let o=a(t,()=>D(e,1));if(r===1/0)return o;let f=w(t,r);return o.map((i,s)=>i/Math.sqrt(f[s]/r))}function zt(t,r,n,e={}){l(e,mt,"rf");let{ncp:o}=e;if(o===void 0)return a(t,()=>{if(Number.isNaN(r)||Number.isNaN(n)||r<=0||n<=0)return NaN;let s=Number.isFinite(r)?_(r)/r:1,u=Number.isFinite(n)?_(n)/n:1;return s/u});let f=r===1/0?w(t,r,{ncp:o}).map(s=>Number.isNaN(s)?NaN:1):w(t,r,{ncp:o}).map(s=>s/r),i=n===1/0?a(t,()=>1):w(t,n).map(s=>s/n);return r>0&&n>0?f.map((s,u)=>s/i[u]):f.map(()=>NaN)}var St=["prob","mu"],Ot=-.5,vt=.3333333,wt=-.2500068,Kt=.2000118,Tt=-.1661269,Yt=.1421878,Lt=-.1384794,dt=.125006,Bt=1/7,Ct=1/12,Gt=1/24,W=.3989422804014327,Pt=[1,1,2,6,24,120,720,5040,40320,362880],M=0,Z=0,$=new Float64Array(36),K=0,z=0,B=0,T=0,tt=0,E=0,rt=0,nt=0,et=0,q=0,k=0,it=0,ot=0,st=0,ft=0,Q=0;function y(t){if(!Number.isFinite(t)||t<0)return NaN;if(t<=0)return 0;let r=t>=10,n=!1;if(!(r&&t===K))if(r)n=!0,K=t,E=Math.sqrt(t),rt=6*t*t,et=Math.floor(t-1.1484);else for(t!==K&&(K=t,Z=Math.max(1,Math.trunc(t)),M=0,T=tt=B=Math.exp(-t));;){let m=h();if(m<=tt)return 0;if(M>0){let c=m>.458?Math.min(M,Z):1;for(let p=c;p<=M;p++)if(m<=$[p])return p;if(M===35)continue}M++;for(let c=M;c<=35;c++)if(B*=t/c,T+=B,$[c]=T,m<=T)return M=c,c;M=35}let e=-1,o=0,f=0,i=0,s=t+E*g();if(s>=0&&(e=Math.floor(s),e>=et||(o=e,f=t-o,i=h(),rt*i>=f*f*f)))return e;(n||t!==z)&&(z=t,nt=W/E,q=Gt/t,k=.3*q*q,Q=Bt*q*k,ft=k-15*Q,st=q-6*k+45*Q,ot=1-q+3*k-15*Q,it=.1069/t);let u=0,S=0,Y=0,O=0,C=()=>{if(e<10)u=-t,S=Math.pow(t,e)/Pt[e];else{let p=Ct/o;p=p*(1-4.8*p*p);let b=f/o;Math.abs(b)<=.25?u=o*b*b*(((((((dt*b+Lt)*b+Yt)*b+Tt)*b+Kt)*b+wt)*b+vt)*b+Ot)-p:u=o*Math.log(1+b)-f-p,S=W/Math.sqrt(o)}let m=(.5-f)/E,c=m*m;Y=-.5*c,O=nt*(((Q*c+ft)*c+st)*c+ot)};if(s>=0&&(C(),O-i*O<=S*Math.exp(u-Y)))return e;for(;;){let m=x();i=2*h()-1;let c=1.8+(i>=0?m:-m);if(c>-.6744&&(e=Math.floor(t+E*c),o=e,f=t-o,C(),it*Math.abs(i)<=S*Math.exp(u+m)-O*Math.exp(Y+m)))break}return e}function or(t,r){return a(t,()=>y(r))}function sr(t,r){return a(t,()=>{if(!Number.isFinite(r)||r<=0||r>1)return NaN;let n=(1-r)/r,e=x(),o=Number.isFinite(n)?e*n:e*(1-r)/r;return o===1/0?1/0:y(o)})}function ut(t,r,n){let e=r/n;if(Number.isFinite(e))return y(A(t,e));let o=A(t,1)*r/n;return o===1/0?1/0:y(o)}function fr(t,r,n){l(n,St,"rnbinom");let{prob:e,mu:o}=n;if(e===void 0==(o===void 0))throw new TypeError("specify exactly one of prob and mu");let f=Number.isFinite(r)?r:Number.MAX_VALUE/2;if(o!==void 0)return a(t,()=>!Number.isFinite(o)||Number.isNaN(r)||r<=0||o<0?NaN:o===0?0:ut(f,o,f));let i=e;return a(t,()=>{if(!Number.isFinite(i)||Number.isNaN(r)||r<=0||i<=0||i>1)return NaN;if(i===1)return 0;let s=ut(f,1-i,i);return r===1/0?1/0:s})}export{y as a,or as b,sr as c,fr as d,A as e,Zt as f,w as g,$t as h,zt as i};
@@ -0,0 +1,2 @@
1
+ /*! rStats.js 1.20.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{h as be}from"./chunk-VSV5QGXX.js";import{c as re,d as ye,e as ve,i as Fe,j as Xe}from"./chunk-OOHFFLMY.js";import{a as we,c as ge}from"./chunk-AWXW4WSX.js";import{d as Oe}from"./chunk-QCQBK5AC.js";import{b as he,c as Ie,o as oe}from"./chunk-DFGW4QWU.js";import{e as Se,f as _e}from"./chunk-VFL4GGYT.js";import{A as Te,B as Ne}from"./chunk-INNFAVT3.js";import{n as ne}from"./chunk-MTSU2QHB.js";import{e as Le}from"./chunk-B5GSH3AK.js";import{t as te,u as pe}from"./chunk-PJJJR3H6.js";import{l as j,u as N,v as de}from"./chunk-ARPXG2PG.js";var st=new Set(["n","delta","sd","sigLevel","power","type","alternative","strict","tol"]),at=["n","p1","p2","sigLevel","power","alternative","strict","tol"],it=["groups","n","betweenVar","withinVar","sigLevel","power"],$e=Number.EPSILON**.25;function G(e,t){if(e===void 0)return t[0];let r=t.find(o=>o===e);if(r!==void 0)return r;let n=t.filter(o=>o.startsWith(e));if(e.length===0||n.length!==1)throw new RangeError(`'arg' should be one of ${t.map(o=>`\u201C${o}\u201D`).join(", ")}`);return n[0]}var H=e=>e==null;function _(e,t,r){if(!H(e)&&!t(e))throw new RangeError(r)}var se=e=>e>=0&&e<=1,fe=e=>e>0&&e<1/0;function Me(e,t){if(e.filter(H).length!==1)throw new RangeError(t)}function L(e,t,r,n={}){return Oe(e,t,r,n).root}var Ve=(e,t,r,n)=>Se(e,t,{ncp:r,lowerTail:n});function xe(e,t){if(e!=null&&!(typeof e=="number"&&e>=0&&e<=1))throw new RangeError(t)}var qe="'sig.level' must be numeric in [0, 1]";function _t(e={}){j(e,st,"powerTTest");let{n:t,delta:r,power:n}=e,o=e.sd===void 0?1:e.sd,s=e.sigLevel===void 0?.05:e.sigLevel;Me([t,r,o,n,s],"exactly one of 'n', 'delta', 'sd', 'power', and 'sig.level' must be NULL"),xe(s,qe),_(n,se,"'power' must be a probability"),_(o,fe,"'sd' must be a positive finite number"),_(t,u=>u>=2,"number of observations in each group must be at least 2"),_(r,u=>!Number.isNaN(u),"'delta' must not be NaN"),_(e.tol,fe,"'tol' must be a positive finite number");let a=G(e.type,["two.sample","one.sample","paired"]),p=G(e.alternative,["two.sided","one.sided"]),f=e.strict??!1,c=e.tol??$e,d=a==="two.sample"?2:1,g=p==="two.sided"?2:1;g===2&&!H(r)&&(r=Math.abs(r));let v=(u,i,E,m)=>{let l=Math.max(1e-7,u-1)*d,h=_e(m/g,l,{lowerTail:!1}),b=Math.sqrt(u/d)*i/E;Number.isFinite(b)||(b=Math.sqrt(u/d)*(i/E));let w=Ve(h,l,b,!1);return f&&g===2?w+Ve(-h,l,b,!0):w};if(H(n))n=v(t,r,o,s);else{let u=n;if(H(t)){if(r===0)throw new RangeError("'n' cannot be determined when 'delta' is 0: the power does not depend on it");t=L(i=>v(i,r,o,s)-u,2,1e7,{tol:c,extendInt:"upX"})}else if(H(o)){if(r===0)throw new RangeError("'sd' cannot be determined when 'delta' is 0: the power does not depend on it");let i=Math.abs(r);o=L(E=>v(t,r,E,s)-u,i*1e-7,i*1e7,{tol:c,extendInt:r>0?"downX":"upX"})}else H(r)?r=L(i=>v(t,i,o,s)-u,o*1e-7,o*1e7,{tol:c,extendInt:"upX"}):s=L(i=>v(t,r,o,i)-u,1e-10,1-1e-10,{tol:c,extendInt:"yes"})}let y=a==="paired"?"n is number of *pairs*, sd is std.dev. of *differences* within pairs":a==="two.sample"?"n is number in *each* group":void 0,M={"two.sample":"Two-sample","one.sample":"One-sample",paired:"Paired"}[a]+" t test power calculation";return{n:t,delta:r,sd:o,sigLevel:s,power:n,alternative:p,...y===void 0?{}:{note:y},method:M,warnings:[]}}function Lt(e={}){j(e,at,"powerPropTest");let{n:t,p1:r,p2:n,power:o}=e,s=e.sigLevel===void 0?.05:e.sigLevel;Me([t,r,n,o,s],"exactly one of 'n', 'p1', 'p2', 'power', and 'sig.level' must be NULL"),xe(s,qe),_(o,se,"'power' must be a probability"),_(r,se,"'p1' must be a probability"),_(n,se,"'p2' must be a probability"),_(t,v=>v>0,"number of observations in each group must be positive"),_(e.tol,fe,"'tol' must be a positive finite number");let a=G(e.alternative,["two.sided","one.sided"]),p=e.strict??!1,f=e.tol??$e,c=a==="two.sided"?2:1,d=(v,y,M,u)=>{let i=pe(u/c,{lowerTail:!1});if(p&&c===2){let E=(y+M)/2,m=y*(1-y),l=M*(1-M),h=E*(1-E),b=Math.abs(y-M),w=Math.sqrt(m+l);return te((Math.sqrt(v)*b-i*Math.sqrt(2*h))/w)+te((Math.sqrt(v)*b+i*Math.sqrt(2*h))/w,{lowerTail:!1})}return te((Math.sqrt(v)*Math.abs(y-M)-i*Math.sqrt((y+M)*(1-(y+M)/2)))/Math.sqrt(y*(1-y)+M*(1-M)))},g=[];if(H(o))o=d(t,r,n,s);else{let v=o;if(H(t)){if(r===n)throw new RangeError("'n' cannot be determined when 'p1' equals 'p2': the power does not depend on it");t=L(y=>d(y,r,n,s)-v,1,1e7,{tol:f,extendInt:"upX"})}else if(H(r)){if(n===0)throw new RangeError("'p1' cannot be determined when 'p2' is 0: no p1 in [0, p2] differs from p2");r=L(y=>d(t,y,n,s)-v,0,n,{tol:f,extendInt:"yes"}),r<0&&g.push("No p1 in [0, p2] can be found to achieve the desired power")}else if(H(n)){if(r===1)throw new RangeError("'p2' cannot be determined when 'p1' is 1: no p2 in [p1, 1] differs from p1");n=L(y=>d(t,r,y,s)-v,r,1,{tol:f,extendInt:"yes"}),n>1&&g.push("No p2 in [p1, 1] can be found to achieve the desired power")}else s=L(y=>d(t,r,n,y)-v,1e-10,1-1e-10,{tol:f,extendInt:"upX"}),(s<0||s>1)&&g.push("No significance level [0, 1] can be found to achieve the desired power")}return ne("powerPropTest",{n:t,p1:r,p2:n,sigLevel:s,power:o,alternative:a,note:"n is number in *each* group",method:"Two-sample comparison of proportions power calculation",warnings:g})}var Be=1e16,ct=(e,t)=>e>Be&&e<1/0&&t>Be;function lt(e,t,r,n){let o=pe(n,{lowerTail:!1}),s=r/e,a=Math.sqrt(2/e+2/t),p=Math.hypot(Math.sqrt(2*(1+2*s)/e),Math.sqrt(2/t)*(1+s));return te((o*a-s)/p,{lowerTail:!1})}function ft(e,t,r,n){if(r===0)return 0;let o=c=>Math.floor(Math.log2(c)),[s,a,p,f]=[o(e),o(t),o(r),o(n)];return N(N(e,-s)*N(t,-a)*N(r,-p)/N(n,-f),s+a+p-f)}function Ot(e={}){j(e,it,"powerAnovaTest");let{groups:t,n:r,betweenVar:n,withinVar:o,power:s}=e,a=e.sigLevel===void 0?.05:e.sigLevel;if(Me([t,r,n,o,s,a],"exactly one of 'groups', 'n', 'between.var', 'within.var', 'power', and 'sig.level' must be NULL"),!H(t)&&!(t>=2))throw new RangeError("number of groups must be at least 2");if(!H(r)&&!(r>=2))throw new RangeError("number of observations in each group must be at least 2");xe(a,qe),_(s,se,"'power' must be a probability"),_(n,f=>f>=0&&f<1/0,"'betweenVar' must be a nonnegative finite number"),_(o,fe,"'withinVar' must be a positive finite number");let p=(f,c,d,g,v)=>{let y=(f-1)*c*d/g;y<1/0||(y=(f-1)*c*(d/g)),!(y<1/0)&&Number.isFinite(f)&&Number.isFinite(c)&&(y=ft(f-1,c,d,g));let M=f-1,u=(c-1)*f;return y===1/0?1:ct(M,u)?lt(M,u,y,v):Te(Ne(v,M,u,{lowerTail:!1}),M,u,{ncp:y,lowerTail:!1})};if(H(s))s=p(t,r,n,o,a);else{let f=s;if(H(t))t=L(c=>p(c,r,n,o,a)-f,2,100);else if(H(r)){if(n===0)throw new RangeError("'n' cannot be determined when 'betweenVar' is 0: the power does not depend on it");r=L(c=>p(t,c,n,o,a)-f,2,1e5)}else if(H(o)){if(n===0)throw new RangeError("'withinVar' cannot be determined when 'betweenVar' is 0: the power does not depend on it");o=L(c=>p(t,r,n,c,a)-f,n*1e-7,n*1e7)}else H(n)?n=L(c=>p(t,r,c,o,a)-f,o*1e-7,o*1e7):a=L(c=>p(t,r,n,o,c)-f,1e-10,1-1e-10)}return{groups:t,n:r,betweenVar:n,withinVar:o,sigLevel:a,power:s,note:"n is number in each group",method:"Balanced one-way analysis of variance power calculation",warnings:[]}}var ut=["type","omega","sandwich"],mt=["cluster","type","cadjust","multi0","fix","sandwich"],ue=2**-52;function Ce(e,t){if(t===0)return e;let r=Re.get(e)??{mant:e,exp:e.map(()=>0)};return Q(r.mant,r.exp.map(n=>n+t))}var me=e=>Math.floor(Math.log2(Math.abs(e)));function O(e){if(e===0||!Number.isFinite(e))return[e,0];let t=me(e);return[N(e,-t),t]}var ae=(e,t)=>[e[0]*t[0],e[1]+t[1]];function $(e,t=!1){let r=-1/0;for(let[o,s]of e)o!==0&&Number.isFinite(o)&&(r=Math.max(r,s+me(o)));let n=r===-1/0?0:r;return t&&(n=2*Math.floor(n/2)),{v:e.map(([o,s])=>de(o,s-n)),s:n}}var W=(e,t)=>Math.abs(t)<=2046?N(e,t):de(e,t),Re=new WeakMap;function Q(e,t){let r=e.map((n,o)=>n.map((s,a)=>W(s,t[o]+t[a])));return Re.set(r,{mant:e,exp:t}),r}function Yt(e,t,r){let n=Re.get(e),o=n?.mant[t]?.[t];if(!(n===void 0||o===void 0||!Object.is(W(o,2*n.exp[t]),r)))return W(Math.sqrt(o),n.exp[t])}function ce(e){return typeof e=="object"&&e!==null&&"family"in e&&"model"in e}function Ue(e){if(!(typeof e=="object"&&e!==null&&Array.isArray(e.coefficients)&&"qr"in e&&(ce(e)||"sigma"in e&&"x"in e&&"rows"in e)))throw new TypeError("'fit' must be the result of lm or glm")}function ze(e,t){return e.pivot.slice(0,t).map((r,n)=>[r,n]).sort((r,n)=>r[0]-n[0])}function Ke(e,t){let{inv:r,e:n}=we(e.qr.slice(0,t).map(s=>s.slice(0,t))),o=ze(e,t);return{inv:o.map(([,s])=>o.map(([,a])=>r[s][a])),e:o.map(([,s])=>n[s]),cols:o.map(([s])=>s)}}function We(e,t,r){let{inv:n,e:o,cols:s}=Ke(e,t);return{A:n.map((a,p)=>a.map((f,c)=>N(f,-o[p]-o[c]-r))),cols:s}}function je(e,t){let r=e.qr.slice(0,t).map(a=>a.slice(0,t)),n=r.map((a,p)=>{let f=0;for(let c=0;c<=p;c++)f=Math.max(f,Math.abs(r[c][p]));return f>0&&Number.isFinite(f)?me(f):0}),{inv:o}=we(r.map(a=>a.map((p,f)=>N(p,-n[f])))),s=ze(e,t);return{B:s.map(([,a])=>s.map(([,p])=>o[a][p])),e:s.map(([,a])=>n[a])}}function Ye(e,t){let r=e.qr.length;return Ie(e,Array.from({length:r},(n,o)=>Array.from({length:t},(s,a)=>o===a?1:0)))}function pt(e,t){let r=e.qr.length;return t===0?new Array(r).fill(0):Ye(e,t).map(o=>{let s=o.reduce((a,p)=>a+p*p,0);return s>1-10*ue?1:s})}function Qe(e,t,r,n){return r.map((o,s)=>{if(o>=1)return 0;let a=n(s);if(o<=.5||e===void 0||a<0)return 1-o;let p=e.qr.length,f=new Array(p).fill(0);f[a]=1;let c=he(e,f),d=0;for(let g=t;g<p;g++)d+=c[g]*c[g];return d})}function Ze(e){if(ce(e))return e.model.columnNames;let t=e.coefNames;if(t!==void 0)return t;let r=e.coefficients.length;return e.intercept?["(Intercept)",...Array.from({length:r-1},(n,o)=>`x${o+1}`)]:Array.from({length:r},(n,o)=>`x${o+1}`)}function dt(e){let t=Ze(e);if(e.qr===void 0||e.rank===0)return{vcov:[],names:[]};let{inv:r,e:n,cols:o}=Ke(e.qr,e.rank),s=ce(e)?0:be(e.qr),a,p;if(ce(e)){let c=re(e),d=ye(e).fixedDispersion?1:ve(c.fit),g=d===0||!Number.isFinite(d)?0:2*Math.floor(me(d)/2);a=N(d,-g),p=g+2*c.k}else{let[c,d]=O(e.sigma);a=c*c,p=2*d}let f=r.map(c=>c.map(d=>d*a));return{vcov:Q(f,n.map(c=>(p-s)/2-c)),names:o.map(c=>t[c])}}function Pe(e,t=!1){let r=Ze(e);if(ce(e)){let u=t?re(e):{fit:e,k:0},i=u.fit,E=ye(i),m=i.priorWeights,l=m.map(A=>A>0),h=m.flatMap((A,R)=>A>0?[R]:[]),{A:b,cols:w}=i.qr===void 0||i.rank===0?{A:[],cols:[]}:We(i.qr,i.rank,0),x=h.map(A=>w.map(R=>i.model.x[A][R])),q=h.map(A=>i.weights[A]),C=h.map(A=>i.weights[A]*i.residuals[A]),T=E.family==="binomial"||E.family==="poisson",k=T?1:C.reduce((A,R)=>A+R*R,0)/q.reduce((A,R)=>A+R,0),S=i.model.rows,z=Fe(i),K=Xe(i),Y=()=>{let A=re(i),R=h.map(I=>A.fit.residuals[I]),F=q.map(Math.sqrt),{B:ee,e:V}=i.qr===void 0||i.rank===0?{B:[],e:[]}:je(i.qr,i.rank),Z=x.map((I,B)=>I.map((P,X)=>N(F[B]*P,-V[X]))),{v:nt,s:rt}=$(F.map((I,B)=>I===0?[0,0]:ae(O(I),O(R[B])))),ot=()=>{let I=[1,0];if(!T){let B=$(q.map((X,D)=>X===0?[0,0]:ae(O(X),O(R[D])))),P=$(q.map(O));I=[B.v.reduce((X,D)=>X+D*D,0)/P.v.reduce((X,D)=>X+D,0),2*B.s-P.s+2*A.k]}return{T:x.map(B=>B.map((P,X)=>W(P,-V[X]))),factor:[I[0]*I[0],2*I[1]]}};return{T:Z,B:ee,e:V,u:nt,s:rt+A.k,omegaPart:ot}},le;if(U(k)&&C.every(Number.isFinite))le=C.map(A=>A/k);else{let A=re(i),R=$(q.map((F,ee)=>F===0?[0,0]:ae(O(F),O(A.fit.residuals[h[ee]]))));if(T)le=R.v.map(F=>W(F,R.s+A.k));else{let F=$(q.map(O)),ee=R.v.reduce((V,Z)=>V+Z*Z,0)/F.v.reduce((V,Z)=>V+Z,0);le=R.v.map(V=>W(V/ee,F.s-R.s-A.k))}}return{glm:!0,names:w.map(A=>r[A]),X:x,W:q,res:le,phiS:k,A:b,h:z,omh:Qe(i.qr,i.rank,z,A=>K[A]),qr:i.qr,rank:i.rank,qrRow:A=>K[A],inputRows:h.map(A=>S[A]),nInput:ge(e,S),nonZero:l,dispersion:()=>ve(i),scaled:Y,k:u.k}}let n=e,o=n.weights,s=n.residuals.map((u,i)=>o===void 0||o[i]!==0),a=s.flatMap((u,i)=>u?[i]:[]),p=be(n.qr),{A:f,cols:c}=n.rank===0?{A:[],cols:[]}:We(n.qr,n.rank,p),d=a.map(u=>c.map(i=>n.x[u][i])),g=a.map(u=>o?.[u]??1),v=a.map((u,i)=>g[i]*n.residuals[u]),y=pt(n.qr,n.rank),M=()=>{let u=g.map(w=>p===0?Math.sqrt(w):N(Math.sqrt(w),-p/2)),{B:i,e:E}=n.rank===0?{B:[],e:[]}:je(n.qr,n.rank),m=d.map((w,x)=>w.map((q,C)=>N(u[x]*q,-E[C]))),{v:l,s:h}=$(u.map((w,x)=>ae(O(w),O(n.residuals[a[x]]))));return{T:m,B:i,e:E,u:l,s:h,omegaPart:()=>({T:d.map(w=>w.map((x,q)=>W(x,-E[q]))),factor:[1,-2*p]})}};return{glm:!1,names:c.map(u=>r[u]),X:d,W:g,res:v,phiS:1,A:f,h:y,omh:Qe(n.qr,n.rank,y,u=>u),qr:n.qr,rank:n.rank,qrRow:u=>u,inputRows:a.map(u=>n.rows[u]),nInput:ge(n,n.rows),nonZero:s,dispersion:()=>n.sigma*n.sigma,scaled:M,k:0}}var ke=2**-969,U=e=>Math.abs(e)>=ke&&Math.abs(e)<1/0;function De(e,t,r,n){if(!(e.phiS>=ke&&e.phiS<1/0)||!U(e.X.length*e.phiS*e.phiS))return!1;for(let o=0;o<r.length;o++)if(!U(e.A[o][o])||!n&&(!U(t[o][o])||!U(r[o][o]))||!r[o].every(Number.isFinite))return!1;return!0}function ie(e,t,r){let n=e.length,s=e.map(a=>Array.from({length:n},(p,f)=>a.reduce((c,d,g)=>c+d*t[g][f],0))).map(a=>Array.from({length:n},(p,f)=>r*a.reduce((c,d,g)=>c+d*e[g][f],0)));for(let a=0;a<n;a++)for(let p=0;p<a;p++)s[a][p]=s[p][a];return s}function J(e,t,r){let n=e[0]?.length??0,o=Array.from({length:n},()=>new Array(n).fill(0));e.forEach((s,a)=>{let p=t[a];for(let f=0;f<n;f++)for(let c=f;c<n;c++)o[f][c]+=p*s[f]*s[c]});for(let s=0;s<n;s++)for(let a=s;a<n;a++)o[s][a]=o[a][s]=o[s][a]/r;return o}function Ee(e){let t=e.slice(0,10).map(r=>String(r+1));return e.length>10?`${t.join(", ")}, ...`:t.join(", ")}var ht=["HC3","const","HC","HC0","HC1","HC2","HC4","HC4m","HC5"];function Zt(e,t={}){j(t,ut,"vcovHC"),Ue(e);let r=G(t.type,ht),n=r==="HC"?"HC0":r,o=t.sandwich??!0;if(typeof o!="boolean")throw new TypeError("'sandwich' must be true or false");let s=Pe(e,t.omega===void 0),a=s.X.length,p=s.names.length,f=[],{res:c,h:d,omh:g}=s,v,y;if(t.omega!==void 0){let u;if(typeof t.omega=="function"?u=t.omega(c.slice(),d.slice(),a-p):(u=t.omega,u.length!==a&&u.length===s.nonZero.length&&(u=u.filter((i,E)=>s.nonZero[E]))),!Array.isArray(u)&&!ArrayBuffer.isView(u))throw new TypeError("'omega' must give an array of numbers");if(u.length!==a)throw new RangeError(`'omega' must have one value per observation (${a})`);if(v=Array.from(u,Number),v.some(i=>!Number.isFinite(i)))throw new RangeError("'omega' must be finite")}else if(n==="const"){let u=s.dispersion();v=s.W.map(i=>u*i/(s.phiS*s.phiS))}else{let u=d.flatMap((m,l)=>m>1-Math.sqrt(ue)?[s.inputRows[l]]:[]);if(u.length>0&&f.push(n==="HC0"||n==="HC1"?`${n} covariances become (close to) singular if hat values are (close to) 1 as for observation(s) ${Ee(u)}`:`${n} covariances are numerically unstable for hat values close to 1 (and undefined if exactly 1) as for observation(s) ${Ee(u)}`),n!=="HC0"&&n!=="HC1"){let m=d.flatMap((l,h)=>l>=1?[s.inputRows[h]]:[]);if(m.length>0)throw new RangeError(`${n} covariances are undefined for hat values of 1 as for observation(s) ${Ee(m)}`)}if(n==="HC1"&&a<=p)throw new RangeError("HC1 covariances need more observations than coefficients");let i=Math.round(d.reduce((m,l)=>m+l,0)),E=d.reduce((m,l)=>Math.max(m,l),0);y=m=>{switch(n){case"HC0":return m;case"HC1":return m.map(l=>l*a/(a-p));case"HC2":return m.map((l,h)=>l/g[h]);case"HC3":return m.map((l,h)=>l/g[h]**2);case"HC4":return m.map((l,h)=>l/g[h]**Math.min(4,a*d[h]/i));case"HC4m":return m.map((l,h)=>l/g[h]**(Math.min(1,a*d[h]/i)+Math.min(1.5,a*d[h]/i)));default:return m.map((l,h)=>l/Math.sqrt(g[h]**Math.min(a*d[h]/i,Math.max(4,a*.7*E/i))))}},v=y(c.map(m=>m*m))}let M;if(o&&n==="const"&&t.omega===void 0)M=dt(e).vcov;else if(o){let u=J(s.X,v,a);if(M=ie(s.A,u,a*s.phiS*s.phiS),!De(s,u,M,(y===void 0?v:c).every(i=>i===0))){let i=s.scaled();if(y!==void 0){let E=ie(i.B,J(i.T,y(i.u.map(m=>m*m)),a),a);M=Q(E,i.e.map(m=>i.s-m))}else{let{T:E,factor:m}=i.omegaPart(),l=$(v.map(h=>ae(O(h),m)),!0);M=Q(ie(i.B,J(E,l.v,a),a),i.e.map(h=>l.s/2-h))}}M=Ce(M,s.k)}else{let u=J(s.X,v,a);if(et(u,(y===void 0?v:c).every(i=>i===0)))M=u;else{let i=s.scaled();if(y!==void 0){let{mant:E,exp:m}=tt(i,J(i.T,y(i.u.map(l=>l*l)),a));M=Q(E,m)}else{let E=$(v.map(O),!0);M=Q(J(i.omegaPart().T,E.v,a),i.e.map(m=>E.s/2+m))}}M=Ce(M,-s.k)}return ne("vcovHC",{vcov:M,names:s.names,warnings:f},e)}var wt=["HC","HC0","HC1","HC2","HC3"];function gt(e){if(e==null||typeof e=="number"&&Number.isNaN(e))throw new RangeError("cannot handle NAs in 'cluster': either refit the model without the NA observations in 'cluster' or impute the NAs");if(typeof e=="boolean")return e?"TRUE":"FALSE";if(typeof e=="number")return Le(e);if(typeof e=="string")return e;throw new TypeError("cluster labels must be numbers, strings or booleans")}function bt(e){let t=new Map;return{g:e.map(n=>{let o=t.get(n);return o===void 0&&(o=t.size,t.set(n,o)),o}),G:t.size}}function yt(e){let t=[],r=(n,o,s)=>{if(s.length===n){t.push(s.slice());return}for(let a=o;a<e;a++)s.push(a),r(n,a+1,s),s.pop()};for(let n=1;n<=e;n++)r(n,0,[]);return t}var Ge=ue**(1/1.3);function Je(e,t){let{values:r,vectors:n}=oe(e,{symmetric:!0});if(r.some(a=>!(a>=Ge)))return;let o=n,s=r.map(a=>a**t);return e.map((a,p)=>e.map((f,c)=>o[p].reduce((d,g,v)=>d+g*s[v]*o[c][v],0)))}function vt(e){return{A:e.A,xs:t=>e.X[t].map(r=>r*Math.sqrt(e.W[t])),rs:t=>{let r=Math.sqrt(e.W[t]);return r===0?0:e.res[t]/r},single:(t,r,n)=>e.X[t].map(o=>r*e.res[t]*n*o),psi:t=>e.X[t].map(r=>r*e.res[t])}}function Mt(e){return{A:e.B,xs:t=>e.T[t],rs:t=>e.u[t],single:(t,r,n)=>e.T[t].map(o=>r*e.u[t]*n*o),psi:t=>e.T[t].map(r=>r*e.u[t])}}function xt(e,t,r,n,o){let s=e.names.length,a=Array.from({length:n},()=>[]);r.forEach((d,g)=>a[d].push(g));let p=Math.sqrt((n-1)/n),f=n===r.length,c;return a.map((d,g)=>{if(d.length===1){let m=d[0];if(f?e.h[m]>=1:!(e.omh[m]>=Ge))throw Ae(g);return t.single(m,p,e.omh[m]**o)}let v=d.map(t.xs),y=d.map(t.rs);if(e.qr!==void 0&&e.rank>0){c??=Ye(e.qr,e.rank);let m=qt(e,c,d,y,o);if(m===null)throw Ae(g);if(m!==void 0)return Array.from({length:s},(l,h)=>p*v.reduce((b,w,x)=>b+w[h]*m[x],0))}let M=v.map(m=>Array.from({length:s},(l,h)=>m.reduce((b,w,x)=>b+w*t.A[x][h],0))),u=v.map((m,l)=>v.map((h,b)=>(l===b?1:0)-M[l].reduce((w,x,q)=>w+x*h[q],0)));for(let m=0;m<u.length;m++)for(let l=0;l<m;l++)u[m][l]=u[l][m]=(u[m][l]+u[l][m])/2;let i=Je(u,o);if(i===void 0)throw Ae(g);let E=i.map(m=>m.reduce((l,h,b)=>l+h*y[b],0));return Array.from({length:s},(m,l)=>p*v.reduce((h,b,w)=>h+b[l]*E[w],0))})}function qt(e,t,r,n,o){let s=e.qr,a=e.rank,p=new Array(a).fill(0),f=r.map(b=>{let w=e.qrRow(b);return w<0?p:t[w]}),c=Array.from({length:a},(b,w)=>Array.from({length:a},(x,q)=>f.reduce((C,T)=>C+T[w]*T[q],0))),{values:d,vectors:g}=oe(c,{symmetric:!0});if(!d.some(b=>b>.5))return;let v=g,y=n.slice(),M=[];d.forEach((b,w)=>{let x=f.map(q=>q.reduce((C,T,k)=>C+T*v[k][w],0));if(b>.5)M.push(x.map(q=>q/Math.sqrt(b)));else if(b>0){let C=Math.expm1(o*Math.log1p(-b))/b*x.reduce((T,k,S)=>T+k*n[S],0);x.forEach((T,k)=>y[k]+=C*T)}});let u=s.qr.length,i=M.map(b=>{let w=new Array(u).fill(0);return r.forEach((x,q)=>{let C=e.qrRow(x);C>=0&&(w[C]=b[q])}),he(s,w).slice(a)}),E=i.map(b=>i.map(w=>b.reduce((x,q,C)=>x+q*w[C],0))),m=Je(E,o);if(m===void 0)return null;let l=M.map(b=>b.reduce((w,x,q)=>w+x*n[q],0)),h=m.map((b,w)=>b.reduce((x,q,C)=>x+q*l[C],0)-l[w]);return M.forEach((b,w)=>b.forEach((x,q)=>y[q]+=h[w]*x)),y}function Ae(e){return new RangeError(`clustered HC2/HC3 covariances are undefined: the block I - H_gg of cluster ${e+1} (in order of appearance) is singular, as with cluster fixed effects`)}function Et(e,t){let r=Array.from({length:t},()=>new Array(t).fill(0));for(let n of e)for(let o=0;o<t;o++)for(let s=0;s<t;s++)r[o][s]+=n[o]*n[s];return r}function He(e){if(e.length===0)return e;let{values:t,vectors:r}=oe(e,{symmetric:!0});if(t.every(s=>s>=0))return e;let n=r,o=t.map(s=>Math.max(s,0));return e.map((s,a)=>e.map((p,f)=>n[a].reduce((c,d,g)=>c+d*o[g]*n[f][g],0)))}function At(e,t){let r=e.length;if(r===0)return{mant:e,exp:t};let n=e.map((f,c)=>f[c]!==0?Math.sqrt(Math.abs(f[c])):1),o=e.map((f,c)=>f.map((d,g)=>d/n[c]/n[g])),{values:s}=oe(o,{symmetric:!0}),a=s.reduce((f,c)=>Math.max(f,Math.abs(c)),0);if(s.every(f=>f>=-16*r*ue*a))return{mant:e,exp:t};let p=Math.max(...t);return{mant:He(e.map((f,c)=>f.map((d,g)=>W(d,t[c]+t[g]-2*p)))),exp:t.map(()=>p)}}function et(e,t){return t||e.every((r,n)=>U(r[n])&&r.every(Number.isFinite))}function tt(e,t){let[r,n]=e.omegaPart().factor;return{mant:t.map(o=>o.map(s=>s/r)),exp:e.e.map(o=>e.s+o-n/2)}}function Pt(e,t={}){j(t,mt,"vcovCL"),Ue(e);let r=Pe(e,!0),n=r.X.length,o=r.names.length,s=t.type===void 0?r.glm?"HC0":"HC1":G(t.type,wt),a=s==="HC"?"HC0":s,p=t.cadjust??!0,f=t.multi0??!1,c=t.fix??!1,d=t.sandwich??!0;for(let[l,h]of[["cadjust",p],["multi0",f],["fix",c],["sandwich",d]])if(typeof h!="boolean")throw new TypeError(`'${l}' must be true or false`);let g,v=t.cluster;if(v===void 0)g=[r.inputRows.map(String)];else{let l=w=>Array.isArray(w)||ArrayBuffer.isView(w);if(!l(v))throw new TypeError("'cluster' must be an array of labels or an array of such arrays");let b=v.length>0&&Array.from(v).every(l)?Array.from(v):[v];if(b.length===0)throw new RangeError("'cluster' has no dimension");g=b.map(w=>{if(w.length!==r.nInput)throw new RangeError("number of observations in 'cluster' and 'estfun()' do not match");return r.inputRows.map(x=>gt(w[x]))})}if(a==="HC1"&&n<=o)throw new RangeError("HC1 covariances need more observations than coefficients");let y=g.length,M=yt(y).map((l,h)=>{let b=f&&y>1&&h===2**y-2,w=b?r.inputRows.map(String):r.inputRows.map((T,k)=>l.length===1?g[l[0]][k]:JSON.stringify(l.map(S=>g[S][k]))),{g:x,G:q}=bt(w);if(q<2)throw new RangeError("at least two clusters are needed");let C=b?a==="HC1"?(n-o)/(n-1):1:p?q/(q-1):1;return{g:x,G:q,c:C,sign:l.length%2===1?1:-1}}),u=l=>{let h=Array.from({length:o},()=>new Array(o).fill(0));for(let{g:b,G:w,c:x,sign:q}of M){let C;a==="HC2"||a==="HC3"?C=xt(r,l,b,w,a==="HC2"?-.5:-1):w===n?C=r.X.map((k,S)=>l.psi(S)):(C=Array.from({length:w},()=>new Array(o).fill(0)),r.X.forEach((k,S)=>{let z=C[b[S]],K=l.psi(S);for(let Y=0;Y<o;Y++)z[Y]+=K[Y]}));let T=Et(C,o);h=h.map((k,S)=>k.map((z,K)=>z+q*x*T[S][K]/n))}return a==="HC1"&&(h=h.map(b=>b.map(w=>w*(n-1)/(n-o)))),h},i=r.res.every(l=>l===0),E=r.phiS>=ke&&r.phiS<1/0&&r.A.every((l,h)=>U(l[h]))&&r.res.every(Number.isFinite),m;if(E){let l=u(vt(r));if(!d)et(l,i)&&(m=c?He(l):l);else{let h=ie(r.A,l,n*r.phiS*r.phiS);De(r,l,h,i)&&(m=c?He(h):h)}}if(m===void 0){let l=r.scaled(),h=u(Mt(l)),{mant:b,exp:w}=d?{mant:ie(l.B,h,n),exp:l.e.map(q=>l.s-q)}:tt(l,h),x=c?At(b,w):{mant:b,exp:w};m=Q(x.mant,x.exp)}return m=Ce(m,d?r.k:-r.k),ne("vcovCL",{vcov:m,names:r.names,warnings:[]},e)}export{G as a,H as b,Me as c,L as d,Ve as e,_t as f,Lt as g,ct as h,lt as i,Ot as j,Yt as k,ce as l,Ue as m,Ze as n,dt as o,Zt as p,Pt as q};
@@ -1,2 +1,2 @@
1
- /*! rStats.js 1.19.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
- import{C as R}from"./chunk-HPIZAWMT.js";import{l as E}from"./chunk-JXKHFSGK.js";var j=["tol"];function k(s,e,r){let h=s+r,u=s-r,f=Math.abs(u),m=e+e,o=Math.abs(m),[a,n]=Math.abs(s)>Math.abs(r)?[s,r]:[r,s],t=f>o?f*Math.sqrt(1+(o/f)**2):f<o?o*Math.sqrt(1+(f/o)**2):o*Math.SQRT2,c,w,i;h<0?(c=.5*(h-t),i=-1,w=a/c*n-e/c*e):h>0?(c=.5*(h+t),i=1,w=a/c*n-e/c*e):(c=.5*t,w=-.5*t,i=1);let M,g;u>=0?(M=u+t,g=1):(M=u-t,g=-1);let b,l;if(Math.abs(M)>o){let v=-m/M;l=1/Math.sqrt(1+v*v),b=v*l}else if(o===0)b=1,l=0;else{let v=-M/m;b=1/Math.sqrt(1+v*v),l=v*b}if(i===g){let v=b;b=-l,l=v}return{rt1:c,rt2:w,cs1:b,sn1:l}}function d(s){let e=s.length,r=Array.from({length:e},(o,a)=>Array.from({length:e},(n,t)=>a>=t?s[a][t]:s[t][a])),h=Array.from({length:e},(o,a)=>Array.from({length:e},(n,t)=>a===t?1:0)),u=2**-53;for(let o=0;o<100;o++){let a=!1;for(let n=0;n<e-1;n++)for(let t=n+1;t<e;t++){let c=r[n][t];if(c===0)continue;let w=r[n][n],i=r[t][t];if(Math.abs(c)<=u*Math.sqrt(Math.abs(w))*Math.sqrt(Math.abs(i))){r[n][t]=r[t][n]=0;continue}a=!0;let M=(i-w)/(2*c),g=Math.abs(M)>1e150?1/(2*M):Math.sign(M||1)/(Math.abs(M)+Math.sqrt(M*M+1)),b=1/Math.sqrt(1+g*g),l=g*b,v=l/(1+b);r[n][n]=w-g*c,r[t][t]=i+g*c,r[n][t]=r[t][n]=0;for(let p=0;p<e;p++){if(p!==n&&p!==t){let x=r[p][n],A=r[p][t];r[p][n]=r[n][p]=x-l*(A+v*x),r[p][t]=r[t][p]=A+l*(x-v*A)}let q=h[p][n],y=h[p][t];h[p][n]=q-l*(y+v*q),h[p][t]=y+l*(q-v*y)}}if(!a)break}let f=Array.from({length:e},(o,a)=>a).sort((o,a)=>r[a][a]-r[o][o]),m=Array.from({length:e},()=>new Array(e));return f.forEach((o,a)=>{let n=0;for(let c=1;c<e;c++)Math.abs(h[c][o])>Math.abs(h[n][o])&&(n=c);let t=h[n][o]<0?-1:1;for(let c=0;c<e;c++)m[c][a]=t*h[c][o]}),{values:f.map(o=>r[o][o]),vectors:m}}function _(s){let e=s.length;if(e===1)return{values:[s[0][0]],vectors:[[1]]};if(e===2){let{rt1:r,rt2:h,cs1:u,sn1:f}=k(s[0][0],s[1][0],s[1][1]);return r>=h?{values:[r,h],vectors:[[u,-f],[f,u]]}:{values:[h,r],vectors:[[-f,u],[u,f]]}}return d(s)}function z(s){let e=s.length;if(e===1)return[[Math.sqrt(Math.max(s[0][0],0))]];let{values:r,vectors:h}=d(s),u=r.map(m=>Math.sqrt(Math.max(m,0))),f=[];for(let m=0;m<e;m++){let o=[];for(let a=0;a<e;a++){let n=0;for(let t=0;t<e;t++)n+=h[m][t]*u[t]*h[a][t];o.push(n)}f.push(o)}return f}function N(s,e){if(s.length!==e||s.some(r=>r.length!==e))throw new RangeError("incompatible arguments");for(let r of s)for(let h of r)if(!Number.isFinite(h))throw new RangeError("'Sigma' must be finite")}function C(s,e,r,h={}){E(h,j,"mvrnorm");let u=h.tol??1e-6,f=Array.from(r,i=>Array.from(i));if(f.some(i=>i.length!==f[0].length))throw new TypeError("all rows of the matrix must have the same length");let m=e.length;N(f,m);let o=Math.trunc(s);if(!(o>=1))throw new RangeError(o===0?"non-conformable arguments":"invalid arguments");let{values:a,vectors:n}=_(f);if(!a.every(i=>i>=-u*Math.abs(a[0])))throw new RangeError("'Sigma' is not positive definite");let t=a.map(i=>Math.sqrt(Math.max(i,0))),c=R(o*m),w=[];for(let i=0;i<o;i++){let M=[];for(let g=0;g<m;g++){let b=0;for(let l=0;l<m;l++)b+=n[g][l]*t[l]*c[l*o+i];M.push(e[g]+b)}w.push(M)}return w}export{z as a,C as b};
1
+ /*! rStats.js 1.20.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{k as R}from"./chunk-VFL4GGYT.js";import{l as E}from"./chunk-ARPXG2PG.js";var j=["tol"];function k(s,e,r){let h=s+r,u=s-r,f=Math.abs(u),m=e+e,o=Math.abs(m),[a,n]=Math.abs(s)>Math.abs(r)?[s,r]:[r,s],t=f>o?f*Math.sqrt(1+(o/f)**2):f<o?o*Math.sqrt(1+(f/o)**2):o*Math.SQRT2,c,w,i;h<0?(c=.5*(h-t),i=-1,w=a/c*n-e/c*e):h>0?(c=.5*(h+t),i=1,w=a/c*n-e/c*e):(c=.5*t,w=-.5*t,i=1);let M,g;u>=0?(M=u+t,g=1):(M=u-t,g=-1);let b,l;if(Math.abs(M)>o){let v=-m/M;l=1/Math.sqrt(1+v*v),b=v*l}else if(o===0)b=1,l=0;else{let v=-M/m;b=1/Math.sqrt(1+v*v),l=v*b}if(i===g){let v=b;b=-l,l=v}return{rt1:c,rt2:w,cs1:b,sn1:l}}function d(s){let e=s.length,r=Array.from({length:e},(o,a)=>Array.from({length:e},(n,t)=>a>=t?s[a][t]:s[t][a])),h=Array.from({length:e},(o,a)=>Array.from({length:e},(n,t)=>a===t?1:0)),u=2**-53;for(let o=0;o<100;o++){let a=!1;for(let n=0;n<e-1;n++)for(let t=n+1;t<e;t++){let c=r[n][t];if(c===0)continue;let w=r[n][n],i=r[t][t];if(Math.abs(c)<=u*Math.sqrt(Math.abs(w))*Math.sqrt(Math.abs(i))){r[n][t]=r[t][n]=0;continue}a=!0;let M=(i-w)/(2*c),g=Math.abs(M)>1e150?1/(2*M):Math.sign(M||1)/(Math.abs(M)+Math.sqrt(M*M+1)),b=1/Math.sqrt(1+g*g),l=g*b,v=l/(1+b);r[n][n]=w-g*c,r[t][t]=i+g*c,r[n][t]=r[t][n]=0;for(let p=0;p<e;p++){if(p!==n&&p!==t){let x=r[p][n],A=r[p][t];r[p][n]=r[n][p]=x-l*(A+v*x),r[p][t]=r[t][p]=A+l*(x-v*A)}let q=h[p][n],y=h[p][t];h[p][n]=q-l*(y+v*q),h[p][t]=y+l*(q-v*y)}}if(!a)break}let f=Array.from({length:e},(o,a)=>a).sort((o,a)=>r[a][a]-r[o][o]),m=Array.from({length:e},()=>new Array(e));return f.forEach((o,a)=>{let n=0;for(let c=1;c<e;c++)Math.abs(h[c][o])>Math.abs(h[n][o])&&(n=c);let t=h[n][o]<0?-1:1;for(let c=0;c<e;c++)m[c][a]=t*h[c][o]}),{values:f.map(o=>r[o][o]),vectors:m}}function _(s){let e=s.length;if(e===1)return{values:[s[0][0]],vectors:[[1]]};if(e===2){let{rt1:r,rt2:h,cs1:u,sn1:f}=k(s[0][0],s[1][0],s[1][1]);return r>=h?{values:[r,h],vectors:[[u,-f],[f,u]]}:{values:[h,r],vectors:[[-f,u],[u,f]]}}return d(s)}function z(s){let e=s.length;if(e===1)return[[Math.sqrt(Math.max(s[0][0],0))]];let{values:r,vectors:h}=d(s),u=r.map(m=>Math.sqrt(Math.max(m,0))),f=[];for(let m=0;m<e;m++){let o=[];for(let a=0;a<e;a++){let n=0;for(let t=0;t<e;t++)n+=h[m][t]*u[t]*h[a][t];o.push(n)}f.push(o)}return f}function N(s,e){if(s.length!==e||s.some(r=>r.length!==e))throw new RangeError("incompatible arguments");for(let r of s)for(let h of r)if(!Number.isFinite(h))throw new RangeError("'Sigma' must be finite")}function C(s,e,r,h={}){E(h,j,"mvrnorm");let u=h.tol??1e-6,f=Array.from(r,i=>Array.from(i));if(f.some(i=>i.length!==f[0].length))throw new TypeError("all rows of the matrix must have the same length");let m=e.length;N(f,m);let o=Math.trunc(s);if(!(o>=1))throw new RangeError(o===0?"non-conformable arguments":"invalid arguments");let{values:a,vectors:n}=_(f);if(!a.every(i=>i>=-u*Math.abs(a[0])))throw new RangeError("'Sigma' is not positive definite");let t=a.map(i=>Math.sqrt(Math.max(i,0))),c=R(o*m),w=[];for(let i=0;i<o;i++){let M=[];for(let g=0;g<m;g++){let b=0;for(let l=0;l<m;l++)b+=n[g][l]*t[l]*c[l*o+i];M.push(e[g]+b)}w.push(M)}return w}export{_ as a,z as b,C as c};
@@ -0,0 +1,2 @@
1
+ /*! rStats.js 1.20.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{b as Xe}from"./chunk-CAUNJ7S6.js";import{d as Ke}from"./chunk-OOO5AAM7.js";import{d as We,e as xe,f as Be}from"./chunk-VFL4GGYT.js";import{n as Ge}from"./chunk-MTSU2QHB.js";import{b as Me}from"./chunk-7C2ECGT6.js";import{t as he,u as Le}from"./chunk-PJJJR3H6.js";import{P as Ue,l as me,m as Oe,q as Ce,v as z}from"./chunk-ARPXG2PG.js";var ot=new Set(["type","time2","dist","weights","offset","strata","scale","init","df","parms","control","intercept","confLevel"]),ut=["maxiter","relTolerance","tolerChol"],ct=["type","p","newX","newStrata","newOffset","seFit"],ft=["type","weighted"],Ie=new WeakMap;function Pt(e){return Ie.get(e)}var gt=Math.log(2*Math.PI),ht=e=>Number(e),dt=e=>e<-Math.LN2?Math.log1p(-Math.exp(e)):Math.log(-Math.expm1(e));function Ze(e,n){return n===-1/0?e:e<n?NaN:e+dt(n-e)}function mt(e,n){if(e===n)return 0;let r=Math.max(e,n),t=Math.min(e,n),a=r+Math.log(-Math.expm1(t-r));return(e>n?1:-1)*Math.exp(a)}function Ye(e,n){return n===0?0:Number.isFinite(n)?Math.sign(n)*Math.exp(e+Math.log(Math.abs(n))):Math.exp(e)*n}function pt(e,n,r){let t=n-e;return Number.isFinite(t)?t/r:n/r-e/r}function je(e,n,r){let t=n-e;if(Number.isFinite(t))return Math.log(t)-Math.log(r);let a=Math.max(Math.abs(e),Math.abs(n));return Math.log(a)+Math.log(n/a-e/a)-Math.log(r)}function wt(e,n,r){let t=je(e,n,r),a=t>Math.log(Number.MAX_VALUE)?1/0:Math.exp(t);if(a<1e-8){let s=n-e;return Me(e,n)+s*(a/24)}return a>50?n-r*t-r*Math.log1p(-Math.exp(-a)):e-r*(t-Math.log(Math.expm1(a)))}function bt(e,n,r){let t=je(e,n,r);if(t<Math.log(1e-8))return t-1;let a=t>Math.log(Number.MAX_VALUE)?1/0:Math.exp(t);if(!Number.isFinite(a))return 0;let s=a>50?a+Math.log1p(-Math.exp(-a)):Math.log(Math.expm1(a)),l=t-s,f=a>50?t-Math.log1p(-Math.exp(-a)):l+a;return Ze(-Math.exp(l),-Math.exp(f))}function Nt(e){return e<-36?e:-Math.log1p(Math.exp(-e))}function xt(e){return e>36?-e:-Math.log1p(Math.exp(e))}function He(e,n,r){if(e===-1/0)return-1/0;if(e===1/0)return 0;if(n==="extreme"||n==="weibull"||n==="exponential"||n==="rayleigh"){let t=Math.exp(e);return t===0?e:Math.log(-Math.expm1(-t))}return n==="logistic"||n==="loglogistic"?Nt(e):n==="gaussian"||n==="loggaussian"||n==="lognormal"?he(e,{logP:!0}):xe(e,r,{logP:!0})}function $e(e,n,r){return e===-1/0?0:e===1/0?-1/0:n==="extreme"||n==="weibull"||n==="exponential"||n==="rayleigh"?-Math.exp(e):n==="logistic"||n==="loglogistic"?xt(e):n==="gaussian"||n==="loggaussian"||n==="lognormal"?he(e,{lowerTail:!1,logP:!0}):xe(e,r,{lowerTail:!1,logP:!0})}function ye(e,n,r){return n==="extreme"||n==="weibull"||n==="exponential"||n==="rayleigh"?e===1/0?-1/0:e-Math.exp(e):n==="logistic"||n==="loglogistic"?-Math.abs(e)-2*Math.log1p(Math.exp(-Math.abs(e))):n==="gaussian"||n==="loggaussian"||n==="lognormal"?-.5*(e*e+gt):We(e,r,{log:!0})}function Ae(e,n,r){if(n==="extreme"||n==="weibull"||n==="exponential"||n==="rayleigh"){let a=Math.exp(e);return[1-a,a*a-3*a+1]}if(n==="logistic"||n==="loglogistic"){let a=Math.exp(-Math.abs(e));return[-Math.tanh(e/2),1-6*a/((1+a)*(1+a))]}if(n==="gaussian"||n==="loggaussian"||n==="lognormal")return[-e,e*e-1];let t=r+e*e;return[-(r+1)*e/t,(r+1)*((r+2)*e*e-r)/(t*t)]}function Mt(e,n,r){if(n==="extreme"||n==="weibull"||n==="exponential"||n==="rayleigh")return-Math.exp(e);if(n==="logistic"||n==="loglogistic"){let t=Math.exp(-Math.abs(e));return-2*t/((1+t)*(1+t))}return n==="gaussian"||n==="loggaussian"||n==="lognormal"?-1:-(r+1)*(r-e*e)/((r+e*e)*(r+e*e))}function ve(e,n,r,t,a,s,l){let f=e===-1/0?-1/0:(e-t)/a,o=n===1/0?1/0:(n-t)/a;if(r===1){let[$]=Ae(o,s,l),Z=ye(o,s,l),v=Mt(o,s,l);return{g:Z-Math.log(a),e:-$/a,ee:v/(a*a),t:-o*$-1,tt:o*$+o*o*v,et:($+o*v)/a}}let _=He(o,s,l),O=He(f,s,l),m=$e(f,s,l),b=$e(o,s,l),g=r===0?m:r===2?_:Ze(f>0?m:_,f>0?b:O),F=f===-1/0?0:Math.exp(r===0&&(s==="extreme"||s==="weibull"||s==="exponential"||s==="rayleigh")?f:ye(f,s,l)-g),d=o===1/0?0:Math.exp(ye(o,s,l)-g),[S]=Ae(f,s,l),[q]=Ae(o,s,l),V=F===0||f===-1/0?0:F*S,A=d===0||o===1/0?0:d*q,w=f===-1/0||F===0?0:f*F,M=o===1/0||d===0?0:o*d,W=f===-1/0||V===0?0:f*f*V,Q=o===1/0||A===0?0:o*o*A,p=-(d-F)/a,R=(A-V)/(a*a)-p*p,C=-(M-w),te=Q-W-C*(1+C),ce=((o===1/0||A===0?0:o*A)-(f===-1/0||V===0?0:f*V))/a-p*(1+C);return{g,e:p,ee:R,t:C,tt:te,et:ce}}function yt(e){let n=e.length,r=e.map((t,a)=>[...t,...t.map((s,l)=>a===l?1:0)]);for(let t=0;t<n;t++){let a=t;for(let l=t+1;l<n;l++)Math.abs(r[l][t])>Math.abs(r[a][t])&&(a=l);if(!Number.isFinite(r[a][t])||Math.abs(r[a][t])<=1e-13*Math.max(Number.MIN_VALUE,...e.map((l,f)=>Math.abs(l[f]??0))))throw new Error("singular information matrix");[r[t],r[a]]=[r[a],r[t]];let s=r[t][t];for(let l=0;l<2*n;l++)r[t][l]/=s;for(let l=0;l<n;l++)if(l!==t){let f=r[l][t];for(let o=0;o<2*n;o++)r[l][o]-=f*r[t][o]}}return r.map(t=>t.slice(n))}function ze(e,n){let r=e.length,t=0,a=!1;for(let o=0;o<r;o++){let _=e[o][o];_>0&&(!a||_>t)&&(t=_,a=!0)}let s=a?t*n:n,l=0,f=!0;for(let o=0;o<r;o++){let _=e[o][o];if(!Number.isFinite(_)||_<=s){e[o][o]=0,_<-8*s&&(f=!1);for(let O=o+1;O<r;O++)e[O][o]=0;continue}l++;for(let O=o+1;O<r;O++){let m=e[O][o]/_;e[O][o]=m,e[O][O]-=m*m*_;for(let b=O+1;b<r;b++)e[b][O]-=m*e[b][o]}}return f?l:-l}function et(e,n){let r=e.length,t=n.slice();for(let a=0;a<r;a++){let s=t[a];for(let l=0;l<a;l++)s-=t[l]*e[a][l];t[a]=s}for(let a=r-1;a>=0;a--){if(e[a][a]===0){t[a]=0;continue}let s=t[a]/e[a][a];for(let l=a+1;l<r;l++)s-=t[l]*e[l][a];t[a]=s}return t}function Je(e){let n=e.length;for(let r=0;r<n;r++)if(e[r][r]>0){e[r][r]=1/e[r][r];for(let t=r+1;t<n;t++){e[t][r]=-e[t][r];for(let a=0;a<r;a++)e[t][a]+=e[t][r]*e[r][a]}}for(let r=0;r<n;r++){if(e[r][r]===0){for(let t=0;t<n;t++)e[r][t]=0,e[t][r]=0;continue}for(let t=r+1;t<n;t++){let a=e[t][r]*e[t][t];e[r][t]=a;for(let s=r;s<t;s++)e[r][s]+=a*e[t][s]}}for(let r=0;r<n;r++)for(let t=0;t<r;t++)e[r][t]=e[t][r];return e}function ue(e,n){return e.map(r=>ie(r,n))}function ie(e,n){let r=e.reduce((t,a,s)=>t+a*n[s],0);return Ce(e,n,r)}function tt(e,n=1e-10){let r=n>0?Math.min(65536,1/Math.sqrt(n)):65536,t=Array.from({length:e[0].length},(a,s)=>{let l=e.map(o=>o[s]),f=0;for(let o of l)f=Math.max(f,Math.abs(o));if(f>r||f>0&&f<1/r){let o=Ue([l]);return{values:o.groups[0],exponent:o.k}}return{values:l,exponent:0}});return{values:e.map((a,s)=>t.map(l=>l.values[s])),exponent:t.map(a=>a.exponent)}}function Qe(e,n,r){return e<=0?-1/0:e>=1?1/0:n==="extreme"||n==="weibull"||n==="exponential"||n==="rayleigh"?Math.log(-Math.log1p(-e)):n==="logistic"||n==="loglogistic"?Math.log(e/(1-e)):n==="gaussian"||n==="loggaussian"||n==="lognormal"?Le(e):Be(e,r)}function Se(e,n,r,t,a,s,l,f,o,_,O,m,b,g,I,F=1e-10){let d=e[0].length,S=d+(m===void 0?o:0),q=tt(e,F),V=q.values,A=q.exponent,w=b.map((x,h)=>h<d?z(x,A[h]):x),M=(x,h)=>{let G=0,T=Array(S).fill(0),E=Array.from({length:S},()=>Array(S).fill(0)),L=Array.from({length:S},()=>Array(S).fill(0));for(let X=0;X<n.length;X++){let U=f[X],ae=ie(V[X],x.slice(0,d))+l[X],oe=m??Math.exp(x[d+U]),re=ve(r[X],t[X],a[X],ae,oe,_,O),J=s[X];G+=J*re.g;let ge=Array(S).fill(0);for(let k=0;k<d;k++)ge[k]=V[X][k]*re.e;m===void 0&&(ge[d+U]=re.t);for(let k=0;k<S;k++){T[k]+=J*ge[k];for(let ee=0;ee<S;ee++)L[k][ee]+=J*ge[k]*ge[ee]}if(h){for(let k=0;k<d;k++){for(let ee=0;ee<d;ee++)E[k][ee]+=J*V[X][k]*V[X][ee]*re.ee;m===void 0&&(E[k][d+U]+=J*V[X][k]*re.et)}if(m===void 0){for(let k=0;k<d;k++)E[d+U][k]+=J*V[X][k]*re.et;E[d+U][d+U]+=J*re.tt}}}return{ll:G,u:T,H:E,B:L}},W=x=>{let h=x.H.map(T=>T.map(E=>-E)),G=ze(h,F);return{factor:h,rank:G}},Q=x=>{let h=M(x,!0),G=W(h),T=G.rank>=0?et(G.factor,h.u):ue(yt(h.B),h.u);return{e:h,delta:T}},p=M(w,!0),R=p.ll,C=0,te=!1,ce=!1,$;try{$=Q(w)}catch{$={e:p,delta:Array(S).fill(0)}}let Z=w.map((x,h)=>x+$.delta[h]);if(g===0){let x=W(p),h=Je(x.factor),G=h.map(E=>E.slice()),T=h.map((E,L)=>E[L]===0?NaN:w[L]/Math.sqrt(Math.max(0,E[L])));return{b:w.map((E,L)=>L<d?z(E,-A[L]):E),ll:p.ll,iter:C,V:h.map((E,L)=>E.map((X,U)=>z(X,(L<d?-A[L]:0)+(U<d?-A[U]:0)))),VScaled:G,xExponent:A,score:p.u.map((E,L)=>L<d?z(E,A[L]):E),z:T,warn:te}}for(let x=1;x<=g;x++){let h=M(Z,!0);if(Number.isFinite(h.ll)&&Math.abs(1-R/h.ll)<=I){w.splice(0,w.length,...Z),p=h,R=h.ll,C=x,ce=!0;break}if(!Number.isFinite(h.ll)||h.ll<R){let G=Z.slice();Z=w.map((T,E)=>T+(G[E]-T)/3);for(let T=0;T<o;T++)m===void 0&&(Z[d+T]=Math.max(Z[d+T],w[d+T]-1.1));C=x;continue}if(w.splice(0,w.length,...Z),p=h,R=h.ll,C=x,x<g)try{let G=Q(w);Z=w.map((T,E)=>T+G.delta[E])}catch{Z=w.slice()}else try{let G=Q(w),T=w.map((L,X)=>L+G.delta[X]),E=M(T,!1);Number.isFinite(E.ll)&&E.ll>=R&&w.splice(0,w.length,...T)}catch{}}C===g&&g>=2&&!ce&&(te=!0);let v=M(w,!0),j=W(v),B=Je(j.factor),fe=B.map(x=>x.slice()),pe=B.map((x,h)=>x[h]===0?NaN:w[h]/Math.sqrt(Math.max(0,x[h])));return{b:w.map((x,h)=>h<d?z(x,-A[h]):x),ll:R,iter:C,V:B.map((x,h)=>x.map((G,T)=>z(G,(h<d?-A[h]:0)+(T<d?-A[T]:0)))),VScaled:fe,xExponent:A,score:v.u.map((x,h)=>h<d?z(x,A[h]):x),z:pe,warn:te}}function Dt(e,n,r=[],t={}){me(t,ot,"survreg"),me(Oe(t,"control"),ut,"survreg","control");let a=t.type??"right",s=t.dist??"weibull",l=t.df??t.parms??4,f=t.intercept??!0,o=e.length,_=n===void 0?Array(o).fill(1):Array.from(n,Number);if(_.length!==o||r.length!==0&&r.length!==o)throw new RangeError("variable lengths differ");if(a==="counting")throw new Error("start-stop type Surv objects are not supported");if(!["right","left","interval","interval2"].includes(a))throw new TypeError("invalid survival type");if(!["extreme","logistic","gaussian","weibull","exponential","rayleigh","loggaussian","lognormal","loglogistic","t"].includes(s))throw new RangeError("'arg' should be one of \u201Cextreme\u201D, \u201Clogistic\u201D, \u201Cgaussian\u201D, \u201Cweibull\u201D, \u201Cexponential\u201D, \u201Crayleigh\u201D, \u201Cloggaussian\u201D, \u201Clognormal\u201D, \u201Cloglogistic\u201D, \u201Ct\u201D");if((a==="interval"||a==="interval2")&&t.time2===void 0)throw new TypeError("time2 is required for interval data");if(t.time2!==void 0&&t.time2.length!==o)throw new RangeError("variable lengths differ (found for 'time2')");if(t.scale!==void 0&&(!Number.isFinite(t.scale)||t.scale<0))throw new RangeError("Invalid scale value");if(s==="t"&&(!(l>=3)||!Number.isFinite(l)))throw new RangeError("Degrees of freedom must be >=3");if(t.df!==void 0&&t.parms!==void 0)throw new RangeError("give the degrees of freedom of the t distribution as 'df' or as 'parms', not both");if(s!=="t"&&(t.df!==void 0||t.parms!==void 0))throw new RangeError("Extreme value distribution has no optional parameters");let O=["weibull","exponential","rayleigh","loggaussian","lognormal","loglogistic"].includes(s),m=t.scale!==void 0&&t.scale>0?t.scale:void 0,b=s==="exponential"||s==="rayleigh"?s==="exponential"?1:.5:m,g=t.time2,I=t.weights??Array(o).fill(1),F=t.offset??Array(o).fill(0),d=t.strata??Array(o).fill("1");for(let[i,u]of[[I,"weights"],[F,"offset"],[d,"strata"]])if(i.length!==o)throw new RangeError(`variable lengths differ (found for '${u}')`);let S=[],q=[],V=[],A=[],w=[],M=[],W=[],Q=[],p=[],R=(a==="right"||a==="left")&&_.some(i=>Number(i)===2),C=i=>{p.includes(i)||p.push(i)},te=[...new Set(d.map(String))].sort(),ce=d.map(i=>te.indexOf(String(i))),$=[];if(b!==void 0&&te.length>1)throw new Error("The scale argument is not valid with multiple strata");for(let i=0;i<o;i++){let u=r.length===0?[]:Array.from(r[i]);if((a==="interval2"?Number.isNaN(e[i])&&Number.isNaN(g[i]):a==="interval"&&ht(_[i])===3?Number.isNaN(e[i])||Number.isNaN(g[i]):Number.isNaN(e[i]))||a!=="interval2"&&Number.isNaN(_[i])||Number.isNaN(I[i])||Number.isNaN(F[i])||Number.isNaN(d[i])||u.some(Number.isNaN))continue;if(!(I[i]>0))throw new RangeError("Invalid weights, must be >0");if(u.some(P=>!Number.isFinite(P)))throw new Error("data contains an infinite predictor");let y=e[i],N=e[i],c=Number(_[i]);if(a==="right")if(R){if(c!==1&&c!==2){C("Invalid status value, converted to NA");continue}c===1&&(N=1/0),c=c===2?1:0}else{if(c!==0&&c!==1){C("Invalid status value, converted to NA");continue}c===0&&(N=1/0),c=c===1?1:0}else if(a==="left")if(R){if(c!==1&&c!==2){C("Invalid status value, converted to NA");continue}c===1&&(y=-1/0),c=c===2?1:2}else{if(c!==0&&c!==1){C("Invalid status value, converted to NA");continue}c===0&&(y=-1/0),c=c===1?1:2}else if(a==="interval"){if(N=g[i],c===0)y=e[i],N=1/0;else if(c===1)N=y;else if(c===2)N=e[i],y=-1/0;else if(c!==3){C("Invalid status value, converted to NA");continue}if(c===3&&y>N){C("Invalid interval: start > stop, NA created");continue}if(c===3&&y===N)throw new Error("initial iteration failed (use starting estimates?)")}else if(a==="interval2"){let P=e[i],D=g[i];if(Number.isNaN(P)&&Number.isNaN(D))continue;if(P>D){C("Invalid interval: start > stop, NA created");continue}P===D?(y=P,N=D,c=1):!Number.isFinite(P)||P===0?(y=-1/0,N=D,c=2):Number.isFinite(D)?(y=P,N=D,c=3):(y=P,N=1/0,c=0)}if(O){if((Number.isFinite(y)&&y<0||Number.isFinite(N)&&N<0)&&C("NaNs produced"),y===1/0||N===-1/0||Number.isFinite(y)&&y<=0||Number.isFinite(N)&&N<=0)throw new Error("Invalid survival times for this distribution");Number.isFinite(y)&&(y=Math.log(y)),Number.isFinite(N)&&(N=Math.log(N))}S.push(i),q.push(c===1?N:Number.isFinite(y)&&Number.isFinite(N)?Me(y,N):Number.isFinite(y)?y:N),V.push(y),A.push(N),w.push(c),M.push(I[i]),W.push(F[i]),Q.push(u),$.push(ce[i])}if(S.length===0)throw new Error("initial iteration failed (use starting estimates?)");if(!w.some(i=>i===1||i===3))throw new Error("initial iteration failed (use starting estimates?)");if(q.some(i=>!Number.isFinite(i)))throw new Error("initial iteration failed (use starting estimates?)");if(Q.some(i=>i.length!==Q[0].length))throw new TypeError("all rows of the matrix must have the same length");let Z=Q[0].length,v=Z+(f?1:0),j=Q.map(i=>f?[1,...i]:i),B=te.length,fe=q.map((i,u)=>i-W[u]),pe=M.reduce((i,u)=>i+u,0),x=fe.reduce((i,u,Y)=>i+u*M[Y],0)/pe,h=fe.reduce((i,u,Y)=>i+M[Y]*(u-x)**2,0)/pe,G=Math.max(...fe)-Math.min(...fe),T=s==="extreme"||s==="weibull"||s==="exponential"||s==="rayleigh"?h/1.64:s==="logistic"||s==="loglogistic"?h/3.2:s==="t"?h*(l-2)/l:h,E=b??2*Math.sqrt(T);if(b===void 0&&(!(E>0)||!(G>0)))throw new Error("initial iteration failed (use starting estimates?)");let L=v+(b===void 0?B:0),X=Array(L).fill(0);if(f&&(X[0]=x),b===void 0)for(let i=0;i<B;i++)X[v+i]=Math.log(E);let U=t.control??{},ae=U.maxiter??30,oe=U.relTolerance??1e-9;if(!Number.isInteger(ae)||ae<0||!Number.isFinite(oe)||oe<0)throw new RangeError("invalid control");if(U.tolerChol!==void 0&&(!Number.isFinite(U.tolerChol)||U.tolerChol<0))throw new RangeError("invalid control");let re=j.map(()=>[1]),J=j.every(i=>i.length===1&&i[0]===1);if(t.init!==void 0&&t.init.length!==v&&t.init.length!==L)throw new Error("Wrong length for initial parameters");let k=q.map((i,u)=>ve(V[u],A[u],w[u],i,b??E,s,l)).map((i,u)=>{let Y=-M[u]*i.ee;return Y>0&&Number.isFinite(Y)?{w:Y,r:q[u]-i.e/i.ee-W[u]}:{w:0,r:0}}),ee=k.reduce((i,u)=>i+u.w,0);if(!(ee>0))throw new Error("initial iteration failed (use starting estimates?)");let nt=k.reduce((i,u)=>i+u.w*u.r,0)/ee,Fe=[t.init!==void 0&&J?t.init[0]:nt,...b===void 0?Array(B).fill(Math.log(E)):[]];if(J&&t.init!==void 0&&t.init.length===L)for(let i=0;i<B;i++)Fe[1+i]=t.init[1+i];let rt=J?ae:Math.max(ae,1e3),le=Se(re,q,V,A,w,M,W,$,B,s,l,b,Fe,rt,oe,U.tolerChol??1e-10),se=X.slice();if(b===void 0)for(let i=0;i<B;i++)se[v+i]=le.b[1+i];if(!J&&t.init!==void 0){for(let i=0;i<v;i++)se[i]=t.init[i];if(t.init.length===L)for(let i=v;i<L;i++)se[i]=t.init[i]}else if(!J&&v>0){let i=Q.map((N,c)=>{let P=b??Math.exp(le.b[1+$[c]]),D=ve(V[c],A[c],w[c],q[c],P,s,l),H=-M[c]*D.ee;return H>0&&Number.isFinite(H)?{w:H,r:q[c]-D.e/D.ee-W[c]}:{w:0,r:0}}),u=tt(j,U.tolerChol??1e-10),Y=Array.from({length:v},(N,c)=>Array.from({length:v},(P,D)=>u.values.reduce((H,ne,De)=>H+i[De].w*ne[c]*ne[D],0))),y=Array.from({length:v},(N,c)=>u.values.reduce((P,D,H)=>P+i[H].w*D[c]*i[H].r,0));try{let N=Y.map(D=>D.slice()),P=ze(N,U.tolerChol??1e-10)>=0?et(N,y):ue(Ke(Y),y);se.splice(0,v,...P.map((D,H)=>z(D,-u.exponent[H])))}catch{}}let K=J?le:Se(j,q,V,A,w,M,W,$,B,s,l,b,se,ae,oe,U.tolerChol??1e-10);if(!J&&f&&v>1&&K.z.slice(1,v).some(Number.isNaN)){let i=Array.from({length:v},(N,c)=>c===0?0:j.reduce((P,D)=>P+D[c],0)/j.length),u=j.map(N=>N.map((c,P)=>c-i[P])),Y=se.slice();Y[0]=se[0]+i.reduce((N,c,P)=>N+c*se[P],0);let y=Se(u,q,V,A,w,M,W,$,B,s,l,b,Y,ae,oe,U.tolerChol??1e-10);if(!y.z.slice(0,v).some(Number.isNaN)){let N=y.b.length,c=Array.from({length:N},(H,ne)=>Array.from({length:N},(De,Ne)=>ne===Ne?1:ne===0&&Ne>0&&Ne<v?-i[Ne]:0)),P=ue(c,y.b),D=c.map(H=>c.map(ne=>ie(H,ue(y.V,ne))));K={...y,b:P,V:D,VScaled:D.map(H=>H.slice()),xExponent:Array(v).fill(0),z:D.map((H,ne)=>H[ne]>0?P[ne]/Math.sqrt(H[ne]):NaN)}}}let we=O?S.reduce((i,u,Y)=>i+(w[Y]===1?M[Y]*Math.log(e[u]):0),0)*-1:0,it=K.V.map(i=>i.slice()),de=K.b.slice(0,v).map((i,u)=>Number.isNaN(K.z[u])?NaN:i),Re=i=>{let u=K.VScaled[i]?.[i]??0;return u===0?0:z(Math.sqrt(Math.max(0,u)),i<v?-K.xExponent[i]:0)},vt=de.map((i,u)=>Re(u)),Et=de.map((i,u)=>K.z[u]).map(i=>2*he(-Math.abs(i))),at=b!==void 0?[b]:Array.from({length:B},(i,u)=>Math.exp(K.b[v+u])),lt=Array.from({length:v},(i,u)=>j.reduce((Y,y)=>Y+y[u],0)/j.length),st=j.map((i,u)=>ie(i,K.b.slice(0,v))+W[u]),qe=2*(K.ll+we-(le.ll+we)),_e=v+(b===void 0?B:0)-(1+(b===void 0?B:0)),Ve=[...de.map((i,u)=>u===0&&f?"(Intercept)":`x${u+(f?0:1)}`),...b===void 0?B===1?["Log(scale)"]:te:[]],be=[...de,...b===void 0?K.b.slice(v):[]],Te=be.map((i,u)=>Re(u)),Ee=be.map((i,u)=>K.z[u]),ke=Ee.map(i=>2*he(-Math.abs(i))),Pe={coefficients:de,coefNames:Ve.slice(0,v),scale:at,table:{value:be,se:Te,z:Ee,p:ke},strataLevels:te.map(i=>d.find(u=>String(u)===i)),hasOffset:t.offset!==void 0,icoef:b===void 0||S.length===1?le.b.slice():[le.b[0],Math.log(b)],var:it,loglik:[le.ll+we,K.ll+we],iter:K.iter,df:v+(b===void 0?B:0),idf:1+(b===void 0?B:0),dfResidual:S.length-(v+(b===void 0?B:0)),n:S.length,linearPredictors:st,means:lt,score:K.score.slice(),tableRowNames:Ve,value:be,se:Te,z:Ee,p:ke,chi:qe,chiDf:_e,chiP:Xe(qe,_e,{lowerTail:!1}),dist:s,distributionDf:l,parms:l,intercept:f,x:j,offset:W,rows:S,weights:M,strata:$,y:q,lower:V,upper:A,status:w,type:a,warnings:[...p,...K.warn||le.warn?["Ran out of iterations and did not converge"]:[],...s==="exponential"&&t.scale!==void 0&&t.scale>0?["Exponential has a fixed scale, user specified value ignored"]:[]]};return Ie.set(Pe,{V:K.VScaled,xExponent:K.xExponent}),Ge("survreg",Pe)}function Ot(e,n={}){me(n,ct,"survregPredict");let r=n.type??"lp",t=n.newX===void 0?e.x:n.newX.map(g=>e.intercept?[1,...g]:Array.from(g)),a=e.hasOffset?n.newOffset??(n.newX===void 0?e.offset:Array(t.length).fill(0)):Array(t.length).fill(0);if(a.length!==t.length)throw new RangeError("variable lengths differ (found for 'newOffset')");let s=e.strataLevels.map(String),l=n.newStrata?.map(g=>s.indexOf(String(g)))??(n.newX===void 0?e.strata.slice():t.map(()=>0));if(e.strataLevels.length>1&&n.newStrata===void 0&&n.newX!==void 0)throw new Error("object 's' not found");if(n.newStrata!==void 0&&n.newStrata.length!==t.length)throw new RangeError("variable lengths differ (found for 'newStrata')");if(n.newX!==void 0&&t.some(g=>g.length!==e.coefficients.length))throw new RangeError("newX has the wrong number of columns");if(l.some(g=>g<0))throw new Error("unknown stratum in newStrata");if(!["lp","linear","link","response","quantile","uquantile"].includes(r))throw new RangeError("invalid prediction type");let f=n.p===void 0?[.1,.9]:typeof n.p=="number"?[n.p]:Array.from(n.p),o=["weibull","exponential","rayleigh","loggaussian","lognormal","loglogistic"].includes(e.dist),_=t.map((g,I)=>{if(g.some(Number.isNaN))return r==="quantile"||r==="uquantile"?f.map(()=>NaN):NaN;let F=n.newX===void 0&&n.newOffset===void 0?e.linearPredictors[I]:ie(g,e.coefficients)+a[I],d=e.scale.length===1?e.scale[0]:e.scale[l[I]];return r==="lp"||r==="linear"||r==="link"?F:r==="response"?o?Math.exp(F):F:f.map(S=>{let q=F+d*Qe(S,e.dist,e.distributionDf);return r==="uquantile"?q:o?Math.exp(q):q})}),O=(r==="quantile"||r==="uquantile")&&f.length===1?_.map(g=>g[0]):_;if(!n.seFit)return O;let m=t.map((g,I)=>{if(g.some(Number.isNaN))return r==="quantile"||r==="uquantile"?f.map(()=>NaN):NaN;let F=n.newX===void 0&&n.newOffset===void 0?e.linearPredictors[I]:ie(g,e.coefficients)+a[I],d=e.scale.length===1?e.scale[0]:e.scale[l[I]],S=Ie.get(e),q=S?.V??e.var,V=A=>{let w=Array(q.length).fill(0);for(let M=0;M<g.length;M++)w[M]=S?z(g[M],-S.xExponent[M]):g[M];return q.length>g.length&&(w[g.length+l[I]]=A*d),Math.sqrt(Math.max(0,ie(w,ue(q,w))))};return r==="lp"||r==="linear"||r==="link"?V(0):r==="response"?o?Ye(F,V(0)):V(0):f.map(A=>{let w=Qe(A,e.dist,e.parms),M=V(w),W=F+d*w;return r==="uquantile"?M:o?Ye(W,M):M})}),b=(r==="quantile"||r==="uquantile")&&f.length===1?m.map(g=>g[0]):m;return{fit:O,seFit:b,warnings:[]}}function Lt(e,n={}){me(n,ft,"survregResiduals");let r=n.type??"response",t=e.distributionDf,a=e.coefficients.length,s=e.var.length,l=n.weighted??!1;if(!["response","deviance","working","dfbeta","dfbetas","ldcase","ldresp","ldshape","matrix"].includes(r))throw new RangeError("invalid residual type");let f=Ie.get(e),o=f?.V??e.var,_=e.x.map((O,m)=>{let b=e.linearPredictors[m],g=e.scale.length===1?e.scale[0]:e.scale[e.strata[m]],I=ve(e.lower[m],e.upper[m],e.status[m],b,g,e.dist,t),F=l?e.weights[m]:1,d=O.map((p,R)=>f?z(p,-f.xExponent[R]):p),S=Array(s).fill(0);for(let p=0;p<a;p++)S[p]=d[p]*I.e;s>a&&(S[a+e.strata[m]]=I.t);let q=ue(o,S),V=q.map((p,R)=>f&&R<a?z(p,-f.xExponent[R]):p),A=ie(S,q);if(r==="matrix")return[I.g,I.e,I.ee,I.t,I.tt,I.et].map(p=>p*F);if(r==="working")return-I.e/I.ee*F;if(r==="dfbeta")return V.map(p=>p*F);if(r==="dfbetas")return q.map((p,R)=>p/Math.sqrt(o[R]?.[R]??NaN)*F);if(r==="ldcase")return A*F;if(r==="ldresp"||r==="ldshape"){let p=Array(s).fill(0);for(let R=0;R<a;R++)p[R]=r==="ldresp"?g*(-d[R]*I.ee):d[R]*I.et;return s>a&&(p[a+e.strata[m]]=r==="ldresp"?-g*I.et:I.tt),ie(p,ue(o,p))*F}let w=ye(0,e.dist,t)-Math.log(g),M=e.status[m]===3?Me(e.lower[m],e.upper[m]):e.y[m];e.status[m]===3&&(e.dist==="extreme"||e.dist==="weibull"||e.dist==="exponential"||e.dist==="rayleigh")&&(M=wt(e.lower[m],e.upper[m],g));let W=e.status[m]===0?1:e.status[m]===2?-1:Math.sign(M-b);if(r==="deviance"){let p=e.status[m]===1?w:0;if(e.status[m]===3){let R=pt(e.lower[m],e.upper[m],g);e.dist==="extreme"||e.dist==="weibull"||e.dist==="exponential"||e.dist==="rayleigh"?p=bt(e.lower[m],e.upper[m],g):e.dist==="logistic"||e.dist==="loglogistic"?p=Math.log(Math.tanh(R/4)):e.dist==="gaussian"||e.dist==="loggaussian"||e.dist==="lognormal"?p=Math.log(2*he(R/2)-1):e.dist==="t"&&(p=Math.log(2*xe(R/2,e.distributionDf)-1))}return W*Math.sqrt(Math.max(0,2*(p-I.g)))*F}let Q=M-b;return(["weibull","exponential","rayleigh","loggaussian","lognormal","loglogistic"].includes(e.dist)?mt(M,b):Q)*F});return _}export{Pt as a,Dt as b,Ot as c,Lt as d};