Skip to content

Stress-testing a pooled result

Ask what missing studies, a prior on heterogeneity or a few influential studies would do to a meta-analysis, with selection models, p-curve, Bayesian pooling and GOSH plots.

Advanced ~18 min15 steps

What runs in CodeSplash

You will be able to

  • Fit a selection model and read its weights as an assumption about publication, not a discovery
  • Use p-curve to ask whether significant results carry evidential value
  • State the priors of a Bayesian meta-analysis and see how much they move the answer
  • Read a GOSH plot and a drapery plot as sensitivity displays

Read first

01

Three ways a pooled result can mislead

Read

A random-effects estimate assumes you saw every study, that τ is estimated well, and that no single study decides the answer. Each assumption gets its own check here. None of them replaces the ordinary model; each asks how far the answer could move.

02

Model the missing studies

Predict

Predict first

Hackshaw's 37 passive-smoking studies give a pooled odds ratio of 1.24. A three-parameter selection modelThree-parameter selection modelThe selection model with one cutpoint at a one-sided p of .025, so its three parameters are μ, τ² and one selection weight. lets non-significant studies be less likely to reach print.

What happens to the pooled odds ratio?

It moves upIt barely movesIt moves towards no effect
Reveal

It moves to 1.21, a little towards no effect. The weight for non-significant studies is below 1, but the likelihood-ratio test for selection gives p = .732.

03

Read the weights

Read
Selection model for 37 studies (random effects, 3PSM)Recorded · Python and R agreeRecorded 2026-11-17 · 39 values compared
R

adjusted ratio = 1.21, 95% CI [1.04, 1.42], p = .015; LRT χ²(1) = 0.12, p = .732

Adjusted ratio
1.215
p
.015
Unadjusted ratio
1.242
p (selection)
.732

Effect size

  • Adjusted ratio 1.215 95% CI [1.039, 1.420]

Plots

Estimated selection weightsHow much more likely were studies to be published when their one-sided p-value fell in each interval?
View data
CI highCI lowstudiesp top fromweight
——70.025001
1.93803010.02500.7644
Funnel plot with the selection-adjusted estimateAre small studies' effects distributed symmetrically around the pooled effect?
View data
log ratiostudystandard error
0.1655Garfinkel 19810.1370
0.3716Hirayama 19840.1818
0.7031Butler 19880.7350
0.1823Cardenas 19970.1768
−0.2877Chan 19820.2822
0.7275Correa 19830.4768
0.7561Trichopolous 19830.2982
−0.2231Buffler 19840.4390
−0.2357Kabat 19840.5823
0.6981Lam 19850.3132
0.2070Garfinkel 19850.2134
0.1823Wu 19850.4814
0.4187Akiba 19860.2822
0.0296Lee 19860.4663
0.4383Koo 19870.2774
0.0296Pershagen 19870.2674
0.8502Humble 19870.5409
0.5008Lam 19870.1801
0.1740Gao 19870.1905
0.4187Brownson 19870.6956
0.7701Geng 19880.3519
0.0770Shimizu 19880.2666
0.9361Inoue 19880.6310
0.4824Kalandidi 19900.2994
0.0583Sobue 19900.1836
−0.2357Wu-Williams 19900.1270
−0.3011Liu 19910.4245
0.8198Jockel 19910.5632
−0.0305Brownson 19920.1120
0.4700Stockwell 19920.3372
0.1740Du 19930.2989
0.5068Liu 19930.4195
0.2311Fontham 19940.1001
0.0953Kabat 19950.2936
0.5068Zaridze 19950.1997
0.1484Sun 19960.1908
0.1044Wang 19960.2577
p-curve of the significant resultsDo the significant results look like they come from real effects (right-skewed) or from selective reporting of null effects (flat or left-skewed)?
View data
p-valueno effect %observed %33% power %
0.01002014.28644.253
0.02002028.57119.514
0.03002042.85714.443
0.040020011.760
0.05002014.28610.030

Assumptions

  • Enough studies — 37 studies.
  • Selection acts on p-values — The model assumes publication depended only on each study's one-sided p-value; other causes of funnel asymmetry are not modeled.
  • Likelihood maximized — Newton iterations converged.

Pooled ratio with and without selection (95% CI)

ModelEstimateCI lowCI highpτ²
Without selection (ML)1.242———0.0204
With selection (weights estimated)1.2151.0391.4200.01480.0166

Selection weights by one-sided p-value (estimated; first interval fixed at 1)

IntervalStudiesWeightSECI lowCI high
0 < p ≤ 0.02571———
0.025 < p ≤ 1300.76440.598901.938

Likelihood-ratio tests

Testχ²p
Selection (all weights = 1), χ²(1)0.11710.7323
Heterogeneity (τ² = 0), χ²(1)2.0330.1539

p-curve of 7 significant result(s) (two-sided p < .05, favored direction)

TestStouffer Zp
Right skew, full curve (evidential value)−0.68820.2457
Right skew, half curve (p < .025)−0.02490.4900
Flatter than 33% power, full curve−0.91670.1796
Flatter than 33% power, half curve−1.0230.1530
Binomial: more p < .025 than half—0.5000
Binomial: fewer p < .025 than at 33% power—0.3210
  • Selection models correct for one assumed publication mechanism; read the adjusted estimate as a sensitivity analysis, not the truth.
  • The p-curve is inconclusive. p-curve reads only the significant results and says nothing about their size.
The exact R script · R R version 4.5.1 (2025-06-13)
# Selection models and p-curve (publication bias)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.selection 1.0.2 · spec 0f4bd5606c457350
# Dataset: m1_hackshaw (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_selmodel, cs_meta_pcurve (twins of codesplash.stats.meta / meta_lab)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/m1_hackshaw.parquet", col_select = c("study", "or", "or_low", "or_high")))
n_input <- nrow(df)
df[["study"]] <- factor(df[["study"]], levels = c("Garfinkel 1981", "Hirayama 1984", "Butler 1988", "Cardenas 1997", "Chan 1982", "Correa 1983", "Trichopolous 1983", "Buffler 1984", "Kabat 1984", "Lam 1985", "Garfinkel 1985", "Wu 1985", "Akiba 1986", "Lee 1986", "Koo 1987", "Pershagen 1987", "Humble 1987", "Lam 1987", "Gao 1987", "Brownson 1987", "Geng 1988", "Shimizu 1988", "Inoue 1988", "Kalandidi 1990", "Sobue 1990", "Wu-Williams 1990", "Liu 1991", "Jockel 1991", "Brownson 1992", "Stockwell 1992", "Du 1993", "Liu 1993", "Fontham 1994", "Kabat 1995", "Zaridze 1995", "Sun 1996", "Wang 1996"))  # stored level order
df <- df[stats::complete.cases(df[c("study", "or", "or_low", "or_high")]), , 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("study", "or", "or_low", "or_high"))  # infinite values stop the run (registry/errors.yaml)
# %% Studies
design <- "ratio_ci"  # inferred from the bound columns
measure <- "GEN"
cols <- list(
  effect = as.numeric(df[["or"]]),
  ci_low = as.numeric(df[["or_low"]]),
  ci_high = as.numeric(df[["or_high"]]),
  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[["study"]])
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

# %% Selection model (maximum likelihood)
conf <- 0.95
weights <- "estimate"
steps <- as.numeric(unlist(c(0.025)))
alternative <- "greater"
model <- "random"
sel <- cs_meta_selmodel(y, v, steps = steps, alternative = alternative, model = model, weights = weights, level = conf)
WEIGHTS_LABEL <- c(estimate = "weights estimated", moderate_one = "Vevea–Woods moderate one-tailed weights",
                   severe_one = "Vevea–Woods severe one-tailed weights", moderate_two = "Vevea–Woods moderate two-tailed weights",
                   severe_two = "Vevea–Woods severe two-tailed weights")[[weights]]
MODEL_LABEL <- paste0(if (model == "random") "random effects" else "common effect",
                      if (weights == "estimate" && length(sel$steps) == 2 && model == "random") ", 3PSM" else "")
est_delta <- weights == "estimate"

# %% p-curve of the significant results
pc <- cs_meta_pcurve(y / sqrt(v), side = alternative)

# %% Assumptions
assumptions <- list(
  list(key = "k_studies", label = "Enough studies", status = if (k < 20 && est_delta) "warn" else "pass",
       detail = paste0(sprintf("%d studies", k), if (k < 20 && est_delta) "; estimated selection weights are unstable below about 20 studies — compare with fixed Vevea–Woods weights." else ".")),
  list(key = "selection_on_p", label = "Selection acts on p-values", status = "info",
       detail = "The model assumes publication depended only on each study's one-sided p-value; other causes of funnel asymmetry are not modeled."),
  list(key = "converged", label = "Likelihood maximized", status = if (sel$converged) "pass" else "warn",
       detail = if (sel$converged) "Newton iterations converged." else "The optimizer stopped before convergence; treat the estimates with caution.")
)

