@numero-uno-jpn/rstats 1.12.0 → 1.13.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 (80) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.ja.md +5 -5
  3. package/README.md +5 -5
  4. package/dist/causal/balance.d.ts +30 -18
  5. package/dist/causal/balance.js +74 -26
  6. package/dist/causal/weightit.d.ts +159 -0
  7. package/dist/causal/weightit.js +491 -0
  8. package/dist/causal.js +2 -2
  9. package/dist/chunks/{chunk-O6OMXX5U.js → chunk-24UIPUSE.js} +1 -1
  10. package/dist/chunks/{chunk-SLMS3FQD.js → chunk-2BXB6DRK.js} +1 -1
  11. package/dist/chunks/{chunk-XQSYV3IZ.js → chunk-2N7PIFPJ.js} +2 -2
  12. package/dist/chunks/{chunk-2P42OXYW.js → chunk-2SOBG73L.js} +2 -2
  13. package/dist/chunks/{chunk-NAACMR7H.js → chunk-3T4TVNXS.js} +2 -2
  14. package/dist/chunks/chunk-5Y425VAJ.js +2 -0
  15. package/dist/chunks/{chunk-UPFMYDF7.js → chunk-7V6FRF32.js} +2 -2
  16. package/dist/chunks/chunk-7ZKPFHAO.js +2 -0
  17. package/dist/chunks/{chunk-52KGBGFL.js → chunk-AH6IVJRF.js} +1 -1
  18. package/dist/chunks/{chunk-QT32BMYA.js → chunk-C7NEFIAH.js} +2 -2
  19. package/dist/chunks/{chunk-4GRV66HW.js → chunk-CAOEREY3.js} +2 -2
  20. package/dist/chunks/{chunk-4U65I4J2.js → chunk-CBAEKGP7.js} +2 -2
  21. package/dist/chunks/chunk-CCYGRSQW.js +2 -0
  22. package/dist/chunks/{chunk-4B7NEJCE.js → chunk-CEY7FHMZ.js} +2 -2
  23. package/dist/chunks/chunk-CKQOWTX7.js +3 -0
  24. package/dist/chunks/chunk-CSZCDPF3.js +2 -0
  25. package/dist/chunks/chunk-DQ2MIFRQ.js +2 -0
  26. package/dist/chunks/{chunk-3QSYPBUM.js → chunk-DZLOU6HK.js} +2 -2
  27. package/dist/chunks/{chunk-ZK7FW5UX.js → chunk-EWJS4VYF.js} +2 -2
  28. package/dist/chunks/{chunk-L54WIMTZ.js → chunk-GQ4HYF4L.js} +2 -2
  29. package/dist/chunks/{chunk-JG26HC2H.js → chunk-GRXOLZ6J.js} +2 -2
  30. package/dist/chunks/{chunk-SZR5HAMB.js → chunk-IIKFLH2E.js} +2 -2
  31. package/dist/chunks/{chunk-3QOW56EJ.js → chunk-JJGRQ22M.js} +2 -2
  32. package/dist/chunks/chunk-JTARV4D3.js +2 -0
  33. package/dist/chunks/{chunk-NGDBJR3K.js → chunk-KOF2HBUV.js} +2 -2
  34. package/dist/chunks/{chunk-YKCZF4ES.js → chunk-LS55YUPZ.js} +2 -2
  35. package/dist/chunks/chunk-M3LK23YR.js +2 -0
  36. package/dist/chunks/{chunk-CHKBDZC4.js → chunk-NRBTDLVW.js} +2 -2
  37. package/dist/chunks/{chunk-WUNTM7PJ.js → chunk-NWWY2WMF.js} +2 -2
  38. package/dist/chunks/{chunk-MAFZ5FGL.js → chunk-OVJU5WCL.js} +2 -2
  39. package/dist/chunks/{chunk-WACTNIKS.js → chunk-OWD2GUXJ.js} +2 -2
  40. package/dist/chunks/{chunk-ULQXNAI6.js → chunk-P2UT6OCU.js} +2 -2
  41. package/dist/chunks/{chunk-ZHAT6244.js → chunk-P6HSXCGZ.js} +2 -2
  42. package/dist/chunks/{chunk-7FXBOYIH.js → chunk-QWXSJEDI.js} +2 -2
  43. package/dist/chunks/{chunk-T5TE5KCP.js → chunk-RGEW3YLB.js} +2 -2
  44. package/dist/chunks/{chunk-WSDLT4AR.js → chunk-ST6I33C6.js} +1 -1
  45. package/dist/chunks/{chunk-CKBUE4FV.js → chunk-TQ4P6W3P.js} +2 -2
  46. package/dist/chunks/chunk-TTBKW2KL.js +2 -0
  47. package/dist/chunks/{chunk-HF3QOIZX.js → chunk-UMLJFZJ5.js} +2 -2
  48. package/dist/chunks/{chunk-7K2LMKZR.js → chunk-VO65CBCV.js} +2 -2
  49. package/dist/chunks/{chunk-SKQHW2GD.js → chunk-XRB552MP.js} +2 -2
  50. package/dist/chunks/{chunk-5AR4V7MW.js → chunk-XRBNTYQW.js} +2 -2
  51. package/dist/chunks/{chunk-MJ7IY7AF.js → chunk-Y4UWFH4Q.js} +2 -2
  52. package/dist/descriptive.js +2 -2
  53. package/dist/distributions.js +2 -2
  54. package/dist/entries/causal.d.ts +1 -0
  55. package/dist/entries/causal.js +1 -0
  56. package/dist/entries/tests.d.ts +2 -0
  57. package/dist/entries/tests.js +2 -0
  58. package/dist/linalg.js +2 -2
  59. package/dist/mixed.js +2 -2
  60. package/dist/models/survfitCoxph.d.ts +95 -0
  61. package/dist/models/survfitCoxph.js +223 -0
  62. package/dist/models/survival.d.ts +9 -2
  63. package/dist/models/survival.js +15 -11
  64. package/dist/models/svyglm.d.ts +77 -0
  65. package/dist/models/svyglm.js +102 -0
  66. package/dist/multivariate.js +2 -2
  67. package/dist/numerics.js +2 -2
  68. package/dist/regression.js +2 -2
  69. package/dist/rstats.js +17 -17
  70. package/dist/special.js +2 -2
  71. package/dist/tests.js +15 -15
  72. package/dist/timeseries.js +2 -2
  73. package/package.json +1 -1
  74. package/dist/chunks/chunk-7UI4PW32.js +0 -2
  75. package/dist/chunks/chunk-CMTCPLIA.js +0 -2
  76. package/dist/chunks/chunk-DWVTVOQS.js +0 -2
  77. package/dist/chunks/chunk-FFMMKXMK.js +0 -2
  78. package/dist/chunks/chunk-MUYGPZ37.js +0 -3
  79. package/dist/chunks/chunk-NQT7ZWL6.js +0 -2
  80. package/dist/chunks/chunk-PYFASERO.js +0 -2
