|
| 1 | +# SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | +"""Meta-analysis composites: pool a set of estimates, and move between scales. |
| 3 | +
|
| 4 | +Parity with rmorie's `morie_meta_pool`, `morie_meta_effect_sizes` and |
| 5 | +`morie_meta_convert` (R/ca_crim_native.R). |
| 6 | +
|
| 7 | +The arithmetic already lives in `morie.fn._ca_crim` as separate |
| 8 | +primitives -- inverse-variance weights, Q, I-squared, the |
| 9 | +DerSimonian-Laird tau-squared, and the effect-size conversions. What was |
| 10 | +missing is the composite surface that does a whole pooling in one call, |
| 11 | +which is how the R side is used, so this module composes them rather |
| 12 | +than restating the formulas. |
| 13 | +
|
| 14 | +Why both a fixed and a random-effects answer come back together: the |
| 15 | +fixed-effect weights assume every study estimates the same quantity, and |
| 16 | +I-squared is the evidence about whether that holds. Reporting the pooled |
| 17 | +mean without the heterogeneity beside it is the standard way to overstate |
| 18 | +a meta-analysis. |
| 19 | +""" |
| 20 | + |
| 21 | +from __future__ import annotations |
| 22 | + |
| 23 | +import math |
| 24 | + |
| 25 | +from morie.fn import _ca_crim as _cc |
| 26 | + |
| 27 | +__all__ = ["meta_pool", "meta_effect_sizes", "meta_convert"] |
| 28 | + |
| 29 | + |
| 30 | +def _num(x, what): |
| 31 | + try: |
| 32 | + v = [float(i) for i in x] |
| 33 | + except TypeError: |
| 34 | + v = [float(x)] |
| 35 | + if not v: |
| 36 | + raise ValueError("`%s` must not be empty" % what) |
| 37 | + for i in v: |
| 38 | + if i != i: |
| 39 | + raise ValueError("`%s` must not contain missing values" % what) |
| 40 | + return v |
| 41 | + |
| 42 | + |
| 43 | +def meta_pool(ys, ses, z_cv: float = 1.96, groups=None) -> dict: |
| 44 | + """Pool estimates by inverse variance, with the heterogeneity beside it. |
| 45 | +
|
| 46 | + Returns the fixed-effect mean and its interval, Cochran's Q, I-squared, |
| 47 | + the DerSimonian-Laird tau-squared and the random-effects weights that |
| 48 | + follow from it. With `groups`, Q is split into within and between |
| 49 | + components, which is how a subgroup claim is actually tested. |
| 50 | + """ |
| 51 | + y = _num(ys, "ys") |
| 52 | + s = _num(ses, "ses") |
| 53 | + if len(y) != len(s): |
| 54 | + raise ValueError("`ys` and `ses` must be the same length") |
| 55 | + if any(i <= 0 for i in s): |
| 56 | + raise ValueError("`ses` must be strictly positive") |
| 57 | + |
| 58 | + w = [_cc.fixed_effect_weight(i) for i in s] |
| 59 | + # The primitives return records, not bare numbers: mean_effect_size |
| 60 | + # already carries the standard error and z, and q_statistic carries |
| 61 | + # its own df. Take those rather than recomputing them here, so there |
| 62 | + # is one definition of each quantity. |
| 63 | + fe = _cc.mean_effect_size(y, w) |
| 64 | + m = fe["mean"] |
| 65 | + se_m = fe["se"] |
| 66 | + qs = _cc.q_statistic(y, w) |
| 67 | + q = qs["q"] |
| 68 | + df = qs["df"] |
| 69 | + tau2 = _cc.tau2_dersimonian_laird(y, w) |
| 70 | + out = { |
| 71 | + "weights": w, |
| 72 | + "mean": m, |
| 73 | + "se": se_m, |
| 74 | + "z": fe["z"], |
| 75 | + "ci": (m - z_cv * se_m, m + z_cv * se_m), |
| 76 | + "q": q, |
| 77 | + "df": df, |
| 78 | + "i2": _cc.i_squared(q, df), |
| 79 | + "tau2": tau2, |
| 80 | + "weights_random": [_cc.random_effects_weight(i, tau2) for i in s], |
| 81 | + } |
| 82 | + if groups is not None: |
| 83 | + g = list(groups) |
| 84 | + if len(g) != len(y): |
| 85 | + raise ValueError("`groups` must be the same length as `ys`") |
| 86 | + ys_by, ws_by = [], [] |
| 87 | + for lab in dict.fromkeys(g): # first-seen order |
| 88 | + idx = [i for i, v in enumerate(g) if v == lab] |
| 89 | + ys_by.append([y[i] for i in idx]) |
| 90 | + ws_by.append([w[i] for i in idx]) |
| 91 | + qwb = _cc.q_within_between(ys_by, ws_by) |
| 92 | + out["q_within"] = qwb["q_within"] |
| 93 | + out["q_between"] = qwb["q_between"] |
| 94 | + out["df_within"] = qwb["df_within"] |
| 95 | + out["df_between"] = qwb["df_between"] |
| 96 | + return out |
| 97 | + |
| 98 | + |
| 99 | +def meta_effect_sizes(m1=None, m2=None, s1=None, s2=None, n1=None, n2=None, |
| 100 | + t_value=None, a=None, b=None, c=None, d=None, |
| 101 | + r=None) -> dict: |
| 102 | + """Effect sizes from whatever a paper actually reported. |
| 103 | +
|
| 104 | + Primary studies report means and SDs, or a t statistic, or a 2x2 |
| 105 | + table, or a correlation. Each of those determines an effect size and |
| 106 | + its standard error, and only the ones the arguments support are |
| 107 | + returned -- an absent input yields an absent key rather than a |
| 108 | + fabricated zero. |
| 109 | + """ |
| 110 | + out: dict = {} |
| 111 | + if n1 is not None and n2 is not None: |
| 112 | + n1f, n2f = float(n1), float(n2) |
| 113 | + if s1 is not None and m1 is not None and m2 is not None \ |
| 114 | + and s2 is not None: |
| 115 | + out["s_pooled"] = _cc.pooled_sd(float(s1), float(s2), n1f, n2f) |
| 116 | + out["d"] = _cc.cohens_d_sample(float(m1), float(m2), float(s1), |
| 117 | + float(s2), n1f, n2f) |
| 118 | + out["j"] = _cc.hedges_j(n1f, n2f) |
| 119 | + if "d" in out: |
| 120 | + out["g"] = _cc.hedges_g(out["d"], n1f, n2f) |
| 121 | + out["se_g"] = _cc.se_g(out["g"], n1f, n2f) |
| 122 | + if t_value is not None: |
| 123 | + out["d_from_t"] = _cc.d_from_t(float(t_value), n1f, n2f) |
| 124 | + if a is not None and None not in (b, c, d): |
| 125 | + af, bf, cf, df_ = float(a), float(b), float(c), float(d) |
| 126 | + p1 = af / (af + bf) |
| 127 | + p2 = cf / (cf + df_) |
| 128 | + out["rr"] = _cc.risk_ratio(af, bf, cf, df_) |
| 129 | + out["or"] = _cc.odds_ratio_2x2(af, bf, cf, df_) |
| 130 | + # se_log_rr takes the two risks and the two group sizes, not the |
| 131 | + # four cells |
| 132 | + out["se_ln_rr"] = _cc.se_log_rr(p1, p2, af + bf, cf + df_) |
| 133 | + out["se_ln_or"] = _cc.se_log_or(af, bf, cf, df_) |
| 134 | + if r is not None: |
| 135 | + rf = float(r) |
| 136 | + out["fisher_z"] = _cc.fisher_z(rf) |
| 137 | + if n1 is not None: |
| 138 | + out["se_fisher_z"] = _cc.se_fisher_z(float(n1)) |
| 139 | + return out |
| 140 | + |
| 141 | + |
| 142 | +def meta_convert(ln_or=None, se_ln_or=None, p1=None, p2=None, n1=None, |
| 143 | + n2=None, d=None, se_d=None, rr=None, or_value=None, |
| 144 | + r=None, se_r=None) -> dict: |
| 145 | + """Move an effect between the scales a synthesis has to mix. |
| 146 | +
|
| 147 | + A review rarely gets one scale. Log odds ratios, standardised mean |
| 148 | + differences, probit differences and correlations all convert, and the |
| 149 | + conversion constants are the ones the literature uses: the logistic |
| 150 | + SD (pi/sqrt(3)) for the logit route and Cox's 1.65. |
| 151 | + """ |
| 152 | + sd_logistic = math.sqrt(math.pi ** 2 / 3.0) |
| 153 | + out: dict = {"sd_logistic": sd_logistic} |
| 154 | + if ln_or is not None: |
| 155 | + out["d_logit"] = _cc.d_from_log_or(float(ln_or), method="logit") |
| 156 | + out["d_cox"] = _cc.d_from_log_or(float(ln_or), method="cox") |
| 157 | + if se_ln_or is not None: |
| 158 | + out["se_d_logit"] = math.sqrt(float(se_ln_or) ** 2 / sd_logistic ** 2) |
| 159 | + out["se_d_cox"] = math.sqrt(float(se_ln_or) ** 2 / 1.65 ** 2) |
| 160 | + if p1 is not None and p2 is not None: |
| 161 | + out["d_probit"] = _cc.d_probit(float(p1), float(p2)) |
| 162 | + if n1 is not None and n2 is not None: |
| 163 | + out["se_d_probit"] = _cc.se_d_probit(float(p1), float(p2), |
| 164 | + float(n1), float(n2)) |
| 165 | + if d is not None: |
| 166 | + dv = float(d) |
| 167 | + out["ln_or_logit"] = _cc.log_or_from_d(dv, method="logit") |
| 168 | + out["ln_or_cox"] = _cc.log_or_from_d(dv, method="cox") |
| 169 | + out["r_from_d"] = _cc.r_from_d(dv, float(n1), float(n2)) \ |
| 170 | + if (n1 is not None and n2 is not None) else _cc.r_from_d(dv) |
| 171 | + if se_d is not None: |
| 172 | + out["se_ln_or_logit"] = _cc.se_log_or_from_se_d(float(se_d), |
| 173 | + method="logit") |
| 174 | + if rr is not None and p2 is not None: |
| 175 | + out["or_from_rr"] = _cc.or_from_rr(float(rr), float(p2)) |
| 176 | + if or_value is not None and p2 is not None: |
| 177 | + out["rr_from_or"] = _cc.rr_from_or(float(or_value), float(p2)) |
| 178 | + if r is not None: |
| 179 | + out["fisher_z"] = _cc.fisher_z(float(r)) |
| 180 | + out["d_from_r"] = _cc.d_from_r_pointbiserial(float(r)) |
| 181 | + if se_r is not None: |
| 182 | + out["se_d_from_se_r"] = _cc.se_d_from_se_r(float(r), |
| 183 | + float(se_r)) |
| 184 | + return out |
0 commit comments