# %% Result
lows <- sel$lows; highs <- sel$steps
na_or <- function(x) if (is.na(x)) NULL else x
g3 <- function(x) format(signif(x, 3))
pct <- sprintf("%.0f%%", conf * 100)
rows_w <- lapply(seq_along(highs), function(j) list(interval = sprintf("%s < p ≤ %s", sprintf("%g", lows[j]), sprintf("%g", highs[j])), k = sel$counts[j],
                                                    weight = sel$delta[j], se = na_or(sel$se_delta[j]), low = na_or(sel$delta_ci_low[j]),
                                                    high = na_or(sel$delta_ci_high[j])))
rows_m <- list(
  list(model = "Without selection (ML)", estimate = bt(sel$mu_unadj), low = NULL, high = NULL, p = NULL, tau2 = sel$tau2_unadj),
  list(model = sprintf("With selection (%s)", WEIGHTS_LABEL), estimate = bt(sel$mu), low = bt(sel$ci_low), high = bt(sel$ci_high), p = sel$p, tau2 = sel$tau2)
)
rows_t <- list()
if (est_delta) rows_t[[length(rows_t) + 1]] <- list(test = sprintf("Selection (all weights = 1), χ²(%d)", as.integer(sel$lrt_df)), statistic = sel$lrt, p = sel$lrt_p)
if (model == "random") rows_t[[length(rows_t) + 1]] <- list(test = "Heterogeneity (τ² = 0), χ²(1)", statistic = sel$lrt_tau2, p = sel$lrt_tau2_p)
tables <- list(
  list(key = "estimates", title = sprintf("Pooled %s with and without selection (%s CI)", DISPLAY_LABEL, pct),
       columns = list(list(key = "model", label = "Model", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
                      list(key = "low", label = "CI low", type = "number"), list(key = "high", label = "CI high", type = "number"),
                      list(key = "p", label = "p", type = "number"), list(key = "tau2", label = "τ²", type = "number")),
       rows = rows_m),
  list(key = "weights", title = paste0("Selection weights by one-sided p-value (", if (est_delta) "estimated; first interval fixed at 1" else "fixed a priori", ")"),
       columns = list(list(key = "interval", label = "Interval", type = "string"), list(key = "k", label = "Studies", type = "integer"),
                      list(key = "weight", label = "Weight", type = "number"), list(key = "se", label = "SE", type = "number"),
                      list(key = "low", label = "CI low", type = "number"), list(key = "high", label = "CI high", type = "number")),
       rows = rows_w)
)
if (length(rows_t)) {
  tables[[length(tables) + 1]] <- list(key = "lrt", title = "Likelihood-ratio tests",
                                       columns = list(list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "χ²", type = "number"),
                                                      list(key = "p", label = "p", type = "number")), rows = rows_t)
}
charts <- list()
if (est_delta) {
  charts[[length(charts) + 1]] <- cs_chart("weights", "selection-weights", "Estimated selection weights",
    list(p_low = cs_col("p from", lows), p_high = cs_col("p to", highs), weight = cs_col("weight", sel$delta), ci_low = cs_col("CI low", sel$delta_ci_low),
         ci_high = cs_col("CI high", sel$delta_ci_high), n = cs_col("studies", sel$counts)),
    controls = list(logP = TRUE, reference = 1))
}
charts[[length(charts) + 1]] <- cs_chart("funnel", "meta-funnel", "Funnel plot with the selection-adjusted estimate",
  list(estimate = cs_col(MEASURE_LABEL, y), se = cs_col("standard error", sqrt(v)), label = cs_col("study", labels)),
  controls = list(center = sel$mu_unadj, adjusted = sel$mu, contours = TRUE))
pc_values <- list(n_sig = 0, pc_right_full_p = NULL, pc_right_half_p = NULL, pc_flat_full_p = NULL, pc_flat_half_p = NULL,
                  pc_binom_right_p = NULL, pc_binom_flat_p = NULL, pc_verdict = "not run")
notes <- list("Selection models correct for one assumed publication mechanism; read the adjusted estimate as a sensitivity analysis, not the truth.")
if (!is.null(pc)) {
  pc_values <- list(n_sig = pc$n_sig, pc_right_full_p = pc$right_full_p, pc_right_half_p = pc$right_half_p, pc_flat_full_p = pc$flat_full_p,
                    pc_flat_half_p = pc$flat_half_p, pc_binom_right_p = pc$binom_right_p, pc_binom_flat_p = pc$binom_flat_p, pc_verdict = pc$verdict)
  if (pc$n_sig > 0) {
    tables[[length(tables) + 1]] <- list(key = "pcurve", title = sprintf("p-curve of %d significant result(s) (two-sided p < .05, favored direction)", pc$n_sig),
      columns = list(list(key = "test", label = "Test", type = "string"), list(key = "z", label = "Stouffer Z", type = "number"), list(key = "p", label = "p", type = "number")),
      rows = list(list(test = "Right skew, full curve (evidential value)", z = pc$right_full_z, p = pc$right_full_p),
                  list(test = "Right skew, half curve (p < .025)", z = na_or(pc$right_half_z), p = na_or(pc$right_half_p)),
                  list(test = "Flatter than 33% power, full curve", z = pc$flat_full_z, p = pc$flat_full_p),
                  list(test = "Flatter than 33% power, half curve", z = na_or(pc$flat_half_z), p = na_or(pc$flat_half_p)),
                  list(test = "Binomial: more p < .025 than half", z = NULL, p = pc$binom_right_p),
                  list(test = "Binomial: fewer p < .025 than at 33% power", z = NULL, p = pc$binom_flat_p)))
    charts[[length(charts) + 1]] <- cs_chart("pcurve", "pcurve", "p-curve of the significant results",
      list(bin = cs_col("p-value", pc$bins), observed = cs_col("observed %", pc$observed), null = cs_col("no effect %", pc$expected_null),
           power33 = cs_col("33% power %", pc$expected_33)),
      controls = list(k = pc$n_sig))
    verdict_txt <- c(evidential = "The significant results are right-skewed: they carry evidential value.",
                     inadequate = "The significant results are flatter than 33% power would give: evidential value is inadequate.",
                     inconclusive = "The p-curve is inconclusive.")[[pc$verdict]]
    notes[[length(notes) + 1]] <- paste(verdict_txt, "p-curve reads only the significant results and says nothing about their size.")
  } else {
    notes[[length(notes) + 1]] <- "No study is significant in the favored direction, so there is no p-curve."
  }
}
stats_list <- list(list(key = "est_bt", label = sprintf("Adjusted %s", DISPLAY_LABEL), value = bt(sel$mu)), list(key = "p", label = "p", value = sel$p, format = "p"),
                   list(key = "est_unadj_bt", label = sprintf("Unadjusted %s", DISPLAY_LABEL), value = bt(sel$mu_unadj)))
if (est_delta) stats_list[[length(stats_list) + 1]] <- list(key = "lrt_p", label = "p (selection)", value = sel$lrt_p, format = "p")
cs_publish(list(
  method = "meta.selection",
  methodVersion = "1.0.2",
  title = sprintf("Selection model for %d studies (%s)", k, MODEL_LABEL),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = k,
  summary = paste0(sprintf("Adjusted %s %s, %s CI [%s, %s], %s (unadjusted %s)", DISPLAY_LABEL, g3(bt(sel$mu)), pct, g3(bt(sel$ci_low)), g3(bt(sel$ci_high)),
                           cs_fmt_p(sel$p), g3(bt(sel$mu_unadj))), if (est_delta) sprintf("; selection LRT %s.", cs_fmt_p(sel$lrt_p)) else "."),
  apa = paste0(sprintf("adjusted %s = %s, %s CI [%s, %s], %s", DISPLAY_LABEL, cs_fmt_num(bt(sel$mu)), pct, cs_fmt_num(bt(sel$ci_low)), cs_fmt_num(bt(sel$ci_high)), cs_fmt_p(sel$p)),
               if (est_delta) sprintf("; LRT χ²(%d) = %s, %s", as.integer(sel$lrt_df), cs_fmt_num(sel$lrt), cs_fmt_p(sel$lrt_p)) else ""),
  statistics = stats_list,
  tables = tables,
  effectSizes = list(list(key = "est_bt", label = sprintf("Adjusted %s", DISPLAY_LABEL), value = bt(sel$mu), ciLow = bt(sel$ci_low), ciHigh = bt(sel$ci_high),
                          ciLevel = conf, method = sprintf("step-function selection model (%s)", WEIGHTS_LABEL))),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = charts,
  values = c(list(
    k = k, est = sel$mu, se = sel$se, z = sel$z, p = sel$p, ci_low = sel$ci_low, ci_high = sel$ci_high,
    est_bt = bt(sel$mu), ci_low_bt = bt(sel$ci_low), ci_high_bt = bt(sel$ci_high),
    est_unadj = sel$mu_unadj, est_unadj_bt = bt(sel$mu_unadj), tau2 = sel$tau2, se_tau2 = sel$se_tau2, tau2_unadj = sel$tau2_unadj,
    ll = sel$ll, ll_unadj = sel$ll_unadj, lrt = sel$lrt, lrt_df = sel$lrt_df, lrt_p = sel$lrt_p, lrt_tau2 = sel$lrt_tau2, lrt_tau2_p = sel$lrt_tau2_p,
    steps = sel$steps, counts = as.numeric(sel$counts), delta = sel$delta, delta_se = sel$se_delta),
    pc_values,
    list(measure = measure, measure_label = MEASURE_LABEL, effect_label = DISPLAY_LABEL, weights_label = WEIGHTS_LABEL, model_label = MODEL_LABEL))
))
Python