@@ -0,0 +1,223 @@
1
+ // survival's survfit for a coxph fit with newdata: the predicted (adjusted) survival curves of covariate profiles, with
2
+ // case weights. The behaviour is in oracle/weightit-behaviour.md, from survival's documentation and published output;
3
+ // Kalbfleisch & Prentice (2002), "The Statistical Analysis of Failure Time Data", section 4.3, and Therneau & Grambsch
4
+ // (2000), "Modeling Survival Data", section 10.2, for the baseline hazard (Breslow, and the Efron form for tied events)
5
+ // and the variance of the predicted cumulative hazard (Tsiatis 1981). Written for rStats.js (no ported code).
6
+ import { coxph } from "./coxph.js";
7
+ import { curveMedian } from "./survival.js";
8
+ import { qnorm } from "../distributions/normal.js";
9
+ import { mergeTiedTimes } from "./tiedTimes.js";
10
+ import { ldexp } from "../internal/summary.js";
11
+ import { reported, unreported } from "../internal/warnings.js";
12
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
13
+ import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
14
+ const SURVFIT_COXPH_KEYS = /* @__PURE__ */ new Set([
15
+ "newdata", "confType", "confInt", "times", "ties", "weights", "init", "control", "nocenter", "confLevel", "robust",
16
+ ]);
17
+ const SURVFIT_COXPH_CONTROL_KEYS = ["eps", "iterMax", "tolerChol", "tolerInf", "timefix"];
18
+ /**
19
+ * Predicted survival curves of a Cox model for covariate profiles (adjusted survival curves). Equivalent to R's
20
+ * `survival::survfit.coxph()`. The call followed is
21
+ * `survfit(coxph(Surv(time, status) ~ ..., weights, robust = TRUE), newdata)`.
22
+ *
23
+ * The baseline cumulative hazard is Breslow's (with `ties: "breslow"`) or its Efron form for tied events (the default
24
+ * `"efron"`), with case weights; the curve of a profile z is exp(−exp((z − means) b) Λ0(t)). The standard error is
25
+ * that of the cumulative hazard (Tsiatis), with the fit's variance of the coefficients (the robust one when the fit
26
+ * uses it, as R; with non-integer weights coxph uses it by default). Strata and counting-process data are not supported.
27
+ * @category Survival analysis
28
+ * @example
29
+ * ```ts
30
+ * const s = survfitCoxph([5, 3, 8, 1, 9, 4], [1, 1, 0, 1, 0, 1], [[0], [1], [0], [1], [0], [1]], { newdata: [[0], [1]] });
31
+ * s.surv[1]; // [0.7165313106444244, 0.43459820864631604, 0.15987974627276413, 0, 0, 0] (the profile x = 1)
32
+ * ```
33
+ */
34
+ export function survfitCoxph(time, status, x, options = {}) {
35
+ checkOptions(options, SURVFIT_COXPH_KEYS, "survfitCoxph"); // generated: option-keys.mjs
36
+ checkOptions(nestedOptions(options, "control"), SURVFIT_COXPH_CONTROL_KEYS, "survfitCoxph", "control"); // generated: option-keys.mjs
37
+ const { newdata, confType = "log", confInt = 0.95, times, ...coxOptions } = options;
38
+ if (!["log", "log-log", "plain", "none"].includes(confType))
39
+ throw new RangeError(`invalid 'confType': ${String(confType)}`);
40
+ if (!(confInt > 0 && confInt < 1))
41
+ throw new RangeError("'confInt' must be between 0 and 1");
42
+ const fit = unreported(() => coxph(time, status, x, coxOptions));
43
+ const { ties = "efron", weights } = coxOptions;
44
+ // the curves from a fit on the columns rescaled exactly (a power of 2, less a first value), the same model: the
45
+ // variance of a coefficient of a column near 1e300 (about 1e-600) would underflow, and a column 1e15 + small
46
+ // differences lose its digits in the centring; newdata is mapped the same way
47
+ const maps = (x[0] ?? []).map((_, j) => columnMap(x.map((r) => r[j])));
48
+ const scaledX = x.map((r) => r.map((v, j) => maps[j](v)));
49
+ const work = unreported(() => coxph(time, status, scaledX, coxOptions));
50
+ const p = work.coefficients.length;
51
+ const beta = work.coefficients.map((b) => (Number.isFinite(b) ? b : 0));
52
+ // the variance of the fit as R keeps it in `var`: the robust one when the fit uses it
53
+ const V = work.var.map((r) => r.map((v) => (Number.isFinite(v) ? v : 0)));
54
+ // the rows the fit used (no missing value), in time order
55
+ const rows = [];
56
+ for (let i = 0; i < time.length; i++) {
57
+ if (Number.isNaN(time[i]) || Number.isNaN(status[i]) || x[i].some((v) => Number.isNaN(v)))
58
+ continue;
59
+ if (weights !== undefined && Number.isNaN(weights[i]))
60
+ continue;
61
+ rows.push(i);
62
+ }
63
+ // times within the tolerance of coxph's timefix (R's aeqSurv) are one time, as in the fit
64
+ const merged = coxOptions.control?.timefix === false ? time.slice() : mergeTiedTimes(time);
65
+ rows.sort((a, b) => merged[a] - merged[b]);
66
+ const w = (i) => (weights === undefined ? 1 : weights[i]);
67
+ const centred = (v) => v.map((e, j) => e - work.means[j]);
68
+ const risk = new Map();
69
+ for (const i of rows)
70
+ risk.set(i, Math.exp(centred(scaledX[i]).reduce((a, e, j) => a + e * beta[j], 0)));
71
+ // sums over the risk set, from the last time backwards
72
+ const distinct = [];
73
+ for (const i of rows)
74
+ if (distinct.length === 0 || distinct[distinct.length - 1] !== merged[i])
75
+ distinct.push(merged[i]);
76
+ const m = distinct.length;
77
+ const hazard = new Array(m).fill(0), varTerm = new Array(m).fill(0);
78
+ const xbarHaz = Array.from({ length: m }, () => new Array(p).fill(0));
79
+ const nRisk = new Array(m).fill(0), nEvent = new Array(m).fill(0), nCensor = new Array(m).fill(0);
80
+ let S0 = 0, Y = 0;
81
+ const S1 = new Array(p).fill(0);
82
+ let k = rows.length - 1;
83
+ for (let j = m - 1; j >= 0; j--) {
84
+ const t = distinct[j];
85
+ let d = 0, dw = 0, E0 = 0;
86
+ const E1 = new Array(p).fill(0);
87
+ for (; k >= 0 && merged[rows[k]] === t; k--) {
88
+ const i = rows[k], wi = w(i), ri = risk.get(i), xi = centred(scaledX[i]);
89
+ S0 += wi * ri;
90
+ Y += wi;
91
+ for (let a = 0; a < p; a++)
92
+ S1[a] += wi * ri * xi[a];
93
+ if (status[i] === 1) {
94
+ d++;
95
+ dw += wi;
96
+ E0 += wi * ri;
97
+ for (let a = 0; a < p; a++)
98
+ E1[a] += wi * ri * xi[a];
99
+ }
100
+ else
101
+ nCensor[j] += wi;
102
+ }
103
+ nRisk[j] = Y;
104
+ nEvent[j] = dw;
105
+ if (d === 0)
106
+ continue;
107
+ // Efron: the d tied events leave the risk set in d equal steps; Breslow: all at once
108
+ const steps = ties === "efron" ? d : 1;
109
+ for (let s = 0; s < steps; s++) {
110
+ const f = ties === "efron" ? s / d : 0;
111
+ const den = S0 - f * E0, share = dw / steps;
112
+ // divided one factor at a time: den * den under- or overflows for weights near 1e-200 or 1e200
113
+ const h = share / den;
114
+ hazard[j] += h;
115
+ varTerm[j] += h / den;
116
+ for (let a = 0; a < p; a++)
117
+ xbarHaz[j][a] += h * ((S1[a] - f * E1[a]) / den);
118
+ }
119
+ }
120
+ if (newdata?.some((z) => z.length !== p))
121
+ throw new RangeError("each row of 'newdata' must have one value per column of 'x'");
122
+ // the default profile is the means of the fit as R keeps them (0 for the columns coxph does not centre)
123
+ const profiles = (newdata ?? [fit.means]).map((z) => z.map((v, j) => maps[j](v)));
124
+ const zq = confInt < 1 - 1e-8 ? qnorm(1 - (1 - confInt) / 2) : qnorm((1 - confInt) / 2, { lowerTail: false });
125
+ const surv = [], stdErr = [], lower = [], upper = [], cumhaz = [];
126
+ for (const z of profiles) {
127
+ const zc = centred(z);
128
+ const rz = Math.exp(zc.reduce((a, e, j) => a + e * beta[j], 0));
129
+ let H = 0, v1 = 0;
130
+ const q = new Array(p).fill(0);
131
+ const s = [], se = [], lo = [], up = [], ch = [];
132
+ for (let j = 0; j < m; j++) {
133
+ H += hazard[j];
134
+ v1 += varTerm[j];
135
+ for (let a = 0; a < p; a++)
136
+ q[a] += zc[a] * hazard[j] - xbarHaz[j][a];
137
+ let quad = 0;
138
+ for (let a = 0; a < p; a++)
139
+ for (let b = 0; b < p; b++)
140
+ quad += q[a] * V[a][b] * q[b];
141
+ const cum = rz * H, sv = Math.exp(-cum), e = rz * Math.sqrt(v1 + quad);
142
+ ch.push(cum);
143
+ s.push(sv);
144
+ se.push(e);
145
+ const [l, u] = limits(sv, e, zq, confType);
146
+ lo.push(l);
147
+ up.push(u);
148
+ }
149
+ surv.push(s);
150
+ stdErr.push(se);
151
+ lower.push(lo);
152
+ upper.push(up);
153
+ cumhaz.push(ch);
154
+ }
155
+ const median = surv.map((s, c) => [curveMedian(distinct, s), curveMedian(distinct, lower[c]), curveMedian(distinct, upper[c])]);
156
+ const result = {
157
+ fit, time: distinct, nRisk, nEvent, nCensor, surv, stdErr, lower, upper, cumhaz, median,
158
+ records: rows.length, nStart: nRisk[0] ?? 0, events: nEvent.reduce((a, b) => a + b, 0), warnings: fit.warnings.slice(),
159
+ };
160
+ if (times !== undefined)
161
+ result.at = readAt(result, times);
162
+ return reported("survfitCoxph", result);
163
+ }
164
+ /** The exact map of a column to units near 1: v 2^-e1 less the first such value, times 2^-e2 */
165
+ function columnMap(c) {
166
+ const exponent = (vals) => {
167
+ let top = 0;
168
+ for (const v of vals)
169
+ if (Number.isFinite(v) && Math.abs(v) > top)
170
+ top = Math.abs(v);
171
+ return top > 0 ? Math.floor(Math.log2(top)) : 0;
172
+ };
173
+ const e1 = exponent(c);
174
+ const first = ldexp(c.find((v) => Number.isFinite(v)) ?? 0, -e1);
175
+ const e2 = exponent(c.map((v) => ldexp(v, -e1) - first));
176
+ return (v) => ldexp(ldexp(v, -e1) - first, -e2);
177
+ }
178
+ /** Pointwise limits of a survival value from the standard error of its cumulative hazard */
179
+ function limits(s, se, z, type) {
180
+ if (type === "none" || !Number.isFinite(se))
181
+ return [NaN, NaN];
182
+ if (type === "plain")
183
+ return [Math.max(0, s - z * se * s), Math.min(1, s + z * se * s)];
184
+ if (s === 0)
185
+ return [NaN, NaN];
186
+ if (type === "log")
187
+ return [Math.exp(Math.log(s) - z * se), Math.min(1, Math.exp(Math.log(s) + z * se))];
188
+ // log-log: on the scale of log(-log S), whose standard error is se / |log S|
189
+ if (s === 1)
190
+ return [NaN, NaN];
191
+ const ll = Math.log(-Math.log(s)), e = se / Math.log(s);
192
+ return [Math.exp(-Math.exp(ll - z * e)), Math.exp(-Math.exp(ll + z * e))];
193
+ }
194
+ /** The curves read at given times: the last row at or before each time; before the first, the start of the curve */
195
+ function readAt(r, times) {
196
+ const sorted = [...times].sort((a, b) => a - b);
197
+ const out = { time: [], surv: r.surv.map(() => []), stdErr: r.surv.map(() => []),
198
+ lower: r.surv.map(() => []), upper: r.surv.map(() => []), nRisk: [], nEvent: [] };
199
+ let from = 0;
200
+ for (const t of sorted) {
201
+ let j = -1;
202
+ while (j + 1 < r.time.length && r.time[j + 1] <= t)
203
+ j++;
204
+ if (t > r.time[r.time.length - 1])
205
+ break;
206
+ out.time.push(t);
207
+ // the number at risk at t: that of the first row at or after t
208
+ const next = r.time.findIndex((u) => u >= t);
209
+ out.nRisk.push(next < 0 ? 0 : r.nRisk[next]);
210
+ let ev = 0;
211
+ for (let k = from; k <= j; k++)
212
+ ev += r.nEvent[k];
213
+ out.nEvent.push(ev);
214
+ from = j + 1;
215
+ r.surv.forEach((_, c) => {
216
+ out.surv[c].push(j < 0 ? 1 : r.surv[c][j]);
217
+ out.stdErr[c].push(j < 0 ? 0 : r.stdErr[c][j]);
218
+ out.lower[c].push(j < 0 ? 1 : r.lower[c][j]);
219
+ out.upper[c].push(j < 0 ? 1 : r.upper[c][j]);
220
+ });
221
+ }
222
+ return out;
223
+ }
@@ -56,13 +56,14 @@ export interface SurvfitOptions {
56
56
  start?: readonly number[];
57
57
  /** Subject identifiers for counting-process data; requires `start`; adjacent split rows are not censorings. */
58
58
  id?: readonly (GroupLabel | null)[];
59
- /** Case weights. Non-negative safe-integer counts are required. */
59
+ /** Case weights, non-negative (inverse probability weights need not be integers; not with `stype: 2` and the robust
60
+ * variance). */
60
61
  weights?: readonly number[];
61
62
  /** Cumulative hazard estimator: 1 Nelson-Aalen, 2 Fleming-Harrington. Default 1. */
62
63
  ctype?: 1 | 2;
63
64
  /** Survival estimator: 1 Kaplan-Meier, 2 exponential of cumulative hazard. Default 1. */
64
65
  stype?: 1 | 2;
65
- /** Use the infinitesimal-jackknife variance. Default false; non-integer weights are rejected. */
66
+ /** Use the infinitesimal-jackknife variance. Default as R: true when some weight is not an integer, else false. */
66
67
  robust?: boolean;
67
68
  /** Restricted-mean upper limit: "common" (default), "individual", "none", or a finite number. */
68
69
  rmean?: "none" | "common" | "individual" | number;
@@ -150,6 +151,12 @@ export interface SurvfitResult {
150
151
  * @category Survival analysis
151
152
  */
152
153
  export declare function survdiff(time: readonly number[], status: readonly number[], group: readonly (GroupLabel | null)[], options?: SurvdiffOptions): SurvdiffResult;
154
+ /**
155
+ * The median of a curve over the rows of a stratum, as survival's survmean (minmin): of the points that are not NaN
156
+ * and lie below 0.5 + sqrt(eps), the first time, or, if the curve equals 0.5 (within sqrt(eps)) there and a later such
157
+ * point is lower, the midpoint between that time and the time of the first lower point. NaN if there is no such point.
158
+ */
159
+ export declare function curveMedian(time: readonly number[], curve: readonly number[]): number;
153
160
  /**
154
161
  * Kaplan-Meier or exponential cumulative-hazard estimate with pointwise confidence intervals, medians and restricted means.
155
162
  * Equivalent to R's `survival::survfit()`. Supports right-censored and counting-process data, Nelson-Aalen and Fleming-Harrington cumulative hazards,
@@ -184,7 +184,7 @@ function pseudoQuadratic(V, u) {
184
184
  * and lie below 0.5 + sqrt(eps), the first time, or, if the curve equals 0.5 (within sqrt(eps)) there and a later such
185
185
  * point is lower, the midpoint between that time and the time of the first lower point. NaN if there is no such point.
186
186
  */
187
- function curveMedian(time, curve) {
187
+ export function curveMedian(time, curve) {
188
188
  const tol = Math.sqrt(Number.EPSILON);
189
189
  const first = curve.findIndex((c) => c < 0.5 + tol);
190
190
  if (first < 0)
@@ -221,7 +221,7 @@ function curveMedian(time, curve) {
221
221
  */
222
222
  export function survfit(time, status, options = {}) {
223
223
  checkOptions(options, SURVFIT_KEYS, "survfit"); // generated: option-keys.mjs
224
- const { group, start: startTimes, id, weights, ctype = 1, stype = 1, robust = false, rmean = "common", confType: confTypeInput = "log", confInt = 0.95 } = options;
224
+ const { group, start: startTimes, id, weights, ctype = 1, stype = 1, rmean = "common", confType: confTypeInput = "log", confInt = 0.95 } = options;
225
225
  if (typeof confTypeInput !== "string")
226
226
  throw new TypeError("confType must be a string");
227
227
  const confTypes = ["log", "log-log", "plain", "none", "logit", "arcsin"];
@@ -259,8 +259,15 @@ export function survfit(time, status, options = {}) {
259
259
  throw new TypeError("'weights' must be an array");
260
260
  if (weights !== undefined && weights.length !== time.length)
261
261
  throw new RangeError("'weights' must have the same length as 'time'");
262
+ // R's default: the robust (infinitesimal jackknife) variance when a case weight is not an integer
263
+ const robust = options.robust ?? (weights !== undefined && Array.from(weights).some((w) => w != null && Number.isFinite(w) && !Number.isInteger(w)));
262
264
  if (typeof robust !== "boolean")
263
265
  throw new TypeError("'robust' must be a boolean");
266
+ // the robust exponential-hazard curve (stype 2) has been checked with integer weights only (its restricted-mean
267
+ // standard error is not right with fractional ones): kept out
268
+ if (robust && stype === 2 && weights !== undefined && Array.from(weights).some((w) => w != null && Number.isFinite(w) && !Number.isInteger(w))) {
269
+ throw new RangeError("non-integer weights with stype 2 and the robust variance are not supported");
270
+ }
264
271
  if (typeof rmean !== "number" && typeof rmean !== "string")
265
272
  throw new TypeError("rmean must be a number or string");
266
273
  if (typeof rmean === "number" && !Number.isFinite(rmean))
@@ -280,8 +287,6 @@ export function survfit(time, status, options = {}) {
280
287
  throw new RangeError("weights must be finite");
281
288
  if (w < 0)
282
289
  throw new RangeError("weights must be non-negative");
283
- if (!Number.isSafeInteger(w))
284
- throw new RangeError("weights must be non-negative safe integers");
285
290
  if (time[i] != null && typeof time[i] !== "number")
286
291
  throw new TypeError("'time' must contain numbers");
287
292
  if (status[i] != null && typeof status[i] !== "number")
@@ -366,9 +371,6 @@ export function survfit(time, status, options = {}) {
366
371
  let totalWeight = 0;
367
372
  for (const o of rows) {
368
373
  totalWeight += o.weight;
369
- if (!Number.isSafeInteger(totalWeight)) {
370
- throw new RangeError("total case weight per group must be a safe integer");
371
- }
372
374
  }
373
375
  nRisk = totalWeight;
374
376
  nUnweighted = rows.length;
@@ -396,8 +398,6 @@ export function survfit(time, status, options = {}) {
396
398
  nRisk = active.reduce((sum, o) => sum + o.weight, 0);
397
399
  nUnweighted = active.length;
398
400
  uwRisk = nUnweighted;
399
- if (!Number.isSafeInteger(nRisk))
400
- throw new RangeError("total case weight at risk must be a safe integer");
401
401
  }
402
402
  const eventRowsAtTime = atTime.filter(o => o.event);
403
403
  const censorRows = atTime.filter(o => !o.event && (allRowsById === undefined ||
@@ -430,9 +430,13 @@ export function survfit(time, status, options = {}) {
430
430
  }
431
431
  H += inc;
432
432
  varH += incVar;
433
+ // (d / n) / (n - d): n (n - d) under- or overflows for weights near 1e-200 or 1e200
434
+ // every row still at risk has its event: the fraction is 1 exactly (sums of non-integer weights round, and
435
+ // d / nRisk could otherwise come out just above or below 1)
436
+ const frac = e === uwRisk && uwRisk > 0 ? 1 : d / nRisk;
433
437
  if (stype === 1) {
434
- S *= 1 - d / nRisk;
435
- green += d < nRisk ? d / (nRisk * (nRisk - d)) : Infinity;
438
+ S *= 1 - frac;
439
+ green += frac < 1 ? (d / nRisk) / (nRisk - d) : Infinity;
436
440
  }
437
441
  else
438
442
  S = Math.exp(-H);
@@ -0,0 +1,77 @@
1
+ import { type GlmOptions, type GlmResult } from "./glm.js";
2
+ import type { MatrixInput } from "../linalg/matrix.js";
3
+ import type { Sample } from "../htest/types.js";
4
+ /**
5
+ * Options for {@link svyglm}.
6
+ *
7
+ * @category Generalized linear models
8
+ */
9
+ export interface SvyglmOptions {
10
+ /** The sampling (inverse probability) weights, one per row, positive. */
11
+ weights: Sample;
12
+ /** The family, as {@link glm} (default `"gaussian"`). */
13
+ family?: GlmOptions["family"];
14
+ /** The link, as {@link glm}. */
15
+ link?: GlmOptions["link"];
16
+ /** Convergence tolerance, as {@link glm} (default `1e-8`). */
17
+ epsilon?: number;
18
+ /** Maximum number of iterations, as {@link glm} (default `25`). */
19
+ maxit?: number;
20
+ }
21
+ /**
22
+ * Result of {@link svyglm}: the rows of R's `summary(svyglm(...))$coefficients` and the fit.
23
+ *
24
+ * @category Generalized linear models
25
+ */
26
+ export interface SvyglmResult {
27
+ /** Column names: `"(Intercept)"`, `"x1"`, `"x2"`, ... */
28
+ names: string[];
29
+ /** Coefficients (the weighted glm's). */
30
+ coefficients: number[];
31
+ /** Standard errors, from `vcov`. */
32
+ se: number[];
33
+ /** t statistics. */
34
+ tValue: number[];
35
+ /** Two-sided p-values from the t distribution with `dfResidual` degrees of freedom. */
36
+ pValue: number[];
37
+ /** The design-based variance matrix (array of rows): sandwich HC0 times n / (n - 1). */
38
+ vcov: number[][];
39
+ /** Residual degrees of freedom of the design, n - p. */
40
+ dfResidual: number;
41
+ /** The dispersion R prints: the weighted variance of the Pearson residuals (about their weighted mean) times
42
+ * n / (n - 1); it does not enter the standard errors. */
43
+ dispersion: number;
44
+ /** Deviance with the weights rescaled to mean 1 (R's). */
45
+ deviance: number;
46
+ /** Null deviance with the weights rescaled to mean 1 (R's). */
47
+ nullDeviance: number;
48
+ /** Fitted means. */
49
+ fittedValues: number[];
50
+ /** Linear predictors. */
51
+ linearPredictors: number[];
52
+ /** Iterations of the glm. */
53
+ iter: number;
54
+ /** Whether the glm converged. */
55
+ converged: boolean;
56
+ /** The weighted glm (weights rescaled to mean 1). */
57
+ glm: GlmResult;
58
+ /** R's warnings, each once. */
59
+ warnings: string[];
60
+ }
61
+ /**
62
+ * A generalised linear model for weighted data with design-based (sandwich) standard errors. Equivalent to
63
+ * `survey::svyglm()` in R. The call followed is `summary(svyglm(y ~ ..., design, family))` for the design
64
+ * `svydesign(ids = ~1, weights = ~w, data)`, the design of inverse probability of treatment weighting.
65
+ *
66
+ * The coefficients are those of `glm(y ~ ..., weights = w)`; the variance is the HC0 sandwich of that fit times
67
+ * n / (n − 1), and the tests are t tests on n − p degrees of freedom. binomial and quasibinomial give the same table
68
+ * (binomial warns about the non-integer successes, as R). AIC is not given (R gives NA).
69
+ * @category Generalized linear models
70
+ * @example
71
+ * ```ts
72
+ * const fit = svyglm([[1, 0.2], [0, 1.1], [1, -0.4], [0, 0.3], [1, 0.9], [0, -1.2]], [1, 0, 1, 1, 0, 0],
73
+ * { weights: [1.5, 2, 1.2, 3, 1.1, 2.5], family: "quasibinomial" });
74
+ * fit.pValue; // [0.7799833144017342, 0.5461647344319471, 0.9579412581407588]
75
+ * ```
76
+ */
77
+ export declare function svyglm(x: MatrixInput | Sample, y: Sample, options: SvyglmOptions): SvyglmResult;
@@ -0,0 +1,102 @@
1
+ // survey's svyglm for the design of inverse probability weighting, svydesign(ids = ~1, weights = w): a glm with the
2
+ // weights rescaled to mean 1, the sandwich variance HC0 times n / (n - 1), and t tests on n - p degrees of freedom. The
3
+ // behaviour is in oracle/weightit-behaviour.md, from survey's documentation and published output; Lumley (2010),
4
+ // "Complex Surveys: A Guide to Analysis Using R", chapter 5. Written for rStats.js (no ported code).
5
+ import { glm } from "./glm.js";
6
+ import { vcovHC } from "./sandwich.js";
7
+ import { pt } from "../distributions/t.js";
8
+ import { reported, unreported } from "../internal/warnings.js";
9
+ import { ldexp } from "../internal/summary.js";
10
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
11
+ import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
12
+ const SVYGLM_KEYS = ["weights", "family", "link", "epsilon", "maxit"];
13
+ const SVYGLM_FAMILY_KEYS = ["family", "link", "variance"];
14
+ const SVYGLM_FAMILY_LINK_KEYS = ["power"];
15
+ /**
16
+ * A generalised linear model for weighted data with design-based (sandwich) standard errors. Equivalent to
17
+ * `survey::svyglm()` in R. The call followed is `summary(svyglm(y ~ ..., design, family))` for the design
18
+ * `svydesign(ids = ~1, weights = ~w, data)`, the design of inverse probability of treatment weighting.
19
+ *
20
+ * The coefficients are those of `glm(y ~ ..., weights = w)`; the variance is the HC0 sandwich of that fit times
21
+ * n / (n − 1), and the tests are t tests on n − p degrees of freedom. binomial and quasibinomial give the same table
22
+ * (binomial warns about the non-integer successes, as R). AIC is not given (R gives NA).
23
+ * @category Generalized linear models
24
+ * @example
25
+ * ```ts
26
+ * const fit = svyglm([[1, 0.2], [0, 1.1], [1, -0.4], [0, 0.3], [1, 0.9], [0, -1.2]], [1, 0, 1, 1, 0, 0],
27
+ * { weights: [1.5, 2, 1.2, 3, 1.1, 2.5], family: "quasibinomial" });
28
+ * fit.pValue; // [0.7799833144017342, 0.5461647344319471, 0.9579412581407588]
29
+ * ```
30
+ */
31
+ export function svyglm(x, y, options) {
32
+ checkOptions(options, SVYGLM_KEYS, "svyglm"); // generated: option-keys.mjs
33
+ checkOptions(nestedOptions(options, "family"), SVYGLM_FAMILY_KEYS, "svyglm", "family"); // generated: option-keys.mjs
34
+ checkOptions(nestedOptions(options, "family.link"), SVYGLM_FAMILY_LINK_KEYS, "svyglm", "family.link"); // generated: option-keys.mjs
35
+ checkOptions(nestedOptions(options, "link"), SVYGLM_FAMILY_LINK_KEYS, "svyglm", "link"); // generated: option-keys.mjs
36
+ const { weights, family, link, epsilon, maxit } = options;
37
+ if (weights === undefined)
38
+ throw new RangeError("'weights' must be given");
39
+ const w = Array.from(weights);
40
+ if (w.length !== y.length)
41
+ throw new RangeError("'weights' must have the length of 'y'");
42
+ if (w.some((v) => !(v > 0) || !Number.isFinite(v)))
43
+ throw new RangeError("'weights' must be positive and finite");
44
+ if (family === "quasi" || (typeof family === "object" && family !== null && family.family === "quasi")) {
45
+ throw new RangeError("the quasi family is not available in svyglm (its variance function is not known here)");
46
+ }
47
+ const n = w.length;
48
+ const mean = w.reduce((a, v) => a + v, 0) / n;
49
+ // survey rescales the weights to mean 1: the deviance and glm's convergence test (|change| / (|dev| + 0.1)) are then R's
50
+ const scaled = w.map((v) => v / mean);
51
+ const fit = unreported(() => glm(x, y, {
52
+ weights: scaled, ...(family === undefined ? {} : { family }), ...(link === undefined ? {} : { link }),
53
+ ...(epsilon === undefined ? {} : { epsilon }), ...(maxit === undefined ? {} : { maxit }),
54
+ }));
55
+ // the variance from a fit on the columns (and a gaussian identity-link response) divided by powers of 2, exactly:
56
+ // a coefficient's variance can be out of range (a column near 1e300 gives about 1e-600) while its standard error is
57
+ // not; the scaled fit gives the standard errors, t values and p-values, the variance matrix is mapped back
58
+ const rows = Array.isArray(x[0]) || ArrayBuffer.isView(x[0]) ? x.map((r) => Array.from(r))
59
+ : Array.from(x, (v) => [v]);
60
+ const exponent = (vals) => {
61
+ let top = 0;
62
+ for (let i = 0; i < vals.length; i++)
63
+ if (Number.isFinite(vals[i]) && Math.abs(vals[i]) > top)
64
+ top = Math.abs(vals[i]);
65
+ return top > 0 ? Math.floor(Math.log2(top)) : 0;
66
+ };
67
+ const ex = (rows[0] ?? []).map((_, j) => exponent(rows.map((r) => r[j])));
68
+ const fam = typeof family === "object" && family !== null ? family.family : family ?? "gaussian";
69
+ const identity = fam === "gaussian" && (link === undefined || link === "identity") &&
70
+ (typeof family !== "object" || family === null || family.link === undefined || family.link === "identity");
71
+ const ey = identity ? exponent(y) : 0;
72
+ const scaledFit = ex.every((e) => e === 0) && ey === 0 ? fit : unreported(() => glm(rows.map((r) => r.map((v, j) => ldexp(v, -ex[j]))), Array.from(y, (v) => ldexp(v, -ey)), { weights: scaled, ...(family === undefined ? {} : { family }), ...(link === undefined ? {} : { link }),
73
+ ...(epsilon === undefined ? {} : { epsilon }), ...(maxit === undefined ? {} : { maxit }) }));
74
+ const hc0 = unreported(() => vcovHC(scaledFit, { type: "HC0" })).vcov;
75
+ // the exponent of each coefficient: 2^(ey - e_j), the intercept's 2^ey
76
+ const ec = [...(fit.coefficients.length > ex.length ? [ey] : []), ...ex.map((e) => ey - e)];
77
+ const vcov = hc0.map((row, j) => row.map((v, k) => ldexp((v * n) / (n - 1), ec[j] + ec[k])));
78
+ const p = fit.coefficients.length;
79
+ const dfResidual = n - p;
80
+ const se = hc0.map((row, j) => ldexp(Math.sqrt((row[j] * n) / (n - 1)), ec[j]));
81
+ const tValue = scaledFit.coefficients.map((b, j) => b / Math.sqrt((hc0[j][j] * n) / (n - 1)));
82
+ const pValue = tValue.map((t) => 2 * pt(-Math.abs(t), dfResidual));
83
+ // the dispersion: the design-based variance of the Pearson residuals (y - mu) / sqrt(V(mu)), weighted by the
84
+ // rescaled weights about their weighted mean, times n / (n - 1)
85
+ // from the scaled fit (a gaussian response divided by 2^ey), the result times 2^(2 ey)
86
+ const mu = scaledFit.fittedValues, yy = scaledFit.y;
87
+ const variance = fit.family === "binomial" || fit.family === "quasibinomial" ? (m) => m * (1 - m)
88
+ : fit.family === "poisson" || fit.family === "quasipoisson" ? (m) => m
89
+ : fit.family === "Gamma" ? (m) => m * m : fit.family === "inverse.gaussian" ? (m) => m * m * m : () => 1;
90
+ const pearson = mu.map((m, i) => (yy[i] - m) / Math.sqrt(variance(m)));
91
+ const rbar = pearson.reduce((a, r, i) => a + scaled[i] * r, 0) / n;
92
+ let swr = 0;
93
+ for (let i = 0; i < n; i++)
94
+ swr += scaled[i] * (pearson[i] - rbar) ** 2;
95
+ const dispersion = ldexp((swr / n) * (n / (n - 1)), 2 * ey);
96
+ return reported("svyglm", {
97
+ names: fit.model.columnNames.slice(), coefficients: fit.coefficients.slice(), se, tValue, pValue, vcov, dfResidual,
98
+ dispersion, deviance: fit.deviance, nullDeviance: fit.nullDeviance, fittedValues: fit.fittedValues.slice(),
99
+ linearPredictors: fit.linearPredictors.slice(), iter: fit.iter, converged: fit.converged, glm: fit,
100
+ warnings: fit.warnings.slice(),
101
+ });
102
+ }