@numero-uno-jpn/rstats 1.11.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 (86) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.ja.md +7 -6
  3. package/README.md +7 -6
  4. package/dist/causal/balance.d.ts +118 -0
  5. package/dist/causal/balance.js +264 -0
  6. package/dist/causal/match.d.ts +86 -0
  7. package/dist/causal/match.js +155 -0
  8. package/dist/causal/scale.d.ts +8 -0
  9. package/dist/causal/scale.js +26 -0
  10. package/dist/causal/weightit.d.ts +159 -0
  11. package/dist/causal/weightit.js +491 -0
  12. package/dist/causal.js +2 -0
  13. package/dist/chunks/{chunk-ZW5OCUIY.js → chunk-24UIPUSE.js} +1 -1
  14. package/dist/chunks/{chunk-JD6JHIVV.js → chunk-2BXB6DRK.js} +1 -1
  15. package/dist/chunks/chunk-2N7PIFPJ.js +2 -0
  16. package/dist/chunks/{chunk-IRO6MXW2.js → chunk-2SOBG73L.js} +2 -2
  17. package/dist/chunks/{chunk-PF6LEBKO.js → chunk-3T4TVNXS.js} +2 -2
  18. package/dist/chunks/chunk-5Y425VAJ.js +2 -0
  19. package/dist/chunks/{chunk-3K5KP3M2.js → chunk-7V6FRF32.js} +2 -2
  20. package/dist/chunks/chunk-7ZKPFHAO.js +2 -0
  21. package/dist/chunks/{chunk-MJLK2RIQ.js → chunk-AH6IVJRF.js} +1 -1
  22. package/dist/chunks/{chunk-W27XXELU.js → chunk-C7NEFIAH.js} +2 -2
  23. package/dist/chunks/{chunk-OG5FTIWF.js → chunk-CAOEREY3.js} +2 -2
  24. package/dist/chunks/{chunk-HIPKYBZ3.js → chunk-CBAEKGP7.js} +2 -2
  25. package/dist/chunks/{chunk-6VIOWV53.js → chunk-CCYGRSQW.js} +2 -2
  26. package/dist/chunks/{chunk-46DELNLN.js → chunk-CEY7FHMZ.js} +2 -2
  27. package/dist/chunks/{chunk-Z6UI6ON2.js → chunk-CKQOWTX7.js} +2 -2
  28. package/dist/chunks/chunk-CSZCDPF3.js +2 -0
  29. package/dist/chunks/chunk-DQ2MIFRQ.js +2 -0
  30. package/dist/chunks/{chunk-XLBSUUWY.js → chunk-DZLOU6HK.js} +2 -2
  31. package/dist/chunks/{chunk-S5JZMHAW.js → chunk-EWJS4VYF.js} +2 -2
  32. package/dist/chunks/{chunk-KICTA3JY.js → chunk-GQ4HYF4L.js} +2 -2
  33. package/dist/chunks/chunk-GRXOLZ6J.js +2 -0
  34. package/dist/chunks/{chunk-BA32XHDA.js → chunk-IIKFLH2E.js} +2 -2
  35. package/dist/chunks/{chunk-M4SLTLOX.js → chunk-JJGRQ22M.js} +2 -2
  36. package/dist/chunks/chunk-JTARV4D3.js +2 -0
  37. package/dist/chunks/{chunk-OWOBNS75.js → chunk-KOF2HBUV.js} +2 -2
  38. package/dist/chunks/{chunk-BKH5GQNA.js → chunk-LS55YUPZ.js} +2 -2
  39. package/dist/chunks/chunk-M3LK23YR.js +2 -0
  40. package/dist/chunks/{chunk-BNHMQU7V.js → chunk-NRBTDLVW.js} +2 -2
  41. package/dist/chunks/{chunk-HCHZ6M34.js → chunk-NWWY2WMF.js} +2 -2
  42. package/dist/chunks/{chunk-TNU4SMV3.js → chunk-OVJU5WCL.js} +2 -2
  43. package/dist/chunks/{chunk-WHKUEZQI.js → chunk-OWD2GUXJ.js} +2 -2
  44. package/dist/chunks/{chunk-BZBPPRSH.js → chunk-P2UT6OCU.js} +2 -2
  45. package/dist/chunks/{chunk-XKQSKVCL.js → chunk-P6HSXCGZ.js} +2 -2
  46. package/dist/chunks/{chunk-YPDFCKL4.js → chunk-QWXSJEDI.js} +2 -2
  47. package/dist/chunks/{chunk-QRUQEJJ5.js → chunk-RGEW3YLB.js} +2 -2
  48. package/dist/chunks/{chunk-BGY7Y3P4.js → chunk-ST6I33C6.js} +1 -1
  49. package/dist/chunks/{chunk-W2D6IDBY.js → chunk-TQ4P6W3P.js} +2 -2
  50. package/dist/chunks/chunk-TTBKW2KL.js +2 -0
  51. package/dist/chunks/{chunk-EV7ZQC6D.js → chunk-UMLJFZJ5.js} +2 -2
  52. package/dist/chunks/{chunk-NO675KX4.js → chunk-VO65CBCV.js} +2 -2
  53. package/dist/chunks/{chunk-DMT423BG.js → chunk-XRB552MP.js} +2 -2
  54. package/dist/chunks/{chunk-JFZOKMZA.js → chunk-XRBNTYQW.js} +2 -2
  55. package/dist/chunks/{chunk-Y2SS3GX2.js → chunk-Y4UWFH4Q.js} +2 -2
  56. package/dist/descriptive.js +2 -2
  57. package/dist/distributions.js +2 -2
  58. package/dist/entries/causal.d.ts +3 -0
  59. package/dist/entries/causal.js +4 -0
  60. package/dist/entries/tests.d.ts +3 -0
  61. package/dist/entries/tests.js +3 -0
  62. package/dist/linalg.js +2 -2
  63. package/dist/mixed.js +2 -2
  64. package/dist/models/clogit.d.ts +80 -0
  65. package/dist/models/clogit.js +211 -0
  66. package/dist/models/coxph.d.ts +9 -0
  67. package/dist/models/coxph.js +3 -3
  68. package/dist/models/survfitCoxph.d.ts +95 -0
  69. package/dist/models/survfitCoxph.js +223 -0
  70. package/dist/models/survival.d.ts +9 -2
  71. package/dist/models/survival.js +15 -11
  72. package/dist/models/svyglm.d.ts +77 -0
  73. package/dist/models/svyglm.js +102 -0
  74. package/dist/multivariate.js +2 -2
  75. package/dist/numerics.js +2 -2
  76. package/dist/regression.js +2 -2
  77. package/dist/rstats.js +18 -18
  78. package/dist/special.js +2 -2
  79. package/dist/tests.js +15 -15
  80. package/dist/timeseries.js +2 -2
  81. package/package.json +6 -1
  82. package/dist/chunks/chunk-HPWRADJM.js +0 -2
  83. package/dist/chunks/chunk-JWMVP7XO.js +0 -2
  84. package/dist/chunks/chunk-P23KCD67.js +0 -2
  85. package/dist/chunks/chunk-QY4OBLXK.js +0 -2
  86. package/dist/chunks/chunk-SV6SLUVB.js +0 -2