adjusted ratio = 1.21, 95% CI [1.04, 1.42], p = .015; LRT χ²(1) = 0.12, p = .732

Adjusted ratio
1.215
p
.015
Unadjusted ratio
1.242
p (selection)
.732

Effect size

  • Adjusted ratio 1.215 95% CI [1.039, 1.420]

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Enough studies — 37 studies.
  • Selection acts on p-values — The model assumes publication depended only on each study's one-sided p-value; other causes of funnel asymmetry are not modeled.
  • Likelihood maximized — Newton iterations converged.

Pooled ratio with and without selection (95% CI)

ModelEstimateCI lowCI highpτ²
Without selection (ML)1.242———0.0204
With selection (weights estimated)1.2151.0391.4200.01480.0166

Selection weights by one-sided p-value (estimated; first interval fixed at 1)

IntervalStudiesWeightSECI lowCI high
0 < p ≤ 0.02571———
0.025 < p ≤ 1300.76440.598901.938

Likelihood-ratio tests

Testχ²p
Selection (all weights = 1), χ²(1)0.11710.7323
Heterogeneity (τ² = 0), χ²(1)2.0330.1539

p-curve of 7 significant result(s) (two-sided p < .05, favored direction)

TestStouffer Zp
Right skew, full curve (evidential value)−0.68820.2457
Right skew, half curve (p < .025)−0.02490.4900
Flatter than 33% power, full curve−0.91670.1796
Flatter than 33% power, half curve−1.0230.1530
Binomial: more p < .025 than half—0.5000
Binomial: fewer p < .025 than at 33% power—0.3210
  • Selection models correct for one assumed publication mechanism; read the adjusted estimate as a sensitivity analysis, not the truth.
  • The p-curve is inconclusive. p-curve reads only the significant results and says nothing about their size.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Selection models and p-curve (publication bias)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.selection 1.0.2 · spec 0f4bd5606c457350
# Dataset: m1_hackshaw (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 (twins of codesplashr::cs_meta_*)
from codesplash.stats import meta_lab  # selection models and p-curve (twins of codesplashr::cs_meta_selmodel / cs_meta_pcurve)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/m1_hackshaw.parquet", columns=["study", "or", "or_low", "or_high"])
n_input = len(df)
df["study"] = pd.Categorical(df["study"], categories=["Garfinkel 1981", "Hirayama 1984", "Butler 1988", "Cardenas 1997", "Chan 1982", "Correa 1983", "Trichopolous 1983", "Buffler 1984", "Kabat 1984", "Lam 1985", "Garfinkel 1985", "Wu 1985", "Akiba 1986", "Lee 1986", "Koo 1987", "Pershagen 1987", "Humble 1987", "Lam 1987", "Gao 1987", "Brownson 1987", "Geng 1988", "Shimizu 1988", "Inoue 1988", "Kalandidi 1990", "Sobue 1990", "Wu-Williams 1990", "Liu 1991", "Jockel 1991", "Brownson 1992", "Stockwell 1992", "Du 1993", "Liu 1993", "Fontham 1994", "Kabat 1995", "Zaridze 1995", "Sun 1996", "Wang 1996"])  # stored level order
df = df.dropna(subset=["study", "or", "or_low", "or_high"])  # listwise deletion over the analysis columns
df["study"] = df["study"].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, ["study", "or", "or_low", "or_high"])  # infinite values stop the run (registry/errors.yaml)
# %% Studies
design = "ratio_ci"  # inferred from the bound columns
measure = "GEN"
cols = {
    "effect": df["or"].to_numpy(dtype=float),
    "ci_low": df["or_low"].to_numpy(dtype=float),
    "ci_high": df["or_high"].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["study"].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)

# %% Selection model (maximum likelihood)
conf = 0.95
weights = "estimate"
steps = [float(t) for t in [0.025]]
alternative = "greater"
model = "random"
sel = meta_lab.selection_model(y, v, steps=steps, alternative=alternative, model=model, weights=weights, level=conf)
WEIGHTS_LABEL = {"estimate": "weights estimated", "moderate_one": "Vevea–Woods moderate one-tailed weights",
                 "severe_one": "Vevea–Woods severe one-tailed weights", "moderate_two": "Vevea–Woods moderate two-tailed weights",
                 "severe_two": "Vevea–Woods severe two-tailed weights"}[weights]
MODEL_LABEL = ("random effects" if model == "random" else "common effect") + (", 3PSM" if weights == "estimate" and len(sel["steps"]) == 2 and model == "random" else "")
est_delta = weights == "estimate"

# %% p-curve of the significant results
pc = meta_lab.pcurve(y / np.sqrt(v), side=alternative)

# %% Assumptions
assumptions = [
    {"key": "k_studies", "label": "Enough studies", "status": "warn" if (k < 20 and est_delta) else "pass",
     "detail": f"{k} studies" + ("; estimated selection weights are unstable below about 20 studies — compare with fixed Vevea–Woods weights." if k < 20 and est_delta else ".")},
    {"key": "selection_on_p", "label": "Selection acts on p-values", "status": "info",
     "detail": "The model assumes publication depended only on each study's one-sided p-value; other causes of funnel asymmetry are not modeled."},
    {"key": "converged", "label": "Likelihood maximized", "status": "pass" if sel["converged"] else "warn",
     "detail": "Newton iterations converged." if sel["converged"] else "The optimizer stopped before convergence; treat the estimates with caution."},
]

# %% Result
lows, highs = sel["lows"], sel["steps"]
nan = lambda x: None if x is None or (isinstance(x, float) and math.isnan(x)) else x  # noqa: E731
rows_w = [{"interval": f"{lows[j]:g} < p ≤ {highs[j]:g}", "k": int(sel["counts"][j]), "weight": float(sel["delta"][j]),
           "se": nan(float(sel["se_delta"][j])), "low": nan(float(sel["delta_ci_low"][j])), "high": nan(float(sel["delta_ci_high"][j]))}
          for j in range(len(highs))]
rows_m = [
    {"model": "Without selection (ML)", "estimate": float(bt(sel["mu_unadj"])), "low": None, "high": None, "p": None, "tau2": sel["tau2_unadj"]},
    {"model": f"With selection ({WEIGHTS_LABEL})", "estimate": float(bt(sel["mu"])), "low": float(bt(sel["ci_low"])), "high": float(bt(sel["ci_high"])),
     "p": sel["p"], "tau2": sel["tau2"]},
]
rows_t = []
if est_delta:
    rows_t.append({"test": f"Selection (all weights = 1), χ²({sel['lrt_df']})", "statistic": sel["lrt"], "p": sel["lrt_p"]})
if model == "random":
    rows_t.append({"test": "Heterogeneity (τ² = 0), χ²(1)", "statistic": sel["lrt_tau2"], "p": sel["lrt_tau2_p"]})
