swaruplab/operon/clinical-biostatistics-power-and-sample-size

Claude Code and agent skill by swaruplab/operon

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Computes sample size and power for clinical trials including continuous, binary, and time-to-event endpoints; superiority, non-inferiority, and equivalence designs; FDA 2016 non-inferiority margin selection with M1/M2 framework; Schoenfeld 1981 and Lakatos 1988 for survival; Schuirmann TOST and 80-125% bioequivalence; minimum clinically important difference (MCID) vs δ distinction. Use when justifying trial size in protocol or SAP per CONSORT 2025 item 7.

Install

npx vskill@latest install swaruplab/operon/clinical-biostatistics-power-and-sample-size

SKILL.md

The same SKILL.md was published earlier as swaruplab/operon/clinical-biostatistics-power-and-sample-size.

Version Compatibility

Reference examples tested with: statsmodels 0.14+, scipy 1.12+, numpy 1.26+, pandas 2.1+. R packages cited: pwr, gsDesign (Anderson/Merck), gsDesign2, rpact (Wassmer/Brannath), presize, npsurvSS, nph, simtrial.

Before using code patterns, verify installed versions match. If versions differ:

  • Python: pip show <package> then help(module.function) to check signatures
  • R: packageVersion('<pkg>') then ?function_name

If code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.

Power and Sample Size for Clinical Trials

"Justify the trial's sample size" -> Compute the n needed to detect a pre-specified alternative δ with power 1-β at significance α, accounting for endpoint distribution, design (superiority/NI/equivalence), expected dropout, multiplicity, and stratification — and distinguish δ (the effect the trial is powered to detect) from MCID (the clinically meaningful difference).

The Foundational Distinction -- δ vs MCID

δ (the alternative effect): what the trial is powered to detect. Usually set above the MCID because sponsors want a strong signal that exceeds noise + design uncertainty.

MCID (Minimum Clinically Important Difference): the smallest effect size considered clinically meaningful. Jaeschke-Singer-Guyatt 1989 Control Clin Trials 10:407 (anchor-based) and Norman-Sloan-Wyrwich 2003 Med Care 41:582 ("the remarkable universality of half a standard deviation") established the modern conventions.

Confusing the two has produced both:

  • Underpowered trials where sponsor sets δ = MCID and gets a CI straddling zero
  • Overgenerous NI margins where sponsor sets M2 = full MCID (NI margin should be a fraction of MCID)

Postdoc rule of thumb: for superiority, δ >= 1.5 × MCID; for NI, M2 <= 0.5 × MCID.

Algorithmic Taxonomy