@@ -0,0 +1,86 @@
1
+ /** The population the matching estimates for: the treated (ATT), everyone (ATE) or the controls (ATC).
2
+ * @category Causal inference
3
+ */
4
+ export type MatchEstimand = "ATT" | "ATE" | "ATC";
5
+ /** Options of {@link match}. Equivalent to the arguments of the Matching package's `Match()` with `ties = FALSE` and
6
+ * `replace = FALSE`.
7
+ * @category Causal inference
8
+ */
9
+ export interface MatchOptions {
10
+ /** The estimand (default `"ATT"`): the treated units are matched (ATT), the controls (ATC), or both (ATE). */
11
+ estimand?: MatchEstimand;
12
+ /** The number of matches for each matched unit (default 1), a positive integer. */
13
+ M?: number;
14
+ /**
15
+ * The caliper in standard deviations of `x` (the SD with divisor n over all units, as R's `ecaliper`): a match
16
+ * farther than `caliper * sd` is not made, and a unit with fewer than `M` controls within it is dropped.
17
+ */
18
+ caliper?: number;
19
+ }
20
+ /** Result of {@link match}. The fields are those of R's `Match` object, with 1-based row numbers.
21
+ * @category Causal inference
22
+ */
23
+ export interface MatchResult {
24
+ /** Rows (1-based) of the treated unit of each pair. */
25
+ indexTreated: number[];
26
+ /** Rows (1-based) of the control unit of each pair. */
27
+ indexControl: number[];
28
+ /** Weight of each pair: `1 / M`. */
29
+ weights: number[];
30
+ /**
31
+ * Rows (1-based) of the dropped units that appear in no pair (R's `index.dropped`), only when a caliper is given;
32
+ * `null` otherwise or when none. Under ATE a dropped unit can still be another unit's match and is then not listed.
33
+ * Without a caliper R lists none even when units are dropped (`ndrops` counts them).
34
+ */
35
+ indexDropped: number[] | null;
36
+ /** The caliper as given (in standard deviations), `null` without one. */
37
+ caliper: number | null;
38
+ /** The caliper on the scale of `x` (R's `ecaliper`), `null` without one. */
39
+ ecaliper: number | null;
40
+ /** Number of units (R's `nobs`). */
41
+ nobs: number;
42
+ /** Number of matched units (R's `wnobs`: units that found their matches). */
43
+ wnobs: number;
44
+ /** Number of matched-for units left without matches, for either reason (R's `ndrops`). */
45
+ ndrops: number;
46
+ /** The estimand. */
47
+ estimand: MatchEstimand;
48
+ /** The number of matches per matched unit. */
49
+ M: number;
50
+ /**
51
+ * Size of each candidate set from which matches were drawn at random (more candidates than needed at equal
52
+ * distance), in the order of the draws. Empty when there were no ties; the pairs are then R's. With sets of 2 only
53
+ * the pairs and the random numbers used are also R's; larger sets are broken by rStats.js's own rule (see
54
+ * {@link match}).
55
+ */
56
+ tieSizes: number[];
57
+ /** Warnings (R's, e.g. when no unit could be matched). */
58
+ warnings: string[];
59
+ }
60
+ /**
61
+ * Nearest-neighbour matching on a scalar score, without replacement and with random tie-breaking. Equivalent to
62
+ * `Matching::Match()` in R. The call followed is
63
+ * `Match(Tr = tr, X = x, estimand, M, caliper, ties = FALSE, replace = FALSE)`, used with the linear predictor
64
+ * `logit(PS)` of a propensity score model.
65
+ *
66
+ * The matched units (the treated for ATT, the controls for ATC, all for ATE) are processed in data order. Each takes
67
+ * its matches from the units of the other group not yet used: every available unit within the M-th smallest distance
68
+ * is a candidate (within the caliper when one is given), and when there are more candidates than M, M of them are
69
+ * drawn at random. A unit with fewer than M available candidates is dropped. Pairs are listed in the order of the
70
+ * matched units, the controls of one treated unit (ATT) in row order.
71
+ *
72
+ * Random draws use rStats.js's generator (`setSeed`): one uniform `u` for each pick, and the candidate at 0-based
73
+ * index `floor(k (1 - u))` among the `k` remaining (in row order) is taken. Without ties no random number is used and
74
+ * the pairs are R's; with sets of two candidates the rule is R's (the second when `u < 0.5`). Known differences from
75
+ * R: larger tie sets are broken differently (R's rule is not documented), and distances count as tied only when
76
+ * exactly equal (R also treats distances within `distance.tolerance = 1e-5` as ties). `M` below 1 is an error (R
77
+ * warns and uses 1).
78
+ * @category Causal inference
79
+ * @example
80
+ * ```ts
81
+ * const m = match([1, 0, 1, 0, 0], [0.2, 0.1, 1.5, 1.4, 3]);
82
+ * m.indexTreated; // [1, 3]
83
+ * m.indexControl; // [2, 4]
84
+ * ```
85
+ */
86
+ export declare function match(tr: readonly (number | boolean)[], x: readonly number[], options?: MatchOptions): MatchResult;
@@ -0,0 +1,155 @@
1
+ // Nearest-neighbour matching on a scalar score without replacement, after the Matching package's Match(Tr, X,
2
+ // estimand, M, caliper, ties = FALSE, replace = FALSE): the behaviour and the choices are in oracle/match-behaviour.md.
3
+ // Written for rStats.js from the package's documentation and its published output (no ported code).
4
+ import { unifRand } from "../random/rng.js";
5
+ import { ldexp } from "../internal/summary.js";
6
+ import { rescaled } from "./scale.js";
7
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
8
+ import { checkOptions } from "../internal/checkOptions.js";
9
+ const MATCH_KEYS = ["estimand", "M", "caliper"];
10
+ /**
11
+ * Nearest-neighbour matching on a scalar score, without replacement and with random tie-breaking. Equivalent to
12
+ * `Matching::Match()` in R. The call followed is
13
+ * `Match(Tr = tr, X = x, estimand, M, caliper, ties = FALSE, replace = FALSE)`, used with the linear predictor
14
+ * `logit(PS)` of a propensity score model.
15
+ *
16
+ * The matched units (the treated for ATT, the controls for ATC, all for ATE) are processed in data order. Each takes
17
+ * its matches from the units of the other group not yet used: every available unit within the M-th smallest distance
18
+ * is a candidate (within the caliper when one is given), and when there are more candidates than M, M of them are
19
+ * drawn at random. A unit with fewer than M available candidates is dropped. Pairs are listed in the order of the
20
+ * matched units, the controls of one treated unit (ATT) in row order.
21
+ *
22
+ * Random draws use rStats.js's generator (`setSeed`): one uniform `u` for each pick, and the candidate at 0-based
23
+ * index `floor(k (1 - u))` among the `k` remaining (in row order) is taken. Without ties no random number is used and
24
+ * the pairs are R's; with sets of two candidates the rule is R's (the second when `u < 0.5`). Known differences from
25
+ * R: larger tie sets are broken differently (R's rule is not documented), and distances count as tied only when
26
+ * exactly equal (R also treats distances within `distance.tolerance = 1e-5` as ties). `M` below 1 is an error (R
27
+ * warns and uses 1).
28
+ * @category Causal inference
29
+ * @example
30
+ * ```ts
31
+ * const m = match([1, 0, 1, 0, 0], [0.2, 0.1, 1.5, 1.4, 3]);
32
+ * m.indexTreated; // [1, 3]
33
+ * m.indexControl; // [2, 4]
34
+ * ```
35
+ */
36
+ export function match(tr, x, options = {}) {
37
+ checkOptions(options, MATCH_KEYS, "match"); // generated: option-keys.mjs
38
+ const { estimand = "ATT", M = 1, caliper } = options;
39
+ const n = tr.length;
40
+ if (x.length !== n)
41
+ throw new RangeError("length(Tr) != nrow(X)");
42
+ if (estimand !== "ATT" && estimand !== "ATE" && estimand !== "ATC")
43
+ throw new RangeError(`invalid 'estimand': ${String(estimand)}`);
44
+ if (!Number.isInteger(M) || M < 1)
45
+ throw new RangeError("'M' must be a positive integer");
46
+ if (caliper !== undefined && !(caliper > 0 && Number.isFinite(caliper)))
47
+ throw new RangeError("'caliper' must be a positive number");
48
+ const treated = [];
49
+ for (let i = 0; i < n; i++) {
50
+ const t = tr[i];
51
+ if (t === true || t === 1)
52
+ treated.push(true);
53
+ else if (t === false || t === 0)
54
+ treated.push(false);
55
+ else if (typeof t === "number" && Number.isNaN(t))
56
+ throw new RangeError("Match(): input includes NAs");
57
+ else
58
+ throw new RangeError("Treatment indicator ('Tr') must be a logical variable---i.e., TRUE (1) or FALSE (0)");
59
+ if (!Number.isFinite(x[i]))
60
+ throw new RangeError("Match(): input includes NAs");
61
+ }
62
+ if (!treated.includes(true) || !treated.includes(false)) {
63
+ throw new RangeError("Treatment indicator ('Tr') must contain both treatment and control observations");
64
+ }
65
+ // distances and the caliper in units of 2^e, the power of 2 of the largest |x|: exact (the ties stay ties), and
66
+ // neither overflowing for |x| near 1e308 nor underflowing for |x| near 1e-300
67
+ let top = 0;
68
+ for (const v of x)
69
+ top = Math.max(top, Math.abs(v));
70
+ const unitExp = top > 0 ? Math.floor(Math.log2(top)) : 0;
71
+ const xs = x.map((v) => ldexp(v, -unitExp));
72
+ let ecaliper = null;
73
+ let reach = Infinity; // the caliper in the units of xs
74
+ if (caliper !== undefined) {
75
+ // the SD with divisor n, from the column rescaled exactly (and shifted: a large common offset keeps its digits)
76
+ const { values: r, unitExp: rExp } = rescaled(xs);
77
+ let mean = 0;
78
+ for (const v of r)
79
+ mean += v;
80
+ mean /= n;
81
+ let ss = 0;
82
+ for (const v of r)
83
+ ss += (v - mean) * (v - mean);
84
+ const sd = ldexp(Math.sqrt(ss / n), rExp); // in the units of xs
85
+ reach = caliper * sd;
86
+ ecaliper = ldexp(reach, unitExp);
87
+ }
88
+ // separate pools: the controls still available to treated units, the treated still available to controls
89
+ const used = [new Array(n).fill(false), new Array(n).fill(false)]; // [for treated, for controls]
90
+ const indexTreated = [];
91
+ const indexControl = [];
92
+ const dropped = [];
93
+ const tieSizes = [];
94
+ let wnobs = 0;
95
+ let ndrops = 0;
96
+ for (let i = 0; i < n; i++) {
97
+ const isT = treated[i];
98
+ if (isT ? estimand === "ATC" : estimand === "ATT")
99
+ continue;
100
+ const pool = used[isT ? 0 : 1];
101
+ // available units of the other group within the caliper, with their distances
102
+ const cand = [];
103
+ for (let j = 0; j < n; j++) {
104
+ if (treated[j] === isT)
105
+ continue;
106
+ const d = Math.abs(xs[i] - xs[j]);
107
+ if (d > reach)
108
+ continue;
109
+ if (!pool[j])
110
+ cand.push({ j, d });
111
+ }
112
+ if (cand.length < M) {
113
+ ndrops++;
114
+ dropped.push(i + 1);
115
+ continue;
116
+ }
117
+ // the M-th smallest distance; every candidate within it
118
+ const sorted = cand.map((c) => c.d).sort((a, b) => a - b);
119
+ const dM = sorted[M - 1];
120
+ let set = cand.filter((c) => c.d <= dM).map((c) => c.j); // row order
121
+ let chosen;
122
+ if (set.length === M)
123
+ chosen = set;
124
+ else {
125
+ tieSizes.push(set.length);
126
+ chosen = [];
127
+ set = set.slice();
128
+ for (let p = 0; p < M; p++) {
129
+ const k = set.length;
130
+ const idx = Math.min(k - 1, Math.floor(k * (1 - unifRand())));
131
+ chosen.push(set[idx]);
132
+ set.splice(idx, 1);
133
+ }
134
+ chosen.sort((a, b) => a - b);
135
+ }
136
+ for (const j of chosen) {
137
+ pool[j] = true;
138
+ indexTreated.push((isT ? i : j) + 1);
139
+ indexControl.push((isT ? j : i) + 1);
140
+ }
141
+ wnobs++;
142
+ }
143
+ // R lists (with a caliper) the dropped units that appear in no pair: under ATE a dropped unit may still be the match
144
+ // of another unit
145
+ const inPairs = new Set([...indexTreated, ...indexControl]);
146
+ const listed = ecaliper === null ? [] : dropped.filter((r) => !inPairs.has(r));
147
+ const warnings = [];
148
+ if (indexTreated.length === 0) {
149
+ warnings.push("'Match' object contains no valid matches (probably because of the caliper or the exact option).");
150
+ }
151
+ return {
152
+ indexTreated, indexControl, weights: indexTreated.map(() => 1 / M), indexDropped: listed.length > 0 ? listed : null,
153
+ caliper: caliper ?? null, ecaliper, nobs: n, wnobs, ndrops, estimand, M, tieSizes, warnings,
154
+ };
155
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The column as `(v 2^-e1 - first) 2^-e2`, and the exponent e1 + e2 back to the original units (of spreads, not of
3
+ * locations: a spread s of the result is s 2^(e1 + e2)). A constant column comes back as zeros.
4
+ */
5
+ export declare function rescaled(values: readonly number[]): {
6
+ values: number[];
7
+ unitExp: number;
8
+ };
@@ -0,0 +1,26 @@
1
+ // Exact rescaling of a column before its moments: by a power of 2 (no rounding) so that its largest magnitude is near
2
+ // 1, then shifted by its first value (exact for nearby values, Sterbenz) and rescaled again. Standardised differences
3
+ // and variance ratios do not change under v -> (v - a) c, c > 0, while the sums of squares then neither overflow
4
+ // (values near 1e300) nor underflow (near 1e-300) nor lose the digits a large common offset (1e15 + small
5
+ // differences) takes from them. Written for rStats.js.
6
+ import { ldexp } from "../internal/summary.js";
7
+ /** The largest finite magnitude's power of 2 (0 for an all-zero column). */
8
+ function exponentOf(values) {
9
+ let top = 0;
10
+ for (const v of values)
11
+ if (Math.abs(v) > top)
12
+ top = Math.abs(v);
13
+ return top > 0 && Number.isFinite(top) ? Math.floor(Math.log2(top)) : 0;
14
+ }
15
+ /**
16
+ * The column as `(v 2^-e1 - first) 2^-e2`, and the exponent e1 + e2 back to the original units (of spreads, not of
17
+ * locations: a spread s of the result is s 2^(e1 + e2)). A constant column comes back as zeros.
18
+ */
19
+ export function rescaled(values) {
20
+ const e1 = exponentOf(values);
21
+ const scaled = values.map((v) => ldexp(v, -e1));
22
+ const first = scaled[0] ?? 0;
23
+ const shifted = scaled.map((v) => v - first);
24
+ const e2 = exponentOf(shifted);
25
+ return { values: shifted.map((v) => ldexp(v, -e2)), unitExp: e1 + e2 };
26
+ }
@@ -0,0 +1,159 @@
1
+ /** The estimand of {@link weightit}: the population whose average treatment effect the weights target.
2
+ * @category Causal inference
3
+ */
4
+ export type WeightitEstimand = "ATE" | "ATT" | "ATC" | "ATO";
5
+ /** The method of {@link weightit} (WeightIt's `method`; `"ps"` is an alias of `"glm"`).
6
+ * @category Causal inference
7
+ */
8
+ export type WeightitMethod = "glm" | "ps" | "cbps" | "ipt" | "ebal";
9
+ /** Options of {@link weightit}. Equivalent to the arguments of WeightIt's `weightit()`.
10
+ * @category Causal inference
11
+ */
12
+ export interface WeightitOptions {
13
+ /** How the weights are estimated (default `"glm"`): see {@link weightit}. */
14
+ method?: WeightitMethod;
15
+ /** The link of the propensity score model: `"logit"` (default), `"probit"`, `"cauchit"` or `"cloglog"` for glm,
16
+ * `"logit"` or `"probit"` for cbps, `"logit"` for ipt; ebal has none. */
17
+ link?: "logit" | "probit" | "cauchit" | "cloglog";
18
+ /** The estimand (default `"ATE"`). ipt and ebal do not allow `"ATO"`. */
19
+ estimand?: WeightitEstimand;
20
+ /** Multiply the weights by the share of the unit's group in the sample (glm with ATE only; ignored with a warning
21
+ * by the other methods, an error with another estimand, as R). Default false. */
22
+ stabilize?: boolean;
23
+ }
24
+ /** Result of {@link weightit}.
25
+ * @category Causal inference
26
+ */
27
+ export interface WeightitResult {
28
+ /** The weights, one per unit, in the order of `tr`. */
29
+ weights: number[];
30
+ /** The propensity scores (null for ebal, which has none): for ipt the score of the tilting that weights the unit's
31
+ * group (ATE), or of the weighted group for all units (ATT: the controls' tilting; ATC: the treated's). */
32
+ ps: number[] | null;
33
+ /** The treatment, 0 or 1 per unit. */
34
+ treat: number[];
35
+ /** The estimand. */
36
+ estimand: WeightitEstimand;
37
+ /** The method as R reports it (`"glm"` for `"ps"`). */
38
+ method: "glm" | "cbps" | "ipt" | "ebal";
39
+ /** The link (null for ebal). */
40
+ link: string | null;
41
+ /** Whether the weights were stabilised. */
42
+ stabilized: boolean;
43
+ /** The focal group of ATT (`1`) and ATC (`0`), null otherwise: its weights are 1. */
44
+ focal: 0 | 1 | null;
45
+ /** The columns of the model matrix after the intercept: the numeric covariates and, for a string covariate, one 0/1
46
+ * column per level after the first (R's treatment contrasts, levels in code-point order). */
47
+ columnNames: string[];
48
+ /** Whether the estimation converged (the glm, or the solution of the balance conditions). */
49
+ converged: boolean;
50
+ /** R's warnings, each once. */
51
+ warnings: string[];
52
+ }
53
+ /** A covariate: numbers, or strings (a factor with its levels in code-point order).
54
+ * @category Causal inference
55
+ */
56
+ export type CovariateColumn = readonly number[] | readonly string[];
57
+ /** The model matrix without its intercept: one column per numeric covariate, k - 1 indicator columns per factor */
58
+ export declare function covariateColumns(covariates: Readonly<Record<string, CovariateColumn>>, n: number): {
59
+ names: string[];
60
+ columns: number[][];
61
+ factors: Record<string, string[]>;
62
+ };
63
+ /**
64
+ * Balancing weights for a binary treatment. Equivalent to `WeightIt::weightit()` in R. The call followed is
65
+ * `weightit(tr ~ covariates, data, method, link, estimand, stabilize)`.
66
+ *
67
+ * - `"glm"` (`"ps"`): the propensity score `p` of a binomial glm with the link, and the weights 1/p and 1/(1 − p)
68
+ * (ATE), 1 and p/(1 − p) (ATT), (1 − p)/p and 1 (ATC), 1 − p and p (ATO, the overlap weights).
69
+ * - `"cbps"`: the just-identified covariate balancing propensity score: the score whose weights (the same formulas)
70
+ * make the weighted means of every covariate column equal in the two groups (ATT: the controls' to the treated's).
71
+ * - `"ipt"`: inverse probability tilting, a logistic score per weighted group whose weights move the group's means to
72
+ * the target (ATE: the whole sample's). Not ATO.
73
+ * - `"ebal"`: entropy balancing: the weights closest to uniform in entropy with the target means, summing to the
74
+ * target size. No propensity score; not ATO.
75
+ *
76
+ * cbps, ipt and ebal are solved exactly (Newton's method on the balance conditions); R stops its optimisers earlier, so
77
+ * those weights agree with R's to about 1e-8 relative. A string covariate is a factor (levels in code-point order);
78
+ * missing values are an error (R drops or imputes them depending on the method).
79
+ * @category Causal inference
80
+ * @example
81
+ * ```ts
82
+ * const tr = [1, 0, 1, 0, 0, 1, 0, 0, 1, 0];
83
+ * const age = [52, 40, 61, 58, 33, 47, 50, 45, 39, 44];
84
+ * const w = weightit(tr, { age }, { estimand: "ATE" });
85
+ * w.ps[0]; // 0.48529828581084455
86
+ * w.weights[0]; // 2.0605883623289194 (1 / ps for a treated unit)
87
+ * ```
88
+ */
89
+ export declare function weightit(tr: readonly (number | boolean)[], covariates: Readonly<Record<string, CovariateColumn>>, options?: WeightitOptions): WeightitResult;
90
+ /** Options of {@link trimWeights}. Equivalent to the arguments of WeightIt's `trim()`.
91
+ * @category Causal inference
92
+ */
93
+ export interface TrimWeightsOptions {
94
+ /** Below 1: the quantile (type 3) of the weights at which they are capped (0.99 caps the top 1%; below 0.5 it is
95
+ * read as 1 − `at`, as R); 1 or more: the number of largest weights set to the next largest (above half the units it
96
+ * is read as the number of units less `at`; as many as the units or more: no trimming, with R's warning). */
97
+ at: number;
98
+ /** Also raise the weights below the quantile 1 − `at` (or the `at` smallest) to it. Default false. */
99
+ lower?: boolean;
100
+ /** For a plain vector of weights: the treatment (only informative with a focal group, which a vector has not). */
101
+ treat?: readonly (number | boolean)[];
102
+ }
103
+ /**
104
+ * Trims (winsorises) extreme weights: those above a quantile, and with `lower` those below the opposite one, are set to
105
+ * it. Equivalent to `WeightIt::trim()` in R. The call followed is `trim(w, at, lower = TRUE)` for a weightit result or a
106
+ * vector of weights.
107
+ *
108
+ * The quantile is R's type 3 of the weights that are not fixed by the estimand: all units for ATE and ATO, the controls
109
+ * for ATT, the treated for ATC. The other weights do not change (no renormalisation). For a weightit result the
110
+ * returned object is a copy with the trimmed weights.
111
+ * @category Causal inference
112
+ */
113
+ export declare function trimWeights(w: WeightitResult, options: TrimWeightsOptions): WeightitResult;
114
+ export declare function trimWeights(w: readonly number[], options: TrimWeightsOptions): number[];
115
+ /** One group's part of {@link weightSummary}.
116
+ * @category Causal inference
117
+ */
118
+ export interface WeightSummaryGroup {
119
+ /** Smallest and largest weight. */
120
+ range: [number, number];
121
+ /** The (up to) 5 largest weights in increasing order; among equal weights the earliest units, as R lists them. */
122
+ top: {
123
+ /** The units (1-based). */
124
+ index: number[];
125
+ /** Their weights. */
126
+ weights: number[];
127
+ };
128
+ /** Mean weight (R prints it for stabilised weights only). */
129
+ mean: number;
130
+ /** Coefficient of variation: SD (divisor n − 1) / mean. */
131
+ coefOfVar: number;
132
+ /** Mean absolute deviation of w / mean(w) from 1. */
133
+ scaledMad: number;
134
+ /** Mean of r log r, r = w / mean(w). */
135
+ negativeEntropy: number;
136
+ /** Number of zero weights (below 1e-10, as R counts them). */
137
+ numZeros: number;
138
+ /** Number of units. */
139
+ n: number;
140
+ /** Kish's effective sample size (sum w)² / sum w². */
141
+ ess: number;
142
+ }
143
+ /** Result of {@link weightSummary}.
144
+ * @category Causal inference
145
+ */
146
+ export interface WeightSummaryResult {
147
+ /** The treated group's summary. */
148
+ treated: WeightSummaryGroup;
149
+ /** The control group's summary. */
150
+ control: WeightSummaryGroup;
151
+ /** Whether the weights were stabilised (R shows the mean weights then). */
152
+ stabilized: boolean;
153
+ }
154
+ /**
155
+ * Summary of balancing weights by group: range, largest weights, coefficient of variation, scaled MAD, negative
156
+ * entropy, zeros and Kish's effective sample size. Equivalent to `WeightIt::summary.weightit()` in R.
157
+ * @category Causal inference
158
+ */
159
+ export declare function weightSummary(w: WeightitResult): WeightSummaryResult;