tables = [
    {"key": "estimates", "title": f"Pooled {DISPLAY_LABEL} with and without selection ({conf:.0%} CI)",
     "columns": [{"key": "model", "label": "Model", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
                 {"key": "low", "label": "CI low", "type": "number"}, {"key": "high", "label": "CI high", "type": "number"},
                 {"key": "p", "label": "p", "type": "number"}, {"key": "tau2", "label": "τ²", "type": "number"}],
     "rows": rows_m},
    {"key": "weights", "title": "Selection weights by one-sided p-value (" + ("estimated; first interval fixed at 1" if est_delta else "fixed a priori") + ")",
     "columns": [{"key": "interval", "label": "Interval", "type": "string"}, {"key": "k", "label": "Studies", "type": "integer"},
                 {"key": "weight", "label": "Weight", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
                 {"key": "low", "label": "CI low", "type": "number"}, {"key": "high", "label": "CI high", "type": "number"}],
     "rows": rows_w},
]
if rows_t:
    tables.append({"key": "lrt", "title": "Likelihood-ratio tests",
                   "columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "χ²", "type": "number"},
                               {"key": "p", "label": "p", "type": "number"}], "rows": rows_t})
charts = []
if est_delta:
    charts.append(cs.chart("weights", "selection-weights", "Estimated selection weights",
                           {"p_low": cs.col("p from", [float(t) for t in lows]), "p_high": cs.col("p to", [float(t) for t in highs]),
                            "weight": cs.col("weight", [float(t) for t in sel["delta"]]), "ci_low": cs.col("CI low", [float(t) for t in sel["delta_ci_low"]]),
                            "ci_high": cs.col("CI high", [float(t) for t in sel["delta_ci_high"]]), "n": cs.col("studies", [float(t) for t in sel["counts"]])},
                           controls={"logP": True, "reference": 1}))
charts.append(cs.chart("funnel", "meta-funnel", "Funnel plot with the selection-adjusted estimate",
                       {"estimate": cs.col(MEASURE_LABEL, [float(t) for t in y]), "se": cs.col("standard error", [float(t) for t in np.sqrt(v)]), "label": cs.col("study", labels)},
                       controls={"center": sel["mu_unadj"], "adjusted": sel["mu"], "contours": True}))
pc_values = {"n_sig": 0, "pc_right_full_p": None, "pc_right_half_p": None, "pc_flat_full_p": None, "pc_flat_half_p": None,
             "pc_binom_right_p": None, "pc_binom_flat_p": None, "pc_verdict": "not run"}
notes = ["Selection models correct for one assumed publication mechanism; read the adjusted estimate as a sensitivity analysis, not the truth."]
if pc is not None:
    pc_values = {"n_sig": pc["n_sig"], "pc_right_full_p": pc["right_full_p"], "pc_right_half_p": pc["right_half_p"], "pc_flat_full_p": pc["flat_full_p"],
                 "pc_flat_half_p": pc["flat_half_p"], "pc_binom_right_p": pc["binom_right_p"], "pc_binom_flat_p": pc["binom_flat_p"], "pc_verdict": pc["verdict"]}
    if pc["n_sig"] > 0:
        tables.append({"key": "pcurve", "title": f"p-curve of {pc['n_sig']} significant result(s) (two-sided p < .05, favored direction)",
                       "columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "z", "label": "Stouffer Z", "type": "number"},
                                   {"key": "p", "label": "p", "type": "number"}],
                       "rows": [{"test": "Right skew, full curve (evidential value)", "z": pc["right_full_z"], "p": pc["right_full_p"]},
                                {"test": "Right skew, half curve (p < .025)", "z": nan(pc["right_half_z"]), "p": nan(pc["right_half_p"])},
                                {"test": "Flatter than 33% power, full curve", "z": pc["flat_full_z"], "p": pc["flat_full_p"]},
                                {"test": "Flatter than 33% power, half curve", "z": nan(pc["flat_half_z"]), "p": nan(pc["flat_half_p"])},
                                {"test": "Binomial: more p < .025 than half", "z": None, "p": pc["binom_right_p"]},
                                {"test": "Binomial: fewer p < .025 than at 33% power", "z": None, "p": pc["binom_flat_p"]}]})
        charts.append(cs.chart("pcurve", "pcurve", "p-curve of the significant results",
                               {"bin": cs.col("p-value", [float(t) for t in pc["bins"]]), "observed": cs.col("observed %", [float(t) for t in pc["observed"]]),
                                "null": cs.col("no effect %", [float(t) for t in pc["expected_null"]]), "power33": cs.col("33% power %", [float(t) for t in pc["expected_33"]])},
                               controls={"k": pc["n_sig"]}))
        verdict_txt = {"evidential": "The significant results are right-skewed: they carry evidential value.",
                       "inadequate": "The significant results are flatter than 33% power would give: evidential value is inadequate.",
                       "inconclusive": "The p-curve is inconclusive."}[pc["verdict"]]
        notes.append(verdict_txt + " p-curve reads only the significant results and says nothing about their size.")
    else:
        notes.append("No study is significant in the favored direction, so there is no p-curve.")