DesignFormula / approachSoftwareStrengthFails when
Two-sample t-test, continuousCohen's d; n = 2 × (z_α/2 + z_β)² / d²pwr::pwr.t.test (R); statsmodels.power.tt_ind_solve_power (Py)StandardHeteroscedasticity; non-normal outcomes
Two-sample proportions (Fleiss)Asymptotic normal approximation with/without continuity correctionpower.prop.test (R) -- uncorrected; pwr::pwr.2p.test; statsmodelsStandardn < 100/arm: continuity correction debate (D'Agostino 1988)
Survival (Schoenfeld 1981)events ≈ 4(z_α/2 + z_β)² / (log HR)² for 1:1gsDesign::nSurv; npsurvSS::size_two_armStandard PH-conformantPH violated (immuno-oncology) under-estimates by 20-50%
Survival under non-PH (Lakatos 1988)Markov chain accommodating time-varying HR, accrual, dropoutgsDesign::nSurv; npsurvSS; simtrialHandles immuno-oncology delayed effectsRequires explicit specification of HR(t) and accrual
MaxCombo SS under NPHSimulation-based; pre-specify weight familynphRCT; simtrialRobust to NPH patternComputationally heavier
Non-inferiority fixed-marginn = (z_α + z_β)² × variance / M²pwr::pwr.t2n.test adapted; rpact::getSampleSizeMeansPre-discounted MConstancy assumption violation invisible
Non-inferiority synthesisPool historical control-vs-placebo + current test-vs-controlgsDesign::ssTwoArmTestMore efficient than fixed-marginConstancy assumption MUST hold exactly
Equivalence TOSTTwo one-sided tests at α eachpwr::pwr.t.test adapted; presizeNo multiplicity adjustment neededWrong question when superiority/NI is intended
Group-sequentialLan-DeMets spending functionrpact; gsDesignInterim analyses; early stoppingMore complex SAP
Sample-size re-estimation (Mehta-Pocock)Promising-zone conditional powerrpact::getSampleSizeMeans with reestimationRecovers power if interim shows promiseUnblinded SSR scares FDA
Cluster-randomisedAdjust for design effect = 1 + (m-1)ICCclusterPower; pwr adaptedStandardICC misspecification

Postdoc reading list:

  • Fleiss JL 1981 Statistical Methods for Rates and Proportions (with/without continuity correction tables)
  • Schoenfeld DA 1981 Biometrika 68:316 (canonical TTE formula)
  • Lakatos E 1988 Biometrics 44:229 (Markov chain SS for complex survival)
  • Schuirmann DJ 1987 J Pharmacokinet Biopharm 15:657 (TOST)
  • Jaeschke R, Singer J, Guyatt GH 1989 Control Clin Trials 10:407 (MCID anchor-based)
  • Norman GR, Sloan JA, Wyrwich KW 2003 Med Care 41:582 (0.5 SD heuristic)
  • Snapinn SM 2000 Curr Control Trials Cardiovasc Med 1:19 (NI biocreep)
  • Temple R, Ellenberg SS 2000 Ann Intern Med 133:455 + 133:464 (NI assay sensitivity; Ann Intern Med NOT NEJM — common citation error)
  • Hung HMJ, Wang SJ, O'Neill RT 2005 Biom J (NI within-trial Type-I not guaranteed)
  • Mehta CR, Pocock SJ 2011 Stat Med 30:3267 (promising zone)
  • Lin RS, Lin J, Roychoudhury S et al 2020 Stat Biopharm Res (NPH Working Group)

Decision Tree by Scenario

ScenarioRecommended approachWhy
Continuous outcome, two-arm parallel, superiorityFleiss / Cohen's d formula via power.t.test or statsmodelsStandard; cite Fleiss 1981
Binary outcome, n > 100/armUncorrected normal approximation via power.prop.test; statsmodels power_proportions_2indepAdequate for n > 100
Binary outcome, n < 100/armFisher exact-based simulation OR Fleiss with continuity correctionContinuity correction debate; cite D'Agostino 1988 if uncorrected
Time-to-event with PHSchoenfeld 1981 via gsDesign::nSurvStandard; pre-specify hazards
Time-to-event under expected NPH (immuno-oncology)Lakatos 1988 OR simulation via simtrial::simtrial/nphRCTSchoenfeld under-estimates by 20-50%; cite Lin 2020
Non-inferiority continuousFixed-margin with M2 = 0.5 × historical M1 (discounted)FDA 2016 NI guidance; cite Temple-Ellenberg 2000
Non-inferiority binaryFixed-margin with Miettinen-Nurminen CI for RDCite EMA NI guidance; MN-CI standard
Bioequivalence (Cmax/AUC)TOST with 80-125% margins on geometric mean ratioFDA 1992 BE guidance; Schuirmann 1987
Cluster-randomisedn × design effect = 1 + (m-1)ICCCite Murray 1998 cluster RCT methodology
Group-sequentialLan-DeMets spending functionrpact or gsDesign
Pilot for sample size re-estimationBlinded SSR (Friede-Kieser 2006)No Type-I inflation; safer than unblinded
Promising-zone reestimationMehta-Pocock 2011 with pre-specified increase ruleRecovers power; cite caveat re Jennison-Turnbull 2015 critique

Continuous Outcomes -- Two-Sample t-Test

python
from statsmodels.stats.power import tt_ind_solve_power
# Solve for n per group
n = tt_ind_solve_power(
effect_size=0.5, # Cohen's d = (mu1 - mu2) / sigma
alpha=0.05,
power=0.80,
alternative='two-sided'
)
print(f'n per arm = {np.ceil(n):.0f}')
# Solve for power given n
power = tt_ind_solve_power(effect_size=0.5, alpha=0.05, nobs1=100, alternative='two-sided')

Cohen's d benchmarks: small = 0.2, medium = 0.5, large = 0.8. Choose d to detect based on prior literature or clinically meaningful effect, NOT post-hoc to fit the affordable n.

Inflate for dropout: if dropout rate is q, multiply final n by 1/(1-q). For q=0.20, n_total = n/0.80.

Stratified randomisation efficiency: if randomisation stratifies on prognostic factors with combined R² = r against outcome, the effective n is n/(1-r²). Senn 2013 Stat Med 32:1439 makes the precision argument explicit.

Binary Outcomes -- The Continuity Correction Debate

python
from statsmodels.stats.power import NormalIndPower
import math
# Without continuity correction
p1, p2 = 0.30, 0.20
pbar = (p1 + p2) / 2
z_alpha = 1.96 # two-sided alpha=0.05
z_beta = 0.84 # power=0.80
n = ((z_alpha * math.sqrt(2 * pbar * (1 - pbar)) +
z_beta * math.sqrt(p1 * (1 - p1) + p2 * (1 - p2))) / (p1 - p2)) ** 2
print(f'n per arm (uncorrected) = {math.ceil(n)}')
# Continuity-corrected (Fleiss formula)
correction = (1 + math.sqrt(1 + 4 / (n * abs(p1 - p2)))) ** 2 / 4
n_corrected = math.ceil(n * correction)
print(f'n per arm (continuity corrected) = {n_corrected}')

The continuity correction debate (D'Agostino, Casagrande, Pike 1988 Stat Med 7:347):

  • Pro (Fleiss, Yates): better matches the exact distribution under H0
  • Con: overly conservative, wastes ~10% sample size; modern computing makes exact (Fisher-Irwin, Boschloo) tests feasible

R's `power.prop.test` uses uncorrected normal approximation — can over-state power 5-10% in small samples (n<100). For confirmatory work with n<100, use simulation-based SS via simr or presize.

Survival (Time-to-Event)

Schoenfeld 1981 -- the canonical formula
python
import math
# Events needed for two-sample log-rank under PH (Schoenfeld 1981)
from scipy.stats import norm
def schoenfeld_events(hr, alpha=0.05, power=0.80, allocation_ratio=1.0, two_sided=True):
"""
events = (z_crit + z_beta)^2 / (p*(1-p) * log(HR)^2)
where z_crit = z_{1-alpha/2} for two-sided test OR z_{1-alpha} for one-sided.
"""
z_crit = norm.ppf(1 - alpha/2) if two_sided else norm.ppf(1 - alpha)
z_beta = norm.ppf(power)
p = 1 / (1 + allocation_ratio)
return math.ceil((z_crit + z_beta) ** 2 / (p * (1 - p) * math.log(hr) ** 2))
# For HR=0.70, alpha=0.05 two-sided, 80% power, 1:1 -> approx 247 events
events_needed = schoenfeld_events(hr=0.70)
print(f'Events needed for HR=0.70: {events_needed}')

Events drive power, not subjects. Convert to n via expected event rate and follow-up:

python
# n needed = events / overall event probability over follow-up
expected_overall_event_prob = 0.40 # from pilot or historical
n_per_arm = math.ceil(events_needed / (2 * expected_overall_event_prob))
# Inflate for dropout
n_per_arm_with_dropout = math.ceil(n_per_arm / (1 - 0.15)) # 15% dropout
Lakatos 1988 -- complex survival

Use R gsDesign::nSurv() or npsurvSS::size_two_arm() for complex scenarios with:

  • Time-varying hazard ratios (delayed effect)
  • Non-uniform accrual
  • Different dropout rates per arm
  • Cure fractions
r
library(gsDesign)
n_lakatos <- nSurv(
lambdaC = 0.04, # control hazard per month
hr = 0.70, # treatment HR
eta = 0.005, # dropout hazard per month
T = 24, # total study duration in months
minfup = 12, # minimum follow-up
accrualTime = 12, # accrual duration
alpha = 0.025, # one-sided
beta = 0.10 # power = 90%
)
print(n_lakatos)
Under non-PH (immuno-oncology with delayed effect)

Schoenfeld 1981 ASSUMES PH. Under immuno-oncology with delayed separation, the formula under-estimates required events by 20-50%. The fix:

r
# Simulate under expected hazard pattern (Lin 2020 NPH Working Group recommendation)
library(simtrial)
sim_result <- simtrial(
n_per_arm = 250,
enroll_rate = piecewise_enroll(),
fail_rate = piecewise_fail( # delayed-effect specification
duration = c(6, 18),
fail_rate = c(0.04, 0.04), # control
hr = c(1.0, 0.5), # treatment HR is 1 for first 6 months, then 0.5
dropout_rate = c(0.005, 0.005)
),
total_duration = 36
)
# Compute empirical power via MaxCombo or weighted log-rank

Non-Inferiority Designs -- The FDA 2016 Framework

FDA NI Trials Guidance (November 2016) establishes the canonical M1/M2 framework:

  • M1 = entire effect of active control vs placebo (lower bound of CI from historical meta-analysis)
  • M2 = clinically acceptable loss, typically M1/2 (50% effect retention) but as conservative as M1/4 for mortality endpoints

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
99
Repository forks
11
7-day trend score
28

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/swaruplab/operon/clinical-biostatistics-power-and-sample-size/badge)](https://verified-skill.com/skills/swaruplab/operon/clinical-biostatistics-power-and-sample-size)

Something wrong with this skill or its page? Tell us.