BMeta-analysis · meta.sensitivity
Sensitivity displays — study subsets (GOSH) and p-value functions (drapery)
Does the pooled result hold whichever studies are included, and at every confidence level rather than only at 95%?
Two robustness displays for a meta-analysis. GOSH fits the model to every subset of studies (or a seeded random sample of subsets when there are too many) and plots each subset's pooled estimate against its I², showing clusters, outlying studies and how far the answer can move; the study whose inclusion shifts the subsets most is flagged. The drapery plot draws the p-value function of every study, of the pooled random-effects estimate and of the prediction distribution, so every confidence interval can be read off at once.
A real result
Example “Bcg rr all subsets”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
GOSH (all 8,191 subsets): pooled estimates −1.62 to 0.45, same sign in 99.9%
- Smallest subset estimate
- −1.621
- Largest subset estimate
- 0.4459
- Same sign (share)
- 0.9985
Assumptions
- Exploratory display — TPT Madras 1980 moves the subsets' pooled estimate most; reread it before deciding anything — clusters are not tests.
- Enough studies — 13 studies give 8191 subsets.
GOSH summary (log risk ratio; all 8,191 subsets, common-effect model)
| Value | |
|---|---|
| All studies | −0.4303 |
| Smallest subset estimate | −1.621 |
| Largest subset estimate | 0.4459 |
| Middle 95% of subsets, low | −1.164 |
| Middle 95% of subsets, high | −0.0656 |
| Share with the all-studies sign (%) | 99.853 |
| Share significant at 5% (%) | 93.554 |
| Median I² (%) | 87.707 |
How much each study moves the subsets (mean with − mean without)
| Study | Estimate shift | I² shift (points) |
|---|---|---|
| TPT Madras 1980 | 0.4679 | 14.399 |
| Hart & Sutherland 1977 | −0.1954 | 12.473 |
| Comstock et al 1974 | 0.1019 | 3.888 |
| Stein & Aronson 1953 | −0.0987 | 5.859 |
| Rosenthal et al 1961 | −0.0547 | 4.403 |
| Comstock et al 1976 | 0.0503 | 2.051 |
| Frimodt-Moller et al 1973 | 0.0465 | 1.007 |
| Ferguson & Simes 1949 | −0.0278 | 2.164 |
| Vandiviere et al 1973 | −0.0253 | 1.888 |
| Coetzee & Berjak 1968 | 0.0181 | −0.6047 |
| Comstock & Webster 1969 | 0.0127 | −0.7500 |
| Rosenthal et al 1960 | −0.0099 | −1.483 |
| Aronson 1948 | −0.0041 | −2.720 |
Random-effects estimate behind the drapery plot (95% CI)
| Estimate | Low | High | |
|---|---|---|---|
| Pooled risk ratio | 0.4894 | 0.3441 | 0.6962 |
| Prediction interval | — | 0.1342 | 1.785 |
- A subset cluster away from the rest points to studies that differ; GOSH shows where to look, it does not test anything.
- Each drapery curve reaches p = 1 at its estimate; where it crosses a level α, the curve gives that (1 − α) interval.
GOSH (all 8,191 subsets): pooled estimates −1.62 to 0.45, same sign in 99.9%
- Smallest subset estimate
- −1.621
- Largest subset estimate
- 0.4459
- Same sign (share)
- 0.9985
Assumptions
- Exploratory display — TPT Madras 1980 moves the subsets' pooled estimate most; reread it before deciding anything — clusters are not tests.
- Enough studies — 13 studies give 8191 subsets.
GOSH summary (log risk ratio; all 8,191 subsets, common-effect model)
| Value | |
|---|---|
| All studies | −0.4303 |
| Smallest subset estimate | −1.621 |
| Largest subset estimate | 0.4459 |
| Middle 95% of subsets, low | −1.164 |
| Middle 95% of subsets, high | −0.0656 |
| Share with the all-studies sign (%) | 99.853 |
| Share significant at 5% (%) | 93.554 |
| Median I² (%) | 87.707 |
How much each study moves the subsets (mean with − mean without)
| Study | Estimate shift | I² shift (points) |
|---|---|---|
| TPT Madras 1980 | 0.4679 | 14.399 |
| Hart & Sutherland 1977 | −0.1954 | 12.473 |
| Comstock et al 1974 | 0.1019 | 3.888 |
| Stein & Aronson 1953 | −0.0987 | 5.859 |
| Rosenthal et al 1961 | −0.0547 | 4.403 |
| Comstock et al 1976 | 0.0503 | 2.051 |
| Frimodt-Moller et al 1973 | 0.0465 | 1.007 |
| Ferguson & Simes 1949 | −0.0278 | 2.164 |
| Vandiviere et al 1973 | −0.0253 | 1.888 |
| Coetzee & Berjak 1968 | 0.0181 | −0.6047 |
| Comstock & Webster 1969 | 0.0127 | −0.7500 |
| Rosenthal et al 1960 | −0.0099 | −1.483 |
| Aronson 1948 | −0.0041 | −2.720 |
Random-effects estimate behind the drapery plot (95% CI)
| Estimate | Low | High | |
|---|---|---|---|
| Pooled risk ratio | 0.4894 | 0.3441 | 0.6962 |
| Prediction interval | — | 0.1342 | 1.785 |
- A subset cluster away from the rest points to studies that differ; GOSH shows where to look, it does not test anything.
- Each drapery curve reaches p = 1 at its estimate; where it crosses a level α, the curve gives that (1 − α) interval.
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Bcg rr all subsetsm1_bcg · events_1: events_1 · events_2: events_2 · study: trial · total_1: total_1 · total_2: total_2
- Normand smd dlm1_normand · mean_1: mean_1 · mean_2: mean_2 · sd_1: sd_1 · sd_2: sd_2 · study: source · total_1: total_1 · total_2: total_2
- Hackshaw sampledm1_hackshaw · ci_high: or_high · ci_low: or_low · effect: or · study: study
- Guide all subsetsm1_guide · effect: effect · se: se · study: study
- Molloy dl sampledm1_molloy · n: n · r: r · study: study
- Degenerate one group leftm1_bcg · events_1: events_1 · events_2: events_2 · study: trial · total_1: total_1 · total_2: total_2
What you need
- Study labels (optional)categorical · 0–1 column
- Names the studies in tables and the forest plot.
- Estimate (or ratio)numeric · 0–1 column
- Generic: each study's estimate on an additive scale (log OR, SMD …). With CI limits: the ratio itself (OR, RR, HR).
- Standard errornumeric · 0–1 column
- Generic design: the estimate's standard error.
- Lower CI limit (ratio)numeric · 0–1 column
- Ratio with CI design: the reported lower limit; the SE comes from the CI width on the log scale.
- Upper CI limit (ratio)numeric · 0–1 column
- Ratio with CI design: the reported upper limit.
- Events, group 1numeric · 0–1 column
- Two-arm counts: events in the first (treatment) arm.
- Total, group 1numeric · 0–1 column
- Participants in the first arm (counts and means designs).
- Events, group 2numeric · 0–1 column
- Two-arm counts: events in the second (control) arm.
- Total, group 2numeric · 0–1 column
- Participants in the second arm (counts and means designs).
- Mean, group 1numeric · 0–1 column
- Means design: mean of the first arm.
- SD, group 1numeric · 0–1 column
- Means design: standard deviation of the first arm (not the SE).
- Mean, group 2numeric · 0–1 column
- Means design: mean of the second arm.
- SD, group 2numeric · 0–1 column
- Means design: standard deviation of the second arm.
- Correlationnumeric · 0–1 column
- Correlation design: each study's Pearson r.
- Sample size (correlation)numeric · 0–1 column
- Correlation design: the number of pairs behind each r.
Choices you make
hypothesis
- Study datadefault auto
What each row reports. Auto picks it from the columns you bound.
- Detect from the columns(default) — Counts → two-arm counts; means → means; r → correlations; CI limits → ratio with CI; else estimate + SE.
- Two-arm counts — Each study gives events and totals in two arms; pick it for yes/no outcomes.
- Means and SDs — Each study gives means, SDs and sizes in two arms; pick it for numeric outcomes.
- Correlations — Each study gives a correlation and its sample size; pick it for associations.
- Ratio with CI — Each study gives a ratio with its CI, worked back to a log-scale SE; pick it for published OR, RR or HR.
- Estimate and SE — Each study gives an estimate and its SE; pick it when effects are already computed.
- Effect measuredefault auto
The scale studies are pooled on (ratios on the log scale and reported back as ratios).
- Default for the data(default) — Odds ratio for counts, Hedges' g for means, Fisher's z for correlations.
- Odds ratio — Odds ratio from two-arm counts; steady across baseline risks, and the usual choice for rare events.
- Risk ratio — Risk ratio from two-arm counts; easier to explain than odds, on a ratio scale.
- Risk difference — Risk difference from two-arm counts; gives the absolute effect, which often varies more across studies.
- Standardized mean difference (Hedges' g) — Mean difference in SD units (Hedges' g); pick it when studies use different scales.
- Mean difference — Raw units; only when every study measured the outcome on the same scale.
- Fisher's z (reported as r) — Transforms correlations by Fisher's z before pooling and reports r; the usual choice for correlations.
- Raw correlation — Pools correlations on their raw scale; easy to read, but each one's variance depends on r.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- Model for the subsetsdefault fixed
The model fitted to every subset; Olkin et al. used the common-effect model, which is closed form and fast.
- Common effect (fixed)(default) — Inverse-variance pooling of each subset, as in Olkin et al.'s GOSH plots.
- Random effects (DerSimonian–Laird) — Closed-form random effects for each subset, so heterogeneous subsets are weighted more evenly.
- Most subsets to fitdefault 32767
All 2^k − 1 subsets when that is no more than this (k ≤ 15 by default); otherwise a seeded random sample.
- τ² estimatordefault REML
How the between-study variance is estimated; REML and Paule–Mandel are the usual recommendations.
- Restricted maximum likelihood (REML)(default) — Estimates between-study variance by restricted likelihood; the recommended all-rounder.
- Paule–Mandel — Chooses τ² so Cochran's Q matches its expected value; a good alternative to REML, also for binary outcomes.
- DerSimonian–Laird — Classic method-of-moments; underestimates τ² with few studies.
- Maximum likelihood — Uses the full likelihood; needed to compare moderator models, though τ² runs low with few studies.
- Hedges (unweighted moments) — An unweighted moment estimate; easy to compute, but noisy when studies differ in size.
- Sidik–Jonkman — Starts from a rough τ² and refines it once; rarely gives zero, and overestimates when heterogeneity is low.
- Empirical Bayes (Morris) — An empirical Bayes estimate; gives the same answer as Paule–Mandel when there are no moderators.
- Inference (drapery)default z
Distribution for the pooled estimate's p-value function; Knapp–Hartung widens it with few studies.
- Wald z(default) — Uses the normal distribution; fine with many studies, but intervals run narrow with few.
- Knapp–Hartung t — Uses a t distribution with an adjusted SE; better coverage with few studies.
options
- Zero cellsdefault only0
Continuity correction for log OR / RR when a study has a zero cell.
- Add ½ to studies with a zero cell(default) — Adds ½ to the cells of studies with a zero; the usual choice.
- Add ½ to every study — Adds ½ to every study's cells; matches some older software, and pulls small studies towards no effect.
- No correction (drop undefined) — Adds nothing, so studies with an undefined effect drop out; pick it as a sensitivity check.
- Leave out double-zero studiesdefault on
Studies with no events (or only events) in both arms carry no information about OR or RR.
- Reported CI level (ratio design)default 0.95
The level of the confidence intervals the studies reported (usually 95%).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Comparable studiesNot checked from data: state why it holds
Studies estimate the same kind of effect in comparable populations.
Independent estimatesNot checked from data: state why it holds
One estimate per study; several outcomes or arms from one study need a multilevel model.
Enough studies
Leave-one-out and subset displays say little with fewer than about 6 studies.
Exploratory display
Subset clusters suggest where to look; they are not tests, and a flagged study is a reason to reread it, not to drop it.
What it reports
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- n_subsets
- How many independent units the analysis used; it sets precision and power.
- total_subsets
- A scatter of the pooled estimate against I² for every subset of the studies.
- subsets_label
- A scatter of the pooled estimate against I² for every subset of the studies.
- est
- The average effect across studies from a meta-analysis, weighted by each study's precision.
- se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- tau2
- How much the studies' true effects vary around their mean; τ is the same on the effect's own scale.
- est_bt
- The average effect across studies from a meta-analysis, weighted by each study's precision.
- ci_low_bt
- A range of effect values compatible with your data at the chosen confidence level.
- ci_high_bt
- A range of effect values compatible with your data at the chosen confidence level.
- pi_low_bt
- Where the true effect of a new, comparable study would be expected to fall — wider than the CI of the mean whenever τ² > 0.
- pi_high_bt
- Where the true effect of a new, comparable study would be expected to fall — wider than the CI of the mean whenever τ² > 0.
- gosh_est_all
- A scatter of the pooled estimate against I² for every subset of the studies.
- gosh_est_min
- A scatter of the pooled estimate against I² for every subset of the studies.
- gosh_est_max
- A scatter of the pooled estimate against I² for every subset of the studies.
- gosh_est_q025
- A scatter of the pooled estimate against I² for every subset of the studies.
- gosh_est_q975
- A scatter of the pooled estimate against I² for every subset of the studies.
- gosh_i2_median
- A scatter of the pooled estimate against I² for every subset of the studies.
- gosh_i2_max
- A scatter of the pooled estimate against I² for every subset of the studies.
- share_same_sign
- A scatter of the pooled estimate against I² for every subset of the studies.
- share_sig
- A scatter of the pooled estimate against I² for every subset of the studies.
- top_study
- A scatter of the pooled estimate against I² for every subset of the studies.
- top_shift
- A scatter of the pooled estimate against I² for every subset of the studies.
- top_i2_shift
- A scatter of the pooled estimate against I² for every subset of the studies.
- shift
- The moment a series' level (mean) jumps — a relocated station, a new instrument, a policy taking effect.
- measure
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- measure_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- effect_label
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Subsets are enumerated in the same binary order in both engines, or drawn from the shared Wichmann–Hill stream (each study in with probability ½, empty draws skipped), so both fit the same subsets. metafor::gosh draws its random subsets from R's own generator, so only fully enumerated runs are compared with it (tests/crosscheck/w3lb1_meta_lab.R).
The exact script CodeSplash ran for example “Bcg rr all subsets” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Sensitivity displays — study subsets (GOSH) and p-value functions (drapery)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.sensitivity 1.0.2 · spec 9ba4864056152d27
# Dataset: m1_bcg (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import meta # effect sizes and the random-effects model (twins of codesplashr::cs_meta_*)
from codesplash.stats import meta_lab # GOSH subsets and drapery curves (twins of codesplashr::cs_meta_gosh / cs_meta_drapery)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/m1_bcg.parquet", columns=["trial", "events_1", "total_1", "events_2", "total_2"])
n_input = len(df)
df["trial"] = pd.Categorical(df["trial"], categories=["Aronson 1948", "Ferguson & Simes 1949", "Rosenthal et al 1960", "Hart & Sutherland 1977", "Frimodt-Moller et al 1973", "Stein & Aronson 1953", "Vandiviere et al 1973", "TPT Madras 1980", "Coetzee & Berjak 1968", "Rosenthal et al 1961", "Comstock et al 1974", "Comstock & Webster 1969", "Comstock et al 1976"]) # stored level order
df = df.dropna(subset=["trial", "events_1", "total_1", "events_2", "total_2"]) # listwise deletion over the analysis columns
df["trial"] = df["trial"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["trial", "events_1", "total_1", "events_2", "total_2"]) # infinite values stop the run (registry/errors.yaml)
# %% Studies
design = "binary" # inferred from the bound columns
measure = "RR"
cols = {
"events_1": df["events_1"].to_numpy(dtype=float),
"total_1": df["total_1"].to_numpy(dtype=float),
"events_2": df["events_2"].to_numpy(dtype=float),
"total_2": df["total_2"].to_numpy(dtype=float),
}
es = meta.escalc(design, measure, cols, zero_cells="only0", drop00=True, ci_level=0.95)
measure = es["measure"]
labels_all = df["trial"].astype(str).tolist()
keep = es["keep"]
left_out = [labels_all[i] for i in np.flatnonzero(~keep)]
idx = np.flatnonzero(keep)
y, v = es["yi"][idx], es["vi"][idx]
labels = [labels_all[i] for i in idx]
k = len(y)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A meta-analysis", min=2, n=k) # one usable study can't be pooled
if left_out:
warnings.append(f"Left out ({len(left_out)}): " + ", ".join(left_out) + (" — no events (or only events) in both arms." if design == "binary" else " — effect or variance not computable."))
bt = meta.back_transform(measure)
MEASURE_LABEL = {"GEN": "effect", "LOG": "log ratio", "OR": "log odds ratio", "RR": "log risk ratio", "RD": "risk difference",
"MD": "mean difference", "SMD": "Hedges' g", "ZCOR": "Fisher's z", "COR": "correlation"}[measure]
RATIO = measure in ("OR", "RR", "LOG")
# What a back-transformed number is: a ratio, not a log ratio; a correlation, not Fisher's z.
DISPLAY_LABEL = {"OR": "odds ratio", "RR": "risk ratio", "LOG": "ratio", "ZCOR": "correlation"}.get(measure, MEASURE_LABEL)
# %% GOSH: the model fitted to every subset of studies (or a seeded random sample of subsets)
conf = 0.95
gosh_model = "fixed"
seed = 42 # shared Wichmann–Hill stream: R samples the same subsets
gs = meta_lab.gosh(y, v, model=gosh_model, max_subsets=32767, seed=seed)
est_s, i2_s = gs["est"], gs["i2"]
top = gs["top"]
SUBSETS_LABEL = f"all {gs['n_subsets']:,} subsets" if gs["enumerated"] else f"{gs['n_subsets']:,} random subsets (of {gs['total_subsets']:,.0f})"
# %% Random-effects model and the drapery p-value functions
fit = meta.rma(y, v, method="REML", test="z", level=conf)
est, se, p = float(fit["beta"][0]), float(fit["se"][0]), float(fit["pval"][0])
ci_low, ci_high = float(fit["ci_low"][0]), float(fit["ci_high"][0])
tau2 = fit["tau2"]
pi_low, pi_high = meta.prediction_interval(est, se, tau2, k, level=conf, dist="t")
df_pool = float(fit["dfr"]) if fit["test"] == "knha" else None
dr = meta_lab.drapery(y, v, est, se, tau2, df_pool=df_pool, df_pred=float(k - 2) if k >= 3 else None)
# %% Assumptions
assumptions = [
{"key": "exploratory", "label": "Exploratory display", "status": "info",
"detail": f"{labels[top]} moves the subsets' pooled estimate most; reread it before deciding anything — clusters are not tests."},
{"key": "k_studies", "label": "Enough studies", "status": "warn" if k < 6 else "pass",
"detail": f"{k} studies give {gs['total_subsets']:.0f} subsets" + ("; with this few the cloud has little structure." if k < 6 else ".")},
]
# %% Result
order = np.argsort(-np.abs(gs["shift"]), kind="stable")
rows_s = [{"study": labels[j], "shift": float(gs["shift"][j]), "i2_shift": float(gs["i2_shift"][j])} for j in order]
q = np.quantile(est_s, [0.025, 0.975])
rows_g = [
{"quantity": "All studies", "value": float(gs["est_all"])},
{"quantity": "Smallest subset estimate", "value": float(np.min(est_s))},
{"quantity": "Largest subset estimate", "value": float(np.max(est_s))},
{"quantity": "Middle 95% of subsets, low", "value": float(q[0])},
{"quantity": "Middle 95% of subsets, high", "value": float(q[1])},
{"quantity": "Share with the all-studies sign (%)", "value": 100.0 * gs["share_same_sign"]},
{"quantity": "Share significant at 5% (%)", "value": 100.0 * gs["share_sig"]},
{"quantity": "Median I² (%)", "value": float(np.median(i2_s))},
]
# The chart shows at most 8,000 subsets (every m-th in subset order); the numbers use all of them.
step = max(1, int(math.ceil(len(est_s) / 8000)))
pick = np.arange(0, len(est_s), step)
with_top = gs["member"][pick, top] > 0
group = [f"with {labels[top]}" if w else f"without {labels[top]}" for w in with_top]
gosh_chart = cs.chart("gosh", "gosh", f"GOSH: {SUBSETS_LABEL}" + ("" if step == 1 else f", 1 in {step} drawn"),
{"estimate": cs.col(MEASURE_LABEL, [float(t) for t in est_s[pick]]), "i2": cs.col("I² (%)", [float(t) for t in i2_s[pick]]),
"group": cs.col("subset", group)},
controls={"center": float(gs["est_all"]), "reference": 0})
grid_bt = [float(t) for t in bt(dr["grid"])]
xs, ps, cv, kd = [], [], [], []
for i in range(k):
xs += grid_bt
ps += [float(t) for t in dr["study"][i]]
cv += [labels[i]] * len(grid_bt)
kd += ["study"] * len(grid_bt)
for name, curve, kind in (("Prediction", dr["prediction"], "prediction"), ("Pooled (random effects)", dr["pooled"], "pooled")):
xs += grid_bt
ps += [float(t) for t in curve]
cv += [name] * len(grid_bt)
kd += [kind] * len(grid_bt)
drapery_chart = cs.chart("drapery", "drapery", "Drapery plot: p-value functions", {"x": cs.col(DISPLAY_LABEL, xs), "p": cs.col("p-value", ps),
"curve": cs.col("curve", cv), "kind": cs.col("kind", kd)},
controls={"log": RATIO, "reference": 1 if RATIO else 0, "alpha": round(1 - conf, 10)})
cs.publish({
"method": "meta.sensitivity",
"methodVersion": "1.0.2",
"title": f"Sensitivity of {k} studies: GOSH and drapery",
"engine": cs.engine_info("numpy", "scipy"),
"n": k,
"summary": f"Across {SUBSETS_LABEL}, pooled {MEASURE_LABEL} {np.min(est_s):.3g} to {np.max(est_s):.3g}; same sign as all studies in {100 * gs['share_same_sign']:.1f}%. {labels[top]} shifts it most ({gs['shift'][top]:+.3g}).",
"apa": f"GOSH ({SUBSETS_LABEL}): pooled estimates {cs.fmt_num(float(np.min(est_s)))} to {cs.fmt_num(float(np.max(est_s)))}, same sign in {100 * gs['share_same_sign']:.1f}%",
"statistics": [{"key": "gosh_est_min", "label": "Smallest subset estimate", "value": float(np.min(est_s))},
{"key": "gosh_est_max", "label": "Largest subset estimate", "value": float(np.max(est_s))},
{"key": "share_same_sign", "label": "Same sign (share)", "value": gs["share_same_sign"]}],
"tables": [
{"key": "gosh", "title": f"GOSH summary ({MEASURE_LABEL}; {SUBSETS_LABEL}, {'common-effect' if gosh_model == 'fixed' else 'DerSimonian–Laird'} model)",
"columns": [{"key": "quantity", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": rows_g},
{"key": "studies", "title": "How much each study moves the subsets (mean with − mean without)",
"columns": [{"key": "study", "label": "Study", "type": "string"}, {"key": "shift", "label": "Estimate shift", "type": "number"},
{"key": "i2_shift", "label": "I² shift (points)", "type": "number"}], "rows": rows_s},
{"key": "pooled", "title": f"Random-effects estimate behind the drapery plot ({conf:.0%} CI)",
"columns": [{"key": "quantity", "label": "", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "low", "label": "Low", "type": "number"}, {"key": "high", "label": "High", "type": "number"}],
"rows": [{"quantity": f"Pooled {DISPLAY_LABEL}", "estimate": float(bt(est)), "low": float(bt(ci_low)), "high": float(bt(ci_high))},
{"quantity": "Prediction interval", "estimate": None, "low": float(bt(pi_low)), "high": float(bt(pi_high))}]},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": ["A subset cluster away from the rest points to studies that differ; GOSH shows where to look, it does not test anything.",
"Each drapery curve reaches p = 1 at its estimate; where it crosses a level α, the curve gives that (1 − α) interval."],
"charts": [gosh_chart, drapery_chart],
"values": {
"k": k, "n_subsets": gs["n_subsets"], "total_subsets": gs["total_subsets"], "subsets_label": SUBSETS_LABEL,
"est": est, "se": se, "p": p, "ci_low": ci_low, "ci_high": ci_high, "tau2": tau2,
"est_bt": float(bt(est)), "ci_low_bt": float(bt(ci_low)), "ci_high_bt": float(bt(ci_high)), "pi_low_bt": float(bt(pi_low)), "pi_high_bt": float(bt(pi_high)),
"gosh_est_all": float(gs["est_all"]), "gosh_est_min": float(np.min(est_s)), "gosh_est_max": float(np.max(est_s)),
"gosh_est_q025": float(q[0]), "gosh_est_q975": float(q[1]), "gosh_i2_median": float(np.median(i2_s)), "gosh_i2_max": float(np.max(i2_s)),
"share_same_sign": gs["share_same_sign"], "share_sig": gs["share_sig"],
"top_study": labels[top], "top_shift": float(gs["shift"][top]), "top_i2_shift": float(gs["i2_shift"][top]),
"shift": [float(t) for t in gs["shift"]],
"measure": measure, "measure_label": MEASURE_LABEL, "effect_label": DISPLAY_LABEL,
},
})
The exact script CodeSplash ran for example “Bcg rr all subsets” · R version 4.5.1 (2025-06-13)
# Sensitivity displays — study subsets (GOSH) and p-value functions (drapery)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.sensitivity 1.0.2 · spec 9ba4864056152d27
# Dataset: m1_bcg (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_meta_escalc, cs_meta_rma, cs_meta_gosh, cs_meta_drapery (twins of codesplash.stats.meta / meta_lab)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/m1_bcg.parquet", col_select = c("trial", "events_1", "total_1", "events_2", "total_2")))
n_input <- nrow(df)
df[["trial"]] <- factor(df[["trial"]], levels = c("Aronson 1948", "Ferguson & Simes 1949", "Rosenthal et al 1960", "Hart & Sutherland 1977", "Frimodt-Moller et al 1973", "Stein & Aronson 1953", "Vandiviere et al 1973", "TPT Madras 1980", "Coetzee & Berjak 1968", "Rosenthal et al 1961", "Comstock et al 1974", "Comstock & Webster 1969", "Comstock et al 1976")) # stored level order
df <- df[stats::complete.cases(df[c("trial", "events_1", "total_1", "events_2", "total_2")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("trial", "events_1", "total_1", "events_2", "total_2")) # infinite values stop the run (registry/errors.yaml)
# %% Studies
design <- "binary" # inferred from the bound columns
measure <- "RR"
cols <- list(
events_1 = as.numeric(df[["events_1"]]),
total_1 = as.numeric(df[["total_1"]]),
events_2 = as.numeric(df[["events_2"]]),
total_2 = as.numeric(df[["total_2"]]),
NULL
)
cols <- Filter(Negate(is.null), cols)
es <- cs_meta_escalc(design, measure, cols, zero_cells = "only0", drop00 = TRUE, ci_level = 0.95)
measure <- es$measure
labels_all <- as.character(df[["trial"]])
keep <- es$keep
left_out <- labels_all[!keep]
idx <- which(keep)
y <- es$yi[idx]; v <- es$vi[idx]
labels <- labels_all[idx]
k <- length(y)
if (k < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A meta-analysis", min = 2, n = k) # one usable study can't be pooled
if (length(left_out)) {
warnings <- c(warnings, paste0(sprintf("Left out (%d): ", length(left_out)), paste(left_out, collapse = ", "),
if (design == "binary") " — no events (or only events) in both arms." else " — effect or variance not computable."))
}
bt <- cs_meta_back(measure)
MEASURE_LABEL <- c(GEN = "effect", LOG = "log ratio", OR = "log odds ratio", RR = "log risk ratio", RD = "risk difference",
MD = "mean difference", SMD = "Hedges' g", ZCOR = "Fisher's z", COR = "correlation")[[measure]]
RATIO <- measure %in% c("OR", "RR", "LOG")
# What a back-transformed number is: a ratio, not a log ratio; a correlation, not Fisher's z.
DISPLAY_LABEL <- if (measure %in% c("OR", "RR", "LOG", "ZCOR")) c(OR = "odds ratio", RR = "risk ratio", LOG = "ratio", ZCOR = "correlation")[[measure]] else MEASURE_LABEL
# %% GOSH: the model fitted to every subset of studies (or a seeded random sample of subsets)
conf <- 0.95
gosh_model <- "fixed"
seed <- 42 # shared Wichmann–Hill stream: Python samples the same subsets
gs <- cs_meta_gosh(y, v, model = gosh_model, max_subsets = 32767, seed = seed)
est_s <- gs$est; i2_s <- gs$i2
top <- gs$top
big <- function(x) formatC(x, format = "f", digits = 0, big.mark = ",")
SUBSETS_LABEL <- if (gs$enumerated) sprintf("all %s subsets", big(gs$n_subsets)) else sprintf("%s random subsets (of %s)", big(gs$n_subsets), big(gs$total_subsets))
# %% Random-effects model and the drapery p-value functions
fit <- cs_meta_rma(y, v, method = "REML", test = "z", level = conf)
est <- fit$beta[1]; se <- fit$se[1]; p <- fit$pval[1]
ci_low <- fit$ci_low[1]; ci_high <- fit$ci_high[1]
tau2 <- fit$tau2
pin <- cs_meta_pi(est, se, tau2, k, level = conf, dist = "t")
pi_low <- pin[1]; pi_high <- pin[2]
df_pool <- if (fit$test == "knha") fit$dfr else NULL
dr <- cs_meta_drapery(y, v, est, se, tau2, df_pool = df_pool, df_pred = if (k >= 3) k - 2 else NULL)
# %% Assumptions
assumptions <- list(
list(key = "exploratory", label = "Exploratory display", status = "info",
detail = sprintf("%s moves the subsets' pooled estimate most; reread it before deciding anything — clusters are not tests.", labels[top])),
list(key = "k_studies", label = "Enough studies", status = if (k < 6) "warn" else "pass",
detail = paste0(sprintf("%d studies give %.0f subsets", k, gs$total_subsets), if (k < 6) "; with this few the cloud has little structure." else "."))
)
# %% Result
ord <- order(-abs(gs$shift))
rows_s <- lapply(ord, function(j) list(study = labels[j], shift = gs$shift[j], i2_shift = gs$i2_shift[j]))
q <- stats::quantile(est_s, c(0.025, 0.975), names = FALSE, type = 7)
rows_g <- list(
list(quantity = "All studies", value = gs$est_all),
list(quantity = "Smallest subset estimate", value = min(est_s)),
list(quantity = "Largest subset estimate", value = max(est_s)),
list(quantity = "Middle 95% of subsets, low", value = q[1]),
list(quantity = "Middle 95% of subsets, high", value = q[2]),
list(quantity = "Share with the all-studies sign (%)", value = 100 * gs$share_same_sign),
list(quantity = "Share significant at 5% (%)", value = 100 * gs$share_sig),
list(quantity = "Median I² (%)", value = stats::median(i2_s))
)
# The chart shows at most 8,000 subsets (every m-th in subset order); the numbers use all of them.
step <- max(1, ceiling(length(est_s) / 8000))
pick <- seq(1, length(est_s), by = step)
with_top <- gs$member[pick, top] > 0
group <- ifelse(with_top, paste("with", labels[top]), paste("without", labels[top]))
gosh_chart <- cs_chart("gosh", "gosh", paste0("GOSH: ", SUBSETS_LABEL, if (step == 1) "" else sprintf(", 1 in %d drawn", step)),
list(estimate = cs_col(MEASURE_LABEL, est_s[pick]), i2 = cs_col("I² (%)", i2_s[pick]), group = cs_col("subset", group)),
controls = list(center = gs$est_all, reference = 0))
grid_bt <- bt(dr$grid)
ng <- length(grid_bt)
xs <- c(rep(grid_bt, k), grid_bt, grid_bt)
ps <- c(as.numeric(t(dr$study)), dr$prediction, dr$pooled)
cv <- c(rep(labels, each = ng), rep("Prediction", ng), rep("Pooled (random effects)", ng))
kd <- c(rep("study", k * ng), rep("prediction", ng), rep("pooled", ng))
drapery_chart <- cs_chart("drapery", "drapery", "Drapery plot: p-value functions",
list(x = cs_col(DISPLAY_LABEL, xs), p = cs_col("p-value", ps), curve = cs_col("curve", cv), kind = cs_col("kind", kd)),
controls = list(log = RATIO, reference = if (RATIO) 1 else 0, alpha = round(1 - conf, 10)))
g3 <- function(x) format(signif(x, 3))
pct <- sprintf("%.0f%%", conf * 100)
cs_publish(list(
method = "meta.sensitivity",
methodVersion = "1.0.2",
title = sprintf("Sensitivity of %d studies: GOSH and drapery", k),
engine = cs_engine_info("stats", "nanoparquet"),
n = k,
summary = sprintf("Across %s, pooled %s %s to %s; same sign as all studies in %.1f%%. %s shifts it most (%+.3g).", SUBSETS_LABEL, MEASURE_LABEL,
g3(min(est_s)), g3(max(est_s)), 100 * gs$share_same_sign, labels[top], gs$shift[top]),
apa = sprintf("GOSH (%s): pooled estimates %s to %s, same sign in %.1f%%", SUBSETS_LABEL, cs_fmt_num(min(est_s)), cs_fmt_num(max(est_s)), 100 * gs$share_same_sign),
statistics = list(list(key = "gosh_est_min", label = "Smallest subset estimate", value = min(est_s)),
list(key = "gosh_est_max", label = "Largest subset estimate", value = max(est_s)),
list(key = "share_same_sign", label = "Same sign (share)", value = gs$share_same_sign)),
tables = list(
list(key = "gosh", title = sprintf("GOSH summary (%s; %s, %s model)", MEASURE_LABEL, SUBSETS_LABEL, if (gosh_model == "fixed") "common-effect" else "DerSimonian–Laird"),
columns = list(list(key = "quantity", label = "", type = "string"), list(key = "value", label = "Value", type = "number")), rows = rows_g),
list(key = "studies", title = "How much each study moves the subsets (mean with − mean without)",
columns = list(list(key = "study", label = "Study", type = "string"), list(key = "shift", label = "Estimate shift", type = "number"),
list(key = "i2_shift", label = "I² shift (points)", type = "number")), rows = rows_s),
list(key = "pooled", title = sprintf("Random-effects estimate behind the drapery plot (%s CI)", pct),
columns = list(list(key = "quantity", label = "", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "low", label = "Low", type = "number"), list(key = "high", label = "High", type = "number")),
rows = list(list(quantity = sprintf("Pooled %s", DISPLAY_LABEL), estimate = bt(est), low = bt(ci_low), high = bt(ci_high)),
list(quantity = "Prediction interval", estimate = NULL, low = bt(pi_low), high = bt(pi_high))))
),
assumptions = assumptions,
warnings = warnings,
notes = list("A subset cluster away from the rest points to studies that differ; GOSH shows where to look, it does not test anything.",
"Each drapery curve reaches p = 1 at its estimate; where it crosses a level α, the curve gives that (1 − α) interval."),
charts = list(gosh_chart, drapery_chart),
values = list(
k = k, n_subsets = gs$n_subsets, total_subsets = gs$total_subsets, subsets_label = SUBSETS_LABEL,
est = est, se = se, p = p, ci_low = ci_low, ci_high = ci_high, tau2 = tau2,
est_bt = bt(est), ci_low_bt = bt(ci_low), ci_high_bt = bt(ci_high), pi_low_bt = bt(pi_low), pi_high_bt = bt(pi_high),
gosh_est_all = gs$est_all, gosh_est_min = min(est_s), gosh_est_max = max(est_s),
gosh_est_q025 = q[1], gosh_est_q975 = q[2], gosh_i2_median = stats::median(i2_s), gosh_i2_max = max(i2_s),
share_same_sign = gs$share_same_sign, share_sig = gs$share_sig,
top_study = labels[top], top_shift = gs$shift[top], top_i2_shift = gs$i2_shift[top],
shift = gs$shift,
measure = measure, measure_label = MEASURE_LABEL, effect_label = DISPLAY_LABEL
)
))
Sources
- Olkin, I., Dahabreh, I. J., & Trikalinos, T. A. (2012). GOSH – a graphical display of study heterogeneity. Research Synthesis Methods, 3, 214–223.
- Rücker, G., & Schwarzer, G. (2021). Beyond the forest plot: The drapery plot. Research Synthesis Methods, 12, 13–19.
- Infanger, D., & Schmidt-Trucksäss, A. (2019). P value functions: An underused method to present research results and to promote quantitative reasoning. Statistics in Medicine, 38, 4189–4197.
- DerSimonian, R., & Laird, N. (1986). Meta-analysis in clinical trials. Controlled Clinical Trials, 7, 177–188.
From the CodeSplash method registry · meta.sensitivity v1.0.2.