cs.publish({
    "method": "meta.selection",
    "methodVersion": "1.0.2",
    "title": f"Selection model for {k} studies ({MODEL_LABEL})",
    "engine": cs.engine_info("numpy", "scipy"),
    "n": k,
    "summary": f"Adjusted {DISPLAY_LABEL} {bt(sel['mu']):.3g}, {conf:.0%} CI [{bt(sel['ci_low']):.3g}, {bt(sel['ci_high']):.3g}], {cs.fmt_p(sel['p'])} (unadjusted {bt(sel['mu_unadj']):.3g})"
               + (f"; selection LRT {cs.fmt_p(sel['lrt_p'])}." if est_delta else "."),
    "apa": f"adjusted {DISPLAY_LABEL} = {cs.fmt_num(float(bt(sel['mu'])))}, {conf:.0%} CI [{cs.fmt_num(float(bt(sel['ci_low'])))}, {cs.fmt_num(float(bt(sel['ci_high'])))}], {cs.fmt_p(sel['p'])}"
           + (f"; LRT χ²({sel['lrt_df']}) = {cs.fmt_num(sel['lrt'])}, {cs.fmt_p(sel['lrt_p'])}" if est_delta else ""),
    "statistics": [{"key": "est_bt", "label": f"Adjusted {DISPLAY_LABEL}", "value": float(bt(sel["mu"]))}, {"key": "p", "label": "p", "value": sel["p"], "format": "p"},
                   {"key": "est_unadj_bt", "label": f"Unadjusted {DISPLAY_LABEL}", "value": float(bt(sel["mu_unadj"]))}]
                  + ([{"key": "lrt_p", "label": "p (selection)", "value": sel["lrt_p"], "format": "p"}] if est_delta else []),
    "tables": tables,
    "effectSizes": [{"key": "est_bt", "label": f"Adjusted {DISPLAY_LABEL}", "value": float(bt(sel["mu"])), "ciLow": float(bt(sel["ci_low"])), "ciHigh": float(bt(sel["ci_high"])),
                     "ciLevel": conf, "method": f"step-function selection model ({WEIGHTS_LABEL})"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": charts,
    "values": {
        "k": k, "est": sel["mu"], "se": sel["se"], "z": sel["z"], "p": sel["p"], "ci_low": sel["ci_low"], "ci_high": sel["ci_high"],
        "est_bt": float(bt(sel["mu"])), "ci_low_bt": float(bt(sel["ci_low"])), "ci_high_bt": float(bt(sel["ci_high"])),
        "est_unadj": sel["mu_unadj"], "est_unadj_bt": float(bt(sel["mu_unadj"])), "tau2": sel["tau2"], "se_tau2": sel["se_tau2"], "tau2_unadj": sel["tau2_unadj"],
        "ll": sel["ll"], "ll_unadj": sel["ll_unadj"], "lrt": sel["lrt"], "lrt_df": float(sel["lrt_df"]), "lrt_p": sel["lrt_p"],
        "lrt_tau2": sel["lrt_tau2"], "lrt_tau2_p": sel["lrt_tau2_p"],
        "steps": [float(t) for t in sel["steps"]], "counts": [float(t) for t in sel["counts"]], "delta": [float(t) for t in sel["delta"]],
        "delta_se": [float(t) for t in sel["se_delta"]],
        **pc_values,
        "measure": measure, "measure_label": MEASURE_LABEL, "effect_label": DISPLAY_LABEL, "weights_label": WEIGHTS_LABEL, "model_label": MODEL_LABEL,
    },
})

The selection modelSelection modelA meta-analysis model that adds the chance of a study being published, as a function of its p-value, to the usual random-effects model. card shows one weight per interval of one-sided p-values. The first interval is fixed at 1. A weight of 0.5 would mean those studies were half as likely to be published.

The adjusted estimate holds only if publication worked the way the model says. Read it as "if selection looked like this, the effect would be about this large".

04

More intervals, less certainty

Reflect

With three cutpoints instead of one (four intervals), the same studies give an adjusted odds ratio of 1.00, 0.84 to 1.19.

Two reasonable models disagree about whether any effect is left. Write down what you would report, and why one adjusted number would overstate what the data can say.

05

Fixed weights when studies are few

Explore

Estimated weights need roughly 20 studies with some in every interval. With fewer, fix the weights at Vevea and Woods' patternsA priori weight functionsSelection weights fixed in advance at values describing moderate or severe publication bias, instead of estimated from the studies. and watch the estimate.

Moderate one-tailed selection moves the odds ratio from 1.24 to 1.17. Try the severe pattern in the dialog and compare.

06

Do the significant results look real?

Predict

Predict first

Only 7 of Hackshaw's studies are significant in the expected direction. If smoking truly raises risk, which shape should their p-curvep-curveThe distribution of the significant p-values in a set of studies, used to judge whether they come from real effects. have?

Right-skewedFlatRising towards .05
Reveal

Right-skewed: real effects give more p-values below .01 than near .05. Here the right-skew test gives p = .246: with so few results the curve can't tell either way.

07

Priors for few studies

Predict

Predict first

Crins et al. pooled 6 small studies of rejection after pediatric liver transplant. A Bayesian model carries the uncertainty in τ into the interval for μ.

Compared with a random-effects z interval, would you expect the credible interval to be narrower or wider?

NarrowerAbout the sameWider
Reveal

Usually wider. With a half-normal priorHalf-normal priorA prior for the heterogeneity τ that keeps it positive and favors small values; its scale sets how large τ is likely to be. on τ (scale 0.5), the average odds ratio is 0.21, credible intervalCredible interval (meta-analysis)A range that holds the average effect μ with the stated posterior probability, given the studies and the priors. 0.11 to 0.39.

08

Read the posterior

Read
Bayesian meta-analysis of 6 studiesRecorded · Python and R agreeRecorded 2026-11-17 · 35 values compared
R

odds ratio = 0.21, 95% CrI [0.11, 0.39]; τ = 0.34, 95% CrI [0.02, 0.97]

Average odds ratio (median)
0.2073
τ (median)
0.3445
P(μ > 0)
6.013e-5
I² (%)
21.723

Effect size

  • Average odds ratio 0.2073 95% CI [0.1067, 0.3932]

Plots

Shrunken study effects and the average effectHow do the studies' effects compare, and what is the pooled effect and its spread?
View data
odds ratiohighrowstudylow
0.17520.3547studyHeffron (2003)0.0664
0.27760.7870studyGibelli (2004)0.1364
0.18910.4246studySchuller (2005)0.0644
0.19580.3738studyGanschow (2005)0.0962
0.22250.5243studySpada (2006)0.1041
0.19930.5243studyGras (2008)0.0618
0.20730.3932summaryμ (posterior)0.1067
Posterior of μ (log odds ratio)How did the data move belief about the effect, and how much more (or less) plausible is the null value now?
View data
curvedensityμ (log odds ratio)
posterior0.0030−2.890
posterior0.0032−2.877
posterior0.0035−2.865
posterior0.0038−2.852
posterior0.0041−2.839
posterior0.0044−2.826
posterior0.0048−2.813
posterior0.0052−2.801
posterior0.0056−2.788
posterior0.0060−2.775
posterior0.0065−2.762
posterior0.0070−2.750
posterior0.0076−2.737
posterior0.0082−2.724
posterior0.0088−2.711
posterior0.0095−2.698
posterior0.0103−2.686
posterior0.0111−2.673
posterior0.0120−2.660
posterior0.0130−2.647
posterior0.0140−2.635
posterior0.0151−2.622
posterior0.0163−2.609
posterior0.0177−2.596
posterior0.0191−2.583
posterior0.0206−2.571
posterior0.0222−2.558
posterior0.0240−2.545
posterior0.0259−2.532
posterior0.0280−2.520
posterior0.0302−2.507
posterior0.0326−2.494
posterior0.0352−2.481
posterior0.0381−2.468
posterior0.0411−2.456
posterior0.0443−2.443
posterior0.0478−2.430
posterior0.0516−2.417
posterior0.0557−2.405
posterior0.0601−2.392
posterior0.0648−2.379
posterior0.0699−2.366
posterior0.0753−2.353
posterior0.0812−2.341
posterior0.0875−2.328
posterior0.0942−2.315
posterior0.1015−2.302
posterior0.1092−2.290
posterior0.1175−2.277
posterior0.1264−2.264
posterior0.1358−2.251
posterior0.1459−2.238
posterior0.1567−2.226
posterior0.1681−2.213
posterior0.1803−2.200
posterior0.1933−2.187
posterior0.2070−2.175
posterior0.2215−2.162
posterior0.2369−2.149
posterior0.2531−2.136

First 60 of 402 rows.

Posterior of τHow did the data move belief about the effect, and how much more (or less) plausible is the null value now?
View data
curvedensityτ
posterior1.4090
posterior1.4090.0060
posterior1.4100.0121
posterior1.4100.0181
posterior1.4110.0241
posterior1.4120.0301
posterior1.4130.0362
posterior1.4140.0422
posterior1.4150.0482
posterior1.4170.0542
posterior1.4190.0603
posterior1.4210.0663
posterior1.4230.0723
posterior1.4250.0784
posterior1.4270.0844
posterior1.4290.0904
posterior1.4320.0964
posterior1.4340.1025
posterior1.4370.1085
posterior1.4400.1145
posterior1.4420.1205
posterior1.4450.1266
posterior1.4480.1326
posterior1.4510.1386
posterior1.4540.1446
posterior1.4560.1507
posterior1.4590.1567
posterior1.4620.1627
posterior1.4640.1688
posterior1.4670.1748
posterior1.4690.1808
posterior1.4720.1868
posterior1.4740.1929
posterior1.4760.1989
posterior1.4770.2049
posterior1.4790.2109
posterior1.4800.2170
posterior1.4810.2230
posterior1.4820.2290
posterior1.4830.2351
posterior1.4830.2411
posterior1.4830.2471
posterior1.4830.2531
posterior1.4820.2592
posterior1.4820.2652
posterior1.4800.2712
posterior1.4790.2772
posterior1.4770.2833
posterior1.4750.2893
posterior1.4720.2953
posterior1.4690.3014
posterior1.4650.3074
posterior1.4610.3134
posterior1.4570.3194
posterior1.4520.3255
posterior1.4470.3315
posterior1.4420.3375
posterior1.4360.3435
posterior1.4290.3496
posterior1.4220.3556

First 60 of 402 rows.

Assumptions

  • Prior stated and checked — 6 studies with a half-normal (scale 0.5) prior on τ; rerun with another τ prior to see how much it matters.
  • Prior scale fits the measure — τ is on the log odds ratio scale.
  • Independent estimates — One estimate per study is assumed; several outcomes from one study need a multilevel model.

Posterior (95% central credible intervals; priors: τ half-normal (scale 0.5), μ normal (mean 0, SD 4))

MedianMeanLowerUpper
μ (average odds ratio)0.2073—0.10670.3932
τ (heterogeneity)0.3445—0.01770.9730
I² (%)21.723—0.073568.882
θ (a new study's odds ratio)0.2080—0.06250.6588

Study effects shrunken towards μ (odds ratio; posterior median, 95% central interval)

StudyObservedShrunkenLowerUpper
Heffron (2003)0.09930.17520.06640.3547
Gibelli (2004)0.63160.27760.13640.7870
Schuller (2005)0.10000.18910.06440.4246
Ganschow (2005)0.17240.19580.09620.3738
Spada (2006)0.28410.22250.10410.5243
Gras (2008)0.08910.19930.06180.5243

Posterior probability and Bayes factors

Value
P(μ > 0 | data) (ratio above 1)6.013e-5
BF₀₁ for τ = 0 (no heterogeneity)0.8832
BF₀₁ for μ = 0 (no average effect)0.0038
  • Priors: τ half-normal (scale 0.5); μ normal (mean 0, SD 4). Credible intervals are central.
  • Bayes factors use the Savage–Dickey ratio (posterior over prior density at the null) and are shown only when that prior is proper; BF₀₁ above 1 favors the null.
The exact R script · R R version 4.5.1 (2025-06-13)
# Bayesian random-effects meta-analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.bayes 1.0.2 · spec ab1c824d53ece71a
# Dataset: lb1_crins (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_bayes (twins of codesplash.stats.meta / meta_lab)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/lb1_crins.parquet", col_select = c("publication", "events_1", "total_1", "events_2", "total_2")))
n_input <- nrow(df)
df[["publication"]] <- factor(df[["publication"]], levels = c("Heffron (2003)", "Gibelli (2004)", "Schuller (2005)", "Ganschow (2005)", "Spada (2006)", "Gras (2008)"))  # stored level order
df <- df[stats::complete.cases(df[c("publication", "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("publication", "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 <- "OR"
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[["publication"]])
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

# %% Priors
conf <- 0.95
tau_prior <- "half_normal"
tau_scale <- 0.5
mu_prior <- c(0, 4) # normal prior on μ (analysis scale)
interval <- "central"
scaled <- tau_prior %in% c("half_normal", "half_cauchy", "exponential", "uniform")
TAU_LABEL <- paste0(cs_meta_tau_prior_labels[[tau_prior]],
                    if (scaled) sprintf(" (%s %s)", if (tau_prior == "uniform") "upper bound" else "scale", sprintf("%g", tau_scale)) else "")
MU_LABEL <- if (!is.null(mu_prior)) sprintf("normal (mean %s, SD %s)", sprintf("%g", mu_prior[1]), sprintf("%g", mu_prior[2])) else "flat"

# %% Posterior (deterministic quadrature over τ; no Markov chains)
fit <- cs_meta_bayes(y, v, tau_prior = tau_prior, tau_scale = tau_scale, mu_prior = mu_prior, level = conf, interval = interval)
theta <- fit$theta

# %% Assumptions
raw_units <- measure %in% c("MD", "RD", "COR")
assumptions <- list(
  list(key = "prior_sensitivity", label = "Prior stated and checked", status = if (k < 5) "warn" else "info",
       detail = paste0(sprintf("%d studies with a %s prior on τ", k, TAU_LABEL),
                       if (k < 5) "; with this few studies the prior moves the answer — rerun with another prior and report both." else "; rerun with another τ prior to see how much it matters.")),
  list(key = "prior_scale", label = "Prior scale fits the measure", status = if (scaled && raw_units) "warn" else "pass",
       detail = if (scaled && raw_units) sprintf("The τ prior scale %s is in the units of the %s; check it matches plausible heterogeneity in those units.", sprintf("%g", tau_scale), MEASURE_LABEL)
                else sprintf("τ is on the %s scale.", MEASURE_LABEL)),
  list(key = "independence", label = "Independent estimates", status = "info", detail = "One estimate per study is assumed; several outcomes from one study need a multilevel model.")
)

# %% Result
level_txt <- sprintf("%.0f%%", conf * 100)
kind_txt <- if (interval == "central") "central" else "shortest"
na_or <- function(x) if (is.na(x)) NULL else x
g3 <- function(x) format(signif(x, 3))
rows_post <- list(
  list(quantity = sprintf("μ (average %s)", DISPLAY_LABEL), median = bt(fit$mu_median), mean = if (!RATIO && measure != "ZCOR") fit$mu_mean else NULL,
       low = bt(fit$mu_low), high = bt(fit$mu_high)),
  list(quantity = "τ (heterogeneity)", median = fit$tau_median, mean = NULL, low = fit$tau_low, high = fit$tau_high),
  list(quantity = "I² (%)", median = fit$i2_median, mean = NULL, low = fit$i2_low, high = fit$i2_high),
  list(quantity = sprintf("θ (a new study's %s)", DISPLAY_LABEL), median = bt(fit$pred_median), mean = NULL, low = bt(fit$pred_low), high = bt(fit$pred_high))
)
rows_theta <- lapply(seq_len(k), function(i) list(study = labels[i], observed = bt(y[i]), median = bt(theta[[i]]$median),
                                                  low = bt(theta[[i]]$low), high = bt(theta[[i]]$high)))
rows_ev <- list(
  list(quantity = paste0("P(μ > 0 | data)", if (RATIO) " (ratio above 1)" else ""), value = fit$p_mu_positive),
  list(quantity = "BF₀₁ for τ = 0 (no heterogeneity)", value = na_or(fit$bf01_tau)),
  list(quantity = "BF₀₁ for μ = 0 (no average effect)", value = na_or(fit$bf01_mu))
)
gr <- fit$grid
th_med <- vapply(theta, function(t) t$median, numeric(1))
th_lo <- vapply(theta, function(t) t$low, numeric(1))
th_hi <- vapply(theta, function(t) t$high, numeric(1))
forest <- list(
  label = cs_col("study", c(labels, "μ (posterior)")),
  estimate = cs_col(DISPLAY_LABEL, c(bt(th_med), bt(fit$mu_median))),
  low = cs_col("low", c(bt(th_lo), bt(fit$mu_low))),
  high = cs_col("high", c(bt(th_hi), bt(fit$mu_high))),
  kind = cs_col("row", c(rep("study", k), "summary"))
)
density_chart <- function(key, title, x, post, prior, lo, hi, point) {
  has_prior <- all(is.finite(prior))
  xs <- c(x, if (has_prior) x)
  ds <- c(post, if (has_prior) prior)
  cv <- c(rep("posterior", length(x)), if (has_prior) rep("prior", length(x)))
  name <- sub(".* of ", "", title)
  cs_chart(key, "prior-posterior", title, list(x = cs_col(name, xs), density = cs_col("density", ds), curve = cs_col("curve", cv)),
           controls = list(point = point, ci_low = lo, ci_high = hi, cred = conf, bf10 = 0))
}
charts <- list(
  cs_chart("forest", "forest-meta", "Shrunken study effects and the average effect", forest,
           controls = list(reference = if (RATIO) 1 else 0, log = RATIO, piLow = bt(fit$pred_low), piHigh = bt(fit$pred_high))),
  density_chart("mu", sprintf("Posterior of μ (%s)", MEASURE_LABEL), gr$mu, gr$mu_density, gr$mu_prior, fit$mu_low, fit$mu_high, 0),
  density_chart("tau", "Posterior of τ", gr$tau, gr$tau_density, gr$tau_prior, fit$tau_low, fit$tau_high, 0)
)
cs_publish(list(
  method = "meta.bayes",
  methodVersion = "1.0.2",
  title = sprintf("Bayesian meta-analysis of %d studies", k),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = k,
  summary = sprintf("Average %s %s (%s credible interval [%s, %s]); τ = %s [%s, %s]; P(μ > 0) = %.3f.", DISPLAY_LABEL, g3(bt(fit$mu_median)), level_txt,
                    g3(bt(fit$mu_low)), g3(bt(fit$mu_high)), g3(fit$tau_median), g3(fit$tau_low), g3(fit$tau_high), fit$p_mu_positive),
  apa = sprintf("%s = %s, %s CrI [%s, %s]; τ = %s, %s CrI [%s, %s]", DISPLAY_LABEL, cs_fmt_num(bt(fit$mu_median)), level_txt, cs_fmt_num(bt(fit$mu_low)),
                cs_fmt_num(bt(fit$mu_high)), cs_fmt_num(fit$tau_median), level_txt, cs_fmt_num(fit$tau_low), cs_fmt_num(fit$tau_high)),
  statistics = list(
    list(key = "mu_median_bt", label = sprintf("Average %s (median)", DISPLAY_LABEL), value = bt(fit$mu_median)),
    list(key = "tau_median", label = "τ (median)", value = fit$tau_median),
    list(key = "p_mu_positive", label = "P(μ > 0)", value = fit$p_mu_positive),
    list(key = "i2_median", label = "I² (%)", value = fit$i2_median)
  ),
  tables = list(
    list(key = "posterior", title = sprintf("Posterior (%s %s credible intervals; priors: τ %s, μ %s)", level_txt, kind_txt, TAU_LABEL, MU_LABEL),
         columns = list(list(key = "quantity", label = "", type = "string"), list(key = "median", label = "Median", type = "number"),
                        list(key = "mean", label = "Mean", type = "number"), list(key = "low", label = "Lower", type = "number"),
                        list(key = "high", label = "Upper", type = "number")),
         rows = rows_post),
    list(key = "shrinkage", title = sprintf("Study effects shrunken towards μ (%s; posterior median, %s central interval)", DISPLAY_LABEL, level_txt),
         columns = list(list(key = "study", label = "Study", type = "string"), list(key = "observed", label = "Observed", type = "number"),
                        list(key = "median", label = "Shrunken", type = "number"), list(key = "low", label = "Lower", type = "number"),
                        list(key = "high", label = "Upper", type = "number")),
         rows = rows_theta),
    list(key = "evidence", title = "Posterior probability and Bayes factors",
         columns = list(list(key = "quantity", label = "", type = "string"), list(key = "value", label = "Value", type = "number")),
         rows = rows_ev)
  ),
  effectSizes = list(list(key = "mu_median_bt", label = sprintf("Average %s", DISPLAY_LABEL), value = bt(fit$mu_median), ciLow = bt(fit$mu_low),
                          ciHigh = bt(fit$mu_high), ciLevel = conf, method = sprintf("Bayesian random effects (%s credible interval)", kind_txt))),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Priors: τ %s; μ %s. Credible intervals are %s.", TAU_LABEL, MU_LABEL, kind_txt),
               "Bayes factors use the Savage–Dickey ratio (posterior over prior density at the null) and are shown only when that prior is proper; BF₀₁ above 1 favors the null."),
  charts = charts,
  values = list(
    k = k, mu_mean = fit$mu_mean, mu_sd = fit$mu_sd, mu_median = fit$mu_median, mu_low = fit$mu_low, mu_high = fit$mu_high,
    mu_median_bt = bt(fit$mu_median), mu_low_bt = bt(fit$mu_low), mu_high_bt = bt(fit$mu_high),
    tau_median = fit$tau_median, tau_mode = fit$tau_mode, tau_low = fit$tau_low, tau_high = fit$tau_high,
    i2_median = fit$i2_median, i2_low = fit$i2_low, i2_high = fit$i2_high,
    pred_median = fit$pred_median, pred_low = fit$pred_low, pred_high = fit$pred_high,
    pred_median_bt = bt(fit$pred_median), pred_low_bt = bt(fit$pred_low), pred_high_bt = bt(fit$pred_high),
    p_mu_positive = fit$p_mu_positive, bf01_tau = fit$bf01_tau, bf01_mu = fit$bf01_mu,
    theta_mean = vapply(theta, function(t) t$mean, numeric(1)), theta_low = th_lo, theta_high = th_hi,
    measure = measure, measure_label = MEASURE_LABEL, effect_label = DISPLAY_LABEL, tau_prior_label = TAU_LABEL, mu_prior_label = MU_LABEL,
    interval_label = kind_txt, cred_level = conf
  )
))
Python

odds ratio = 0.21, 95% CrI [0.11, 0.39]; τ = 0.34, 95% CrI [0.02, 0.97]

Average odds ratio (median)
0.2073
τ (median)
0.3445
P(μ > 0)
6.013e-5
I² (%)
21.723

Effect size

  • Average odds ratio 0.2073 95% CI [0.1067, 0.3932]

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Prior stated and checked — 6 studies with a half-normal (scale 0.5) prior on τ; rerun with another τ prior to see how much it matters.
  • Prior scale fits the measure — τ is on the log odds ratio scale.
  • Independent estimates — One estimate per study is assumed; several outcomes from one study need a multilevel model.

Posterior (95% central credible intervals; priors: τ half-normal (scale 0.5), μ normal (mean 0, SD 4))

MedianMeanLowerUpper
μ (average odds ratio)0.2073—0.10670.3932
τ (heterogeneity)0.3445—0.01770.9730
I² (%)21.723—0.073568.882
θ (a new study's odds ratio)0.2080—0.06250.6588

Study effects shrunken towards μ (odds ratio; posterior median, 95% central interval)

StudyObservedShrunkenLowerUpper
Heffron (2003)0.09930.17520.06640.3547
Gibelli (2004)0.63160.27760.13640.7870
Schuller (2005)0.10000.18910.06440.4246
Ganschow (2005)0.17240.19580.09620.3738
Spada (2006)0.28410.22250.10410.5243
Gras (2008)0.08910.19930.06180.5243

Posterior probability and Bayes factors

Value
P(μ > 0 | data) (ratio above 1)6.013e-5
BF₀₁ for τ = 0 (no heterogeneity)0.8832
BF₀₁ for μ = 0 (no average effect)0.0038
  • Priors: τ half-normal (scale 0.5); μ normal (mean 0, SD 4). Credible intervals are central.
  • Bayes factors use the Savage–Dickey ratio (posterior over prior density at the null) and are shown only when that prior is proper; BF₀₁ above 1 favors the null.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Bayesian random-effects meta-analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.bayes 1.0.2 · spec ab1c824d53ece71a
# Dataset: lb1_crins (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 (twins of codesplashr::cs_meta_*)
from codesplash.stats import meta_lab  # Bayesian meta-analysis (twin of codesplashr::cs_meta_bayes)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/lb1_crins.parquet", columns=["publication", "events_1", "total_1", "events_2", "total_2"])
n_input = len(df)
df["publication"] = pd.Categorical(df["publication"], categories=["Heffron (2003)", "Gibelli (2004)", "Schuller (2005)", "Ganschow (2005)", "Spada (2006)", "Gras (2008)"])  # stored level order
df = df.dropna(subset=["publication", "events_1", "total_1", "events_2", "total_2"])  # listwise deletion over the analysis columns
df["publication"] = df["publication"].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, ["publication", "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 = "OR"
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["publication"].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)

# %% Priors
conf = 0.95
tau_prior = "half_normal"
tau_scale = 0.5
mu_prior = (0, 4)  # normal prior on μ (analysis scale)
interval = "central"
scaled = tau_prior in ("half_normal", "half_cauchy", "exponential", "uniform")
TAU_LABEL = meta_lab.TAU_PRIOR_LABELS[tau_prior] + (f" ({'upper bound' if tau_prior == 'uniform' else 'scale'} {tau_scale:g})" if scaled else "")
MU_LABEL = f"normal (mean {mu_prior[0]:g}, SD {mu_prior[1]:g})" if mu_prior else "flat"

# %% Posterior (deterministic quadrature over τ; no Markov chains)
fit = meta_lab.bayes(y, v, tau_prior=tau_prior, tau_scale=tau_scale, mu_prior=mu_prior, level=conf, interval=interval)
theta = fit["theta"]

# %% Assumptions
raw_units = measure in ("MD", "RD", "COR")
assumptions = [
    {"key": "prior_sensitivity", "label": "Prior stated and checked", "status": "warn" if k < 5 else "info",
     "detail": f"{k} studies with a {TAU_LABEL} prior on τ" + ("; with this few studies the prior moves the answer — rerun with another prior and report both." if k < 5 else "; rerun with another τ prior to see how much it matters.")},
    {"key": "prior_scale", "label": "Prior scale fits the measure", "status": "warn" if scaled and raw_units else "pass",
     "detail": (f"The τ prior scale {tau_scale:g} is in the units of the {MEASURE_LABEL}; check it matches plausible heterogeneity in those units." if scaled and raw_units
                else f"τ is on the {MEASURE_LABEL} scale.")},
    {"key": "independence", "label": "Independent estimates", "status": "info", "detail": "One estimate per study is assumed; several outcomes from one study need a multilevel model."},
]

# %% Result
level_txt = f"{conf:.0%}"
kind_txt = "central" if interval == "central" else "shortest"
nan = lambda x: None if x is None or (isinstance(x, float) and math.isnan(x)) else x  # noqa: E731
rows_post = [
    {"quantity": f"μ (average {DISPLAY_LABEL})", "median": float(bt(fit["mu_median"])), "mean": fit["mu_mean"] if not RATIO and measure != "ZCOR" else None,
     "low": float(bt(fit["mu_low"])), "high": float(bt(fit["mu_high"]))},
    {"quantity": "τ (heterogeneity)", "median": fit["tau_median"], "mean": None, "low": fit["tau_low"], "high": fit["tau_high"]},
    {"quantity": "I² (%)", "median": fit["i2_median"], "mean": None, "low": fit["i2_low"], "high": fit["i2_high"]},
    {"quantity": f"θ (a new study's {DISPLAY_LABEL})", "median": float(bt(fit["pred_median"])), "mean": None,
     "low": float(bt(fit["pred_low"])), "high": float(bt(fit["pred_high"]))},
]
rows_theta = [{"study": labels[i], "observed": float(bt(y[i])), "median": float(bt(theta[i]["median"])),
               "low": float(bt(theta[i]["low"])), "high": float(bt(theta[i]["high"]))} for i in range(k)]
above = "1" if RATIO else "0"
rows_ev = [
    {"quantity": f"P(μ > 0 | data)" + (" (ratio above 1)" if RATIO else ""), "value": fit["p_mu_positive"]},
    {"quantity": "BF₀₁ for τ = 0 (no heterogeneity)", "value": nan(fit["bf01_tau"])},
    {"quantity": "BF₀₁ for μ = 0 (no average effect)", "value": nan(fit["bf01_mu"])},
]
g = fit["grid"]
forest = {
    "label": cs.col("study", labels + ["μ (posterior)"]),
    "estimate": cs.col(DISPLAY_LABEL, [r["median"] for r in rows_theta] + [float(bt(fit["mu_median"]))]),
    "low": cs.col("low", [r["low"] for r in rows_theta] + [float(bt(fit["mu_low"]))]),
    "high": cs.col("high", [r["high"] for r in rows_theta] + [float(bt(fit["mu_high"]))]),
    "kind": cs.col("row", ["study"] * k + ["summary"]),
}


def density_chart(key, title, x, post, prior, lo, hi, point):
    has_prior = bool(np.all(np.isfinite(prior)))
    xs = [float(t) for t in x] + ([float(t) for t in x] if has_prior else [])
    ds = [float(t) for t in post] + ([float(t) for t in prior] if has_prior else [])
    cv = ["posterior"] * len(x) + (["prior"] * len(x) if has_prior else [])
    return cs.chart(key, "prior-posterior", title, {"x": cs.col(title.split(" of ")[-1], xs), "density": cs.col("density", ds), "curve": cs.col("curve", cv)},
                    controls={"point": point, "ci_low": float(lo), "ci_high": float(hi), "cred": conf, "bf10": 0})


charts = [
    cs.chart("forest", "forest-meta", "Shrunken study effects and the average effect", forest,
             controls={"reference": 1 if RATIO else 0, "log": RATIO, "piLow": float(bt(fit["pred_low"])), "piHigh": float(bt(fit["pred_high"]))}),
    density_chart("mu", f"Posterior of μ ({MEASURE_LABEL})", g["mu"], g["mu_density"], g["mu_prior"], fit["mu_low"], fit["mu_high"], 0.0),
    density_chart("tau", "Posterior of τ", g["tau"], g["tau_density"], g["tau_prior"], fit["tau_low"], fit["tau_high"], 0.0),
]
cs.publish({
    "method": "meta.bayes",
    "methodVersion": "1.0.2",
    "title": f"Bayesian meta-analysis of {k} studies",
    "engine": cs.engine_info("numpy", "scipy"),
    "n": k,
    "summary": f"Average {DISPLAY_LABEL} {bt(fit['mu_median']):.3g} ({level_txt} credible interval [{bt(fit['mu_low']):.3g}, {bt(fit['mu_high']):.3g}]); τ = {fit['tau_median']:.3g} [{fit['tau_low']:.3g}, {fit['tau_high']:.3g}]; P(μ > 0) = {fit['p_mu_positive']:.3f}.",
    "apa": f"{DISPLAY_LABEL} = {cs.fmt_num(float(bt(fit['mu_median'])))}, {level_txt} CrI [{cs.fmt_num(float(bt(fit['mu_low'])))}, {cs.fmt_num(float(bt(fit['mu_high'])))}]; τ = {cs.fmt_num(fit['tau_median'])}, {level_txt} CrI [{cs.fmt_num(fit['tau_low'])}, {cs.fmt_num(fit['tau_high'])}]",
    "statistics": [
        {"key": "mu_median_bt", "label": f"Average {DISPLAY_LABEL} (median)", "value": float(bt(fit["mu_median"]))},
        {"key": "tau_median", "label": "τ (median)", "value": fit["tau_median"]},
        {"key": "p_mu_positive", "label": "P(μ > 0)", "value": fit["p_mu_positive"]},
        {"key": "i2_median", "label": "I² (%)", "value": fit["i2_median"]},
    ],
    "tables": [
        {"key": "posterior", "title": f"Posterior ({level_txt} {kind_txt} credible intervals; priors: τ {TAU_LABEL}, μ {MU_LABEL})",
         "columns": [{"key": "quantity", "label": "", "type": "string"}, {"key": "median", "label": "Median", "type": "number"},
                     {"key": "mean", "label": "Mean", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"},
                     {"key": "high", "label": "Upper", "type": "number"}],
         "rows": rows_post},
        {"key": "shrinkage", "title": f"Study effects shrunken towards μ ({DISPLAY_LABEL}; posterior median, {level_txt} central interval)",
         "columns": [{"key": "study", "label": "Study", "type": "string"}, {"key": "observed", "label": "Observed", "type": "number"},
                     {"key": "median", "label": "Shrunken", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"},
                     {"key": "high", "label": "Upper", "type": "number"}],
         "rows": rows_theta},
        {"key": "evidence", "title": "Posterior probability and Bayes factors",
         "columns": [{"key": "quantity", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
         "rows": rows_ev},
    ],
    "effectSizes": [{"key": "mu_median_bt", "label": f"Average {DISPLAY_LABEL}", "value": float(bt(fit["mu_median"])), "ciLow": float(bt(fit["mu_low"])),
                     "ciHigh": float(bt(fit["mu_high"])), "ciLevel": conf, "method": f"Bayesian random effects ({kind_txt} credible interval)"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Priors: τ {TAU_LABEL}; μ {MU_LABEL}. Credible intervals are {kind_txt}.",
              "Bayes factors use the Savage–Dickey ratio (posterior over prior density at the null) and are shown only when that prior is proper; BF₀₁ above 1 favors the null."],
    "charts": charts,
    "values": {
        "k": k, "mu_mean": fit["mu_mean"], "mu_sd": fit["mu_sd"], "mu_median": fit["mu_median"], "mu_low": fit["mu_low"], "mu_high": fit["mu_high"],
        "mu_median_bt": float(bt(fit["mu_median"])), "mu_low_bt": float(bt(fit["mu_low"])), "mu_high_bt": float(bt(fit["mu_high"])),
        "tau_median": fit["tau_median"], "tau_mode": float(fit["tau_mode"]), "tau_low": fit["tau_low"], "tau_high": fit["tau_high"],
        "i2_median": fit["i2_median"], "i2_low": fit["i2_low"], "i2_high": fit["i2_high"],
        "pred_median": fit["pred_median"], "pred_low": fit["pred_low"], "pred_high": fit["pred_high"],
        "pred_median_bt": float(bt(fit["pred_median"])), "pred_low_bt": float(bt(fit["pred_low"])), "pred_high_bt": float(bt(fit["pred_high"])),
        "p_mu_positive": fit["p_mu_positive"], "bf01_tau": fit["bf01_tau"], "bf01_mu": fit["bf01_mu"],
        "theta_mean": [t["mean"] for t in theta], "theta_low": [t["low"] for t in theta], "theta_high": [t["high"] for t in theta],
        "measure": measure, "measure_label": MEASURE_LABEL, "effect_label": DISPLAY_LABEL, "tau_prior_label": TAU_LABEL, "mu_prior_label": MU_LABEL,
        "interval_label": kind_txt, "cred_level": conf,
    },
})
  • τ has posterior median 0.34, between 0.02 and 0.97.
  • A new study's true odds ratio would fall between 0.06 and 0.66.
  • The shrunken study effects sit closer to μ than the observed ones; small studies move most.
09

Change the prior

Reflect

A heavier-tailed half-Cauchy prior (scale 1, shortest intervals) gives τ = 0.47 and an average odds ratio of 0.20, 0.09 to 0.44.

μ barely moves, τ and the prediction interval do. Which of these would you put in a report, and how would you describe the prior?

10

Every subset of studies

Explore

A GOSH plotGOSH plotA scatter of the pooled estimate against I² for every subset of the studies. fits the model to every subset. For the 13 BCG trials that is 8,191 fits.

Sensitivity of 13 studies: GOSH and draperyRecorded · Python and R agreeRecorded 2026-11-17 · 31 values compared
R

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 estimate0.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)

StudyEstimate shiftI² shift (points)
TPT Madras 19800.467914.399
Hart & Sutherland 1977−0.195412.473
Comstock et al 19740.10193.888
Stein & Aronson 1953−0.09875.859
Rosenthal et al 1961−0.05474.403
Comstock et al 19760.05032.051
Frimodt-Moller et al 19730.04651.007
Ferguson & Simes 1949−0.02782.164
Vandiviere et al 1973−0.02531.888
Coetzee & Berjak 19680.0181−0.6047
Comstock & Webster 19690.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)

EstimateLowHigh
Pooled risk ratio0.48940.34410.6962
Prediction interval—0.13421.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.
The exact R script · R 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
  )
))
Python

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 estimate0.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)

StudyEstimate shiftI² shift (points)
TPT Madras 19800.467914.399
Hart & Sutherland 1977−0.195412.473
Comstock et al 19740.10193.888
Stein & Aronson 1953−0.09875.859
Rosenthal et al 1961−0.05474.403
Comstock et al 19760.05032.051
Frimodt-Moller et al 19730.04651.007
Ferguson & Simes 1949−0.02782.164
Vandiviere et al 1973−0.02531.888
Coetzee & Berjak 19680.0181−0.6047
Comstock & Webster 19690.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)

EstimateLowHigh
Pooled risk ratio0.48940.34410.6962
Prediction interval—0.13421.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.
The exact Python script · Python 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,
    },
})

Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.

Pooled log risk ratios range from −1.62 to 0.45, and TPT Madras 1980 moves them most. Find its subsets in the plot: do they form their own cloud?

11

Every confidence level at once

Read

The same card's drapery plotDrapery plotThe compatibility curve of every study, the pooled estimate and the prediction distribution drawn on one axis. draws each study's p-value function. Where the bold pooled curve crosses p = .05, you read the 95% interval; where it crosses .01, the 99% interval. The shaded prediction curve is far wider, from 0.13 to 1.78 at 95%: the trials disagree about how large the effect is.

12

The code behind the cards

Read
Python
import pandas as pd
from codesplash.stats import meta, meta_lab

d = pd.read_csv("hackshaw.csv")  # columns or, or_low, or_high
es = meta.escalc("ratio_ci", "LOG", {"effect": d["or"], "ci_low": d["or_low"], "ci_high": d["or_high"]})
sel = meta_lab.selection_model(es["yi"], es["vi"], steps=[0.025])
bayes = meta_lab.bayes(es["yi"], es["vi"], tau_prior="half_normal", tau_scale=0.5)
print(sel["mu"], sel["delta"], bayes["mu_median"], bayes["tau_median"])
R
library(codesplashr)
d <- read.csv("hackshaw.csv")
es <- cs_meta_escalc("ratio_ci", "LOG", list(effect = d$or, ci_low = d$or_low, ci_high = d$or_high))
sel <- cs_meta_selmodel(es$yi, es$vi, steps = 0.025)
bayes <- cs_meta_bayes(es$yi, es$vi, tau_prior = "half_normal", tau_scale = 0.5)
c(sel$mu, sel$delta, bayes$mu_median, bayes$tau_median)
13

Check your understanding

Checkpoint

Check yourself

A 3PSM moves a pooled odds ratio from 1.40 to 1.15. What is the most defensible statement?

Show the answer

Answer: b

Selection models correct for one assumed mechanism. Report the adjusted value as a sensitivity analysis next to the ordinary estimate, and show how other weight functions change it.

Check yourself

With five studies, a half-normal and a half-Cauchy prior on τ give clearly different prediction intervals. What should you do?

Show the answer

Answer: b

With few studies the data hold little information about τ, so the prior shapes the answer. Showing two reasonable priors makes that visible.

Check yourself

In a GOSH plot, subsets with one study form a separate cloud with higher I². What follows?

Show the answer

Answer: b

GOSH shows where heterogeneity comes from. A flagged study is a reason to look closer, not a license to delete it.

14

Do it in CodeSplash

In the app

In the Meta-analysis studio, the Small-study effects step has a Selection models tab next to the funnel tests, and Robustness has Bayesian and Subsets (GOSH) tabs. Each starts from the Model step's columns.

15

Recap

Recap
  • Selection models adjust for one assumed publication mechanism; compare several and report the range.
  • p-curve reads only the significant results and asks whether they look real, not how large the effect is.
  • Bayesian pooling carries the uncertainty in τ; state the prior and try another.
  • GOSH and drapery plots show where the answer is fragile. They point to studies to reread, not to drop.

Concepts in this lesson