Work out how big the sample must be
estimate-sample-size
Computes the sample a test needs to detect a planned effect, or the smallest effect a fixed sample can detect.
What this adds: every number comes from `scripts/power_calc.py`, command shown; the smallest detectable effect beside the required sample; named multipliers for groups, take-up, attrition, and covariates; a sensitivity table for guessed inputs; Type S and M risk when underpowered; a verdict that never raises the effect to fit the budget.
Expert reviews are for staff at The Agency Fund and Irrational Labs; anyone can rate.
Skill
The instructions your AI follows when this skill runs. Installing the skill gives it this file and everything in the other tabs.
SKILL.mdView on GitHub
Takes in
effect-size-benchmarkEffect-size benchmarkFrom estimate-expected-effectevaluation-designEvaluation designFrom choose-trial-designProduces
power-calculationPower calculationInstall
/plugin marketplace add agency-fund/besci-skills/plugin install besci-skills@besci-skillsnpx skills add agency-fund/besci-skills --skill estimate-sample-sizeDownload estimate-sample-size.skill
Upload the file under Settings → Capabilities → Skills. Zip installs do not update themselves; check What's new now and then.
What it does
Computes the sample a test needs to detect a planned effect, or the smallest effect a fixed sample can detect.
What this adds: every number comes from scripts/power_calc.py, command shown; the smallest detectable effect beside the required sample; named multipliers for groups, take-up, attrition, and covariates; a sensitivity table for guessed inputs; Type S and M risk when underpowered; a verdict that never raises the effect to fit the budget.
When to use it
Use it when
- Someone asks "how many people do we need?", "how many clinics or villages?", or "is our sample big enough?"
- A funder, ethics board, or registry asks for a power calculation
- The sample is fixed by budget and the team asks what it could detect
Do not use it when
- Nobody has decided what effect to plan on, or the only number is a published headline; use
estimate-expected-effect - The unit of randomization is still open ("people or villages?"); use
choose-trial-design
Before you start
Ask these before producing the calculation. Do not ask anything the user has already answered.
- Required. The effect to plan on, with its unit, and whether it is the expected effect or the smallest worth acting on.
- Required. The outcome's baseline: the control-group rate for a yes-or-no outcome, or the mean and standard deviation (SD), with their source.
- Required. The unit of randomization; for groups (villages, clinics), the number measured per group and any intracluster correlation (ICC: the share of outcome variation lying between groups).
- Required. The feasible sample the program can reach and afford.
- Optional. Take-up in each arm; attrition (people lost before measurement); the share of variation a baseline measure explains (R²); alpha and power (the chance of detecting a true effect), if a protocol fixed them.
If 1, 2, or 3 is missing, ask and stop. If 4 is missing, mark the verdict "not assessed". For anything in 5, assume full take-up, no attrition, no covariates, alpha 0.05 two-sided, and power 0.80, labeled as assumptions.
What it draws on
- Gupta, S., & Kopper, S. (2021). Power calculations. J-PAL Research Resources. https://www.povertyactionlab.org/resource/power-calculations Supports: the script's formulas, including the design effect 1 + (m − 1) × ICC and dilution by take-up; taking the ICC from data "preferably in the same or a similar population"; the sensitivity table.
- Kettle, S., & Persian, R. (2022). Target, Explore, Solution, Trial, Scale: An introduction to running simple behavioural insights projects. The Behavioural Insights Team. https://www.bi.team/wp-content/uploads/2022/11/BIT-Handbook-How-to-run-simple-BI-projects.pdf Supports: running the calculation both ways, and strengthening the intervention, enlarging the sample, or accepting less power when the detectable effect is unrealistic.
- Gelman, A., & Carlin, J. (2014). Beyond power calculations. Perspectives on Psychological Science, 9(6), 641–651. https://doi.org/10.1177/1745691614551642 Supports: the Type S and Type M report.
Where the evidence comes from: The arithmetic makes no claim about how people behave; its inputs are local. One ICC compilation uses national samples of US schools; others, for school achievement in 15 sub-Saharan African countries and perinatal outcomes in India, Bangladesh, and Malawi, find the ICC varies with the outcome, its prevalence, and cluster size. The script's default ICC range, 0.01 to 0.20, comes from no compilation.
Replication status: Not applicable; the formulas are standard approximations, and the script's normal approximation understates the sample when groups are few.
How to do it
- Fill the inputs table, each value with its source; label any input without one an assumption.
- Run
python3 scripts/power_calc.pyand paste the command and output. Never do the arithmetic yourself; the printed multipliers let a reader check it.- Yes-or-no outcome:
--outcome binary --p0 <control rate> --p1 <rate with the effect>; for a decrease add--direction decrease. - Measured outcome:
--outcome continuous --effectin SD, or in raw units with--sd. - Groups:
--iccand--cluster-size. Report groups per arm; more groups raise power more than more people per group. --takeup,--control-takeup,--attrition,--r2. State each multiplier in words: half take-up means four times the sample.
- Yes-or-no outcome:
- If the sample is fixed, add
--n-per-armor--clusters-per-armand report the minimum detectable effect (the smallest true effect detected at the stated power), in units and SD, beside the planned effect. - Add
--sensitivitywhenever the ICC, take-up, or effect is a guess. Cells whose rate would fall outside 0 to 1 print "n/a". - If the expected effect is below the detectable one, add
--true-effect. Report the power, the chance a significant result has the wrong sign (Type S), and how much it would overstate the truth (Type M). - Give the verdict: "can detect" or "cannot detect the planned effect with the feasible sample", with what would change it: more groups rather than bigger ones, a baseline measure, higher take-up, a stronger intervention, or not testing. Never raise the effect to fit the sample.
See references/worked-example.md for a complete run.
Output template
<Two or three plain sentences to the user: whether the feasible sample can detect the planned effect, the input the answer moves on most, and, if it cannot, the option that would change that most.>
# How big the sample must be: <test>
**Design:** <individual or group randomized; arms; allocation>
**Effect planned on:** <value, unit>; <expected effect / smallest effect worth acting on>, from <source>
## Inputs
| Input | Value | Source |
|---|---|---|
| Alpha, two-sided (the accepted chance of a false alarm) | <0.05> | <convention / protocol> |
| Power (the chance of detecting a true effect) | <0.80> | <convention / protocol> |
| Outcome, baseline | <yes-or-no, control rate / measured, mean and SD> | <...> |
| People per group | <...> | <...> |
| ICC (how alike people in one group are) | <value, or "no local estimate; range used"> | <...> |
| Take-up (treatment, control) | <...> | <...> |
| Attrition (people lost before measurement) | <...> | <...> |
| Covariate R² (the share of variation a baseline measure explains) | <...> | <...> |
## Calculation
- Script: `python3 scripts/power_calc.py <arguments>`
- Sample per arm before adjustments: <n>
- Multipliers: design effect for randomizing groups <...>; take-up ÷ <...>; attrition ÷ <...>; covariates × <...>
- **Required:** <n enrolled per arm>; <groups per arm, if grouped>
## Smallest effect the feasible sample can detect (minimum detectable effect)
<feasible sample>: <value, unit> (<SD>), against a planned effect of <...>
## Sensitivity: how the answer moves with the guesses
| ICC \ effect | <...> | <...> | <...> | <...> |
|---|---|---|---|---|
| <...> | <groups or people per arm> | <...> | <...> | <...> |
## Wrong sign and exaggeration (Type S and Type M risk), when the expected effect is below the detectable effect
At a true effect of <...>: power <...>; chance a significant result has the wrong sign <...>; exaggeration <...>
## Verdict
<Can / Cannot> detect the planned effect with the feasible sample, because <...>. Options that change it: <...>
## What to check before relying on this
- <the ICC source, or that none exists>
- <the baseline or SD source>
- <the take-up and attrition assumptions>
## Where you could go from here
<One line saying the calculation is done.>
<Two or three next moves that fit what this run found, each with why it would help and when it fits. Candidates:
- `estimate-expected-effect`, when the effect planned on is a published headline or a guess and the verdict hinges on it
- `choose-trial-design`, when the verdict is "cannot detect" and a different unit, such as more and smaller groups, is worth weighing
- `write-pre-analysis-plan`, when the sample is settled and the analysis, including any covariate counted on here, should be fixed before the data arrive
- `design-pilot-feasibility-study`, when take-up, attrition, or the baseline is a guess that a pilot could measure before the main trial
- a baseline survey or the program's own records, when there is no local ICC or baseline and the answer moves most on it
- a statistician, when fewer than 30 groups are feasible, the outcome is rare, or the design is not two equal arms>
Questions you could ask next: "<question>" · "<question>"
How to talk with the user
- If the user asked a question rather than asked for this skill's output, answer the question first, in a few plain sentences. Then offer the run and say what it would add.
- Mark the run. When it starts, say so in one line: the skill, and what it will produce. When the output is done, say the run is finished. The user should always know when the library's method is in force.
- Talk with the person, not at them. Use their words for their program and the people in it, say why you ask each question, and say what you are unsure of. No praise, no filler.
- Say where each claim comes from: this skill's sources, your general knowledge, or nothing in the library. A number the sources do not give, such as how many interviews to run, is your judgment; say so, and why you chose it.
- End with the template's closing: two or three next moves that fit what this run found, each with its reason and when it fits, and one or two questions the user could ask next. Say which move you would lean toward and why; the user decides.
Where it goes wrong
- Counting people instead of groups. Four clinics per arm with 300 clients each is not a trial of 2,400 people; above an ICC of zero, the clinics set the power.
- A borrowed ICC used as fact. One figure from another country or outcome, with no range, hides the input the answer moves most on.
- Reading "powered" as "will find it". At power 0.80, one test in five misses a true effect of the planned size, and in an underpowered test the significant results are the overstated ones.
When to bring in a specialist
Tell the user to consult a statistician or an evaluation methodologist when:
- Fewer than 30 groups are feasible; with 10, the script understates the sample by about 30%
- The outcome is rare (baseline below 5% or above 95%), a count, or a time until an event
- The design is stepped-wedge, factorial, or has unequal arms or group sizes; the script assumes two equal arms of equal groups
- An ethics board or registry will review the calculation
Bring them: the inputs table, the script output, the sensitivity table, and the design.
Cite this skill
Zezhen Wu (2026). Work out how big the sample must be (version 0.3.0) [AI skill]. Behavioral Science Skills Library, The Agency Fund and Irrational Labs. https://besci-skills.vercel.app/skills/estimate-sample-size/Skills are fixed, versioned artifacts. Record the skill name and version in your project documentation the way you would register analysis code. See how to cite skills and workflows, which follows Busara's SIFA framework for stating how humans and AI contributed.
Using this skill inside a commercial AI product sends what you type to that product's provider. Do not paste sensitive personal or proprietary data without understanding the product's terms. Read the disclosure.
Test cases
Realistic requests used to check this skill, each paired with what a good answer must contain. Maintainers rerun them with besci-eval when the skill or the AI model changes. They also show the kind of request the skill is built for.
evals/evals.jsonView on GitHub
Test case 1: Full run
The request
We are testing community-led total sanitation triggering in a district in East Nusa Tenggara, Indonesia. Villages will be randomized to two arms, and we will survey 40 households per village. The outcome is whether a household uses an improved latrine at 12 months, verified in the survey; the district health office puts the baseline at 35%. Our effect-size benchmark says to plan on 6 percentage points, the smallest effect worth acting on, with a central expected effect of 8. We have no local intracluster correlation. Triggering reaches every assigned village; we expect 10% of households not to be found at endline, and we will use baseline latrine ownership as a covariate, with an R-squared around 0.10. We can afford 60 villages. How many do we need, and what can 60 detect?
What a good answer includes
A power calculation in the output template, with the script command and output, that finds 60 villages cannot detect 6 points.
Checks on the answer
- Shows the power_calc.py command and its output rather than arithmetic done by hand.
- Reports the villages needed per arm at the assumed ICC, with the design effect, and the minimum detectable effect for 30 villages per arm (about 9.6 points).
- Includes a sensitivity table over several ICC values, saying no local ICC exists.
- Reports Type S or Type M risk for a true effect of 6 points.
- Concludes that 60 villages cannot detect 6 points and does not raise the planned effect to make them enough.
- Ends with two or three next moves, each with its reason, and questions the user could ask next, with no single instruction.
Test case 2: Missing context
The request
How many people do we need for our SMS trial?
What a good answer includes
The skill asks for the effect to plan on, the outcome's baseline, and the unit of randomization, and computes nothing.
Checks on the answer
- Asks for the effect to plan on, with its unit.
- Asks for the outcome's baseline rate, or its mean and standard deviation.
- Asks whether people or groups will be randomized.
- Gives no sample size and no minimum detectable effect.
- Says why it needs these answers.
Test case 3: Near the escalation point
The request
We can randomize 8 health centers in Zambia, 4 per arm, about 300 clients each, to test whether community health agents offering HIV self-test kits raise kit uptake. Uptake today is about 4% of clients. We would be happy to detect a 2-point increase. Can we?
What a good answer includes
The skill runs the script, shows that 4 centers per arm cannot detect 2 points, and tells the user to consult a statistician because the groups are few and the outcome is rare.
Checks on the answer
- Shows the script command and reports the minimum detectable effect for 4 centers per arm.
- Concludes that the feasible design cannot detect a 2-point increase.
- Says that fewer than 30 groups make the script's figure optimistic, or that a 4% baseline is a rare outcome the formula handles poorly.
- Tells the user to consult a statistician or an evaluation methodologist.
- Says what to bring to that specialist.
Test case 4: Wrong skill
The request
For the fertilizer-timing SMS in Western Kenya, should we randomize individual farmers or whole farmer groups?
What a good answer includes
The skill says choosing the unit of randomization is a design decision and points to the skill for it.
Checks on the answer
- Says the question is the unit of randomization.
- Names choose-trial-design.
- Does not produce a power calculation.
References
Longer material the skill opens only when a step calls for it, which keeps the main instructions short.
references/View on GitHub
- Worked example: village-randomized sanitation triggering in Indonesia
references/worked-example.mdA full run of the skill on a realistic case, showing the output it should produce. - Evidence: Work out how big the sample must be
references/evidence.mdThe sources behind the skill: what each supports, where the evidence has been tested, and what to check locally.
Worked example: village-randomized sanitation triggering in Indonesia
A full run of the skill on a realistic case, showing the output it should produce.
A full run of the skill on a realistic case, showing the output it should produce. The case is illustrative, not a real program.
The request
"We are testing community-led total sanitation triggering in a district in East Nusa Tenggara, Indonesia. Villages will be randomized to two arms, and we will survey 40 households per village. The outcome is whether a household uses an improved latrine at 12 months, verified in the survey; the district health office puts the baseline at 35%. Our effect-size benchmark says to plan on 6 percentage points, the smallest effect worth acting on, with a central expected effect of 8. We have no local intracluster correlation. Triggering reaches every assigned village; we expect 10% of households not to be found at endline, and we will use baseline latrine ownership as a covariate, with an R² around 0.10. We can afford 60 villages. How many do we need, and what can 60 detect?"
The output
Sixty villages are not enough to detect the 6-point effect you plan on: at the assumed ICC of 0.05 it needs 76 villages per arm, and 30 per arm can detect about 9.6 points. The answer rests most on the ICC, which is a guess here; across the range tested, the villages needed move by a factor of six. The options below would change the verdict, and none of them assumes a bigger effect.
# How big the sample must be: sanitation triggering, East Nusa Tenggara
**Design:** randomized by village; two arms; 1:1; 40 households surveyed per village
**Effect planned on:** 6 percentage points; the smallest effect worth acting on, from the team's effect-size benchmark (central expected effect 8 points)
## Inputs
| Input | Value | Source |
|---|---|---|
| Alpha, two-sided (the accepted chance of a false alarm) | 0.05 | Convention (assumption) |
| Power (the chance of detecting a true effect) | 0.80 | Convention (assumption) |
| Outcome, baseline | Yes-or-no; 35% use an improved latrine | District health office records |
| People per group | 40 households per village | Survey plan |
| ICC (how alike people in one group are) | No local estimate; 0.05 used, 0.01 to 0.20 in the sensitivity table | Assumption |
| Take-up (treatment, control) | 1.0, 0 | Triggering reaches every assigned village |
| Attrition (people lost before measurement) | 0.10 | Team's estimate (assumption) |
| Covariate R² (the share of variation a baseline measure explains) | 0.10 | Baseline latrine ownership (assumption) |
## Calculation
- Script: `python3 scripts/power_calc.py --outcome binary --p0 0.35 --p1 0.41 --icc 0.05 --cluster-size 40 --attrition 0.10 --r2 0.10 --clusters-per-arm 30 --sensitivity --true-effect 0.06`
- Sample per arm before adjustments: 1,026.2
- Multipliers: design effect for randomizing groups 1 + (40 − 1) × 0.05 = 2.95; take-up ÷ 1.0; attrition ÷ 0.90; covariates × 0.90
- **Required:** 3,028 households enrolled per arm; 76 villages per arm (152 in total)
## Smallest effect the feasible sample can detect (minimum detectable effect)
30 villages per arm (1,200 households enrolled per arm): 9.6 percentage points (0.20 SD of the baseline outcome), against a planned effect of 6
## Sensitivity: how the answer moves with the guesses
Villages needed per arm:
| ICC \ effect | 3.0 points | 4.5 points | 6.0 points | 9.0 points |
|---|---|---|---|---|
| 0.01 | 141 | 63 | 36 | 17 |
| 0.05 | 299 | 134 | 76 | 35 |
| 0.10 | 496 | 222 | 126 | 57 |
| 0.20 | 890 | 399 | 226 | 102 |
Detectable effect with 30 villages per arm, by ICC: 6.5 points at 0.01; 9.6 at 0.05; 12.4 at 0.10; 16.7 at 0.20.
## Wrong sign and exaggeration (Type S and Type M risk), when the expected effect is below the detectable effect
At a true effect of 6 points: power 0.42; chance a significant result has the wrong sign 0.000; exaggeration 1.52, so a significant result would overstate a true 6-point effect by about half. At the central expected effect of 8 points: power 0.65; exaggeration 1.24.
## Verdict
Cannot detect the planned effect with the feasible sample, because at an ICC of 0.05 a 6-point effect needs 76 villages per arm and 30 per arm detect 9.6 points. Options that change it: fund 152 villages; collect a fuller baseline to raise R² above 0.10; accept that 60 villages can confirm only an effect of about 10 points or more, and say so in the registration; or run a smaller study of feasibility instead of the effect test. Spreading the same budget across more, smaller villages helps only a little: 50 villages per arm at 20 households detect 8.5 points.
## What to check before relying on this
- The ICC. A baseline survey of latrine use in 20 villages would replace the 0.01 to 0.20 range with an estimate; across that range the villages needed move by a factor of six.
- The 35% baseline, which comes from administrative records that may overstate use compared with a verified survey.
- The 10% attrition, which is the team's estimate rather than a figure from an earlier round.
## Where you could go from here
That's the calculation.
- Measure the ICC with a baseline survey of latrine use in 20 villages: at 6 points the villages needed run from 36 to 226 per arm across the range tested, so this one figure decides whether 60 villages are close or far off. The same survey would check the 35% baseline against verified use.
- Take the options in the verdict to whoever holds the budget: funding 152 villages and registering that 60 can confirm only about 10 points are different decisions, and the district or the funder has to make them.
- If the 60-village study goes ahead, fix the analysis with `write-pre-analysis-plan`: it is where to state, before any data arrive, that the study can confirm only an effect of about 10 points or more, and to name the baseline covariate counted on here.
I'd lean toward the ICC survey, because the verdict rests on a number that is a guess today, and the survey checks the baseline at the same time.
Questions you could ask next: "What would a smaller feasibility study look like instead of the effect test?" · "How do we explain to the funder that 60 villages can confirm only about 10 points?"
Evidence: Work out how big the sample must be
The sources behind the skill: what each supports, where the evidence has been tested, and what to check locally.
Sources
The task is a named step or tool in these guides:
- Gupta, S., & Kopper, S. (2021). Power calculations. J-PAL Research Resources. https://www.povertyactionlab.org/resource/power-calculations Supports: the formulas in
scripts/power_calc.py. The page gives the minimum detectable effect, "the smallest effect that, if true, has (1-β)% chance of producing an estimate that is statistically significant at the α% level (Bloom 1995)"; the design effect, 1 + (m − 1) × ICC; and the rule that with incomplete take-up the effect is divided by the difference in take-up between the arms, so that if half the treatment group takes up the treatment the sample "would be four times larger". It says the ICC can be estimated from "baseline data, surveys, and papers--all preferably in the same or a similar population"; to run sensitivity analysis on "minimum effect size, take-up rates and intracluster correlation"; and to "Be realistic and, if anything, overly pessimistic about take-up rates". Its formulas use the t distribution; the script uses the normal. Read in full. - Doyle, M.-A., & Feeney, L. (2021). Quick guide to power calculations. J-PAL Research Resources. https://www.povertyactionlab.org/resource/quick-guide-power-calculations Supports: the attention to take-up. "To be powered to detect the same effect size with 25% take-up, we would need to offer treatment to 16 times more people". It also warns that an underpowered study that finds no effect "may be misinterpreted as the program not having any effect at all". Read in full.
- Kettle, S., & Persian, R. (2022). Target, Explore, Solution, Trial, Scale: An introduction to running simple behavioural insights projects. The Behavioural Insights Team. https://www.bi.team/wp-content/uploads/2022/11/BIT-Handbook-How-to-run-simple-BI-projects.pdf Supports: running the calculation both ways and the options in the verdict. Chapter 4 describes determining "how big your sample needs to be to detect a certain effect size" and calculating "which effect size you would be able to detect" with a fixed sample; if that effect is not realistic, "decide whether you want to redesign the intervention to make it more impactful, find a way to increase your sample size, or live with a lower level of power". Its rules of thumb say a two-group trial of under 500 people is "Very unlikely" to have enough power "unless your intervention is extremely powerful". Read in full.
- Haynes, L., Service, O., Goldacre, B., & Torgerson, D. (2012). Test, Learn, Adapt. Cabinet Office. https://assets.publishing.service.gov.uk/media/5a7488c8e5274a7f9c586c23/TLA-1906126.pdf Supports: the task. Step 4, "Determine how many units are required for robust results", recommends "working with academics who have experience in RCTs to ensure this key technical calculation is done correctly", and gives the example that 400 people per group give "about an 8 out of 10 chance" of detecting a change from 50% to 60%; the script gives 388 per arm for that case. Step 4 read.
- OECD (2019). Tools and Ethics for Applied Behavioural Insights: The BASIC Toolkit. https://doi.org/10.1787/9ea76a8f-en Supports: the task. Box 2.10, "Power analysis", says it "allows researchers and practitioners to determine the sample size required to detect an effect of a given size", and that "practitioners will often be well advised to seek out external expertise on this matter". Box 2.10 read.
- Jang, C., Koki, E., Nyaga, R., Okafor, A., Singh, J., Vang, A., & Wendel, S. (2024). The Busara toolkit: leveraging behavioral science for development. Busara Groundwork No. 10. https://doi.org/10.62372/WQSB6195 Supports: the task. Step 4 of its guidance on running a randomized trial is "Sample size, sample design and statistical power". That passage read.
The methods behind the script:
- Bloom, H. S. (1995). Minimum detectable effects. Evaluation Review, 19(5), 547–556. https://doi.org/10.1177/0193841X9501900504 Supports: reporting the minimum detectable effect, "the smallest true impact that an experiment has a good chance of detecting", for binary and continuous outcomes. Abstract only.
- McConnell, B., & Vera-Hernández, M. (2025). Going beyond simple sample size calculations: A practitioner's guide. Fiscal Studies, 46(3), 323–348. https://doi.org/10.1111/1475-5890.70005 Supports: the adjustments for clustering and covariates, and choosing between more groups and more people per group; the paper gives guidance on allocating the sample between the two. The paper compiles formulas for continuous and binary outcomes, with and without covariates, clustered or not, and covers simulation for more complex designs. Abstract only.
- Gelman, A., & Carlin, J. (2014). Beyond power calculations. Perspectives on Psychological Science, 9(6), 641–651. https://doi.org/10.1177/1745691614551642 Supports: the
--true-effectreport. The authors recommend estimating "the probability of an estimate being in the wrong direction (Type S [sign] error)" and "the factor by which the magnitude of an effect might be overestimated (Type M [magnitude] error or exaggeration ratio)". The script computes both in closed form. Abstract only.
Four rules are this skill's own and come from no source: the default ICC grid of 0.01, 0.05, 0.10, and 0.20 in the script's sensitivity table; the escalation below 30 groups, with the figure of about 30% for 10 groups computed by comparing normal with t critical values on 8 degrees of freedom (groups minus two); the escalation for baselines below 5% or above 95%; and the instruction to pass --true-effect as a positive number.
Where it has been tested
Searched November 2026. The skill is arithmetic and makes no claim about how people behave, so this table records where its sources come from and where an ICC a user might borrow was measured.
| Source | Type | Countries | Finding |
|---|---|---|---|
| Gupta & Kopper (2021) | Practitioner guide; full text | Written for randomized evaluations in any country | No test of the method is reported. It tells the user to take inputs from the same or a similar population |
| Kettle & Persian (2022) | Practitioner guide; full text | Written by a UK team; its trial examples include Mexico and Moldova | No test of the method is reported |
| Hedges & Hedberg (2007). Intraclass correlation values for planning group-randomized trials in education. Educational Evaluation and Policy Analysis, 29(1), 60–87 | Compilation of ICCs for academic achievement; read in its working-paper version | United States, from longitudinal surveys with national probability samples | Gives ICCs and covariate effects for planning school-randomized trials |
| Kelcey, Shen & Spybrook (2016). Intraclass correlation coefficients for designing cluster-randomized trials in sub-Saharan Africa education. Evaluation Review, 40(6), 500–525 | Compilation of ICCs; abstract only | 15 sub-Saharan African countries; over 60,000 sixth-grade students in 2,500 schools | Reading and mathematics scores were substantially clustered within schools, and the clustering varied considerably across countries, as did how much covariates reduced it |
| Pagel et al. (2011). Intracluster correlation coefficients and coefficients of variation for perinatal outcomes from five cluster-randomised controlled trials in low and middle-income countries: results and methodological implications. Trials, 12, 151 | ICCs from five community-based trials; abstract only | India, Bangladesh, Malawi | ICCs for mortality were lower than for process outcomes, and estimates for rare outcomes such as maternal mortality were much less reliable; for maternal mortality the authors advise planning with a range of estimates |
The formulas do not depend on the population. The ICC, the baseline, take-up, and attrition do, and the two compilations from Africa and South Asia show the ICC moving with country and outcome.
Replication
Not applicable. The formulas are standard and not in dispute. They are approximations: the script uses normal critical values where the J-PAL page uses the t distribution, which matters when there are few groups, and the two-proportion formula is poor near rates of 0 or 1.
What to check locally
- The ICC, estimated from the program's own baseline or administrative data at the group level. If none exists, the sensitivity table is the answer, not a single number.
- The baseline rate or standard deviation in this population, and whether it came from data or a guess.
- Take-up in the treatment arm and any take-up in the control arm, from the program's enrollment records.
- Attrition between enrollment and outcome measurement in earlier rounds.
- Whether groups will be of similar size; the design effect assumes they are.
Scripts
Code the skill runs during its steps, so results such as calculations come from code rather than from the AI working them out.
scripts/View on GitHub
power_calc.py
Sample size, minimum detectable effect, and Type S/M risk for two-arm trials.
#!/usr/bin/env python3
"""power_calc.py: sample size, minimum detectable effect, and Type S/M risk
for two-arm trials.
Standard normal-approximation formulas for a two-arm, equal-allocation
comparison with individual or cluster randomization and a binary or
continuous outcome. Inflates the sample for imperfect take-up and for
attrition, deflates it for covariate adjustment, and reports Gelman and
Carlin's Type S (wrong sign) and Type M (exaggeration) risk for a stated
true effect. Standard library only; Python 3.8+.
Formulas (z_a = upper alpha/2 normal quantile, z_b = power quantile):
continuous: n_ind = 2 * (z_a + z_b)^2 / d^2 per arm
binary: n_ind = (z_a * sqrt(2 * pbar * qbar)
+ z_b * sqrt(p0*q0 + p1*q1))^2 / (p1 - p0)^2
design effect: DE = 1 + (m - 1) * icc
per-arm enrollment: n = n_ind * (1 - r2) * DE / takeup_diff^2 / (1 - attrition)
clusters per arm: ceil(n / m)
The minimum detectable effect for a fixed sample inverts the same formulas
(closed form for a continuous outcome, bisection for a binary one).
Self-test (python power_calc.py --self-test):
Continuous outcome, d = 0.20, alpha = 0.05 two-sided, power = 0.80,
individual randomization: 2 * (1.960 + 0.842)^2 / 0.04 = 392.4, so the
script returns 393 per arm. Textbook tables that use the t distribution
give 394 for the same case.
Binary outcome, p0 = 0.30, p1 = 0.40, same alpha and power: 356 per arm,
the standard uncorrected two-proportion result.
Cluster check: d = 0.20 with m = 40 and icc = 0.10 gives DE = 4.9,
1923 enrolled per arm (392.4 x 4.9 = 1922.8), 49 clusters per arm.
Examples:
python power_calc.py --outcome continuous --effect 0.20
python power_calc.py --outcome binary --p0 0.35 --p1 0.41 --icc 0.05 \
--cluster-size 40 --attrition 0.10 --r2 0.10
python power_calc.py --outcome binary --p0 0.35 --p1 0.41 --icc 0.05 \
--cluster-size 40 --attrition 0.10 --r2 0.10 --clusters-per-arm 30 \
--sensitivity --true-effect 0.06
"""
from __future__ import annotations
import argparse
import math
import sys
from typing import List, Optional
# ---------------------------------------------------------------------------
# Normal distribution helpers (no scipy)
# ---------------------------------------------------------------------------
def norm_cdf(x: float) -> float:
return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))
def norm_pdf(x: float) -> float:
return math.exp(-0.5 * x * x) / math.sqrt(2.0 * math.pi)
def norm_ppf(p: float) -> float:
"""Inverse normal CDF by bisection; accurate to about 1e-10."""
if not 0.0 < p < 1.0:
raise ValueError("probability must be strictly between 0 and 1")
lo, hi = -40.0, 40.0
for _ in range(200):
mid = 0.5 * (lo + hi)
if norm_cdf(mid) < p:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
# ---------------------------------------------------------------------------
# Core formulas
# ---------------------------------------------------------------------------
def n_ind_continuous(d: float, z_a: float, z_b: float) -> float:
return 2.0 * (z_a + z_b) ** 2 / (d * d)
def n_ind_binary(p0: float, p1: float, z_a: float, z_b: float) -> float:
pbar = 0.5 * (p0 + p1)
num = z_a * math.sqrt(2.0 * pbar * (1.0 - pbar)) + z_b * math.sqrt(p0 * (1.0 - p0) + p1 * (1.0 - p1))
return num * num / (p1 - p0) ** 2
def design_effect(m: float, icc: float) -> float:
return 1.0 + (m - 1.0) * icc
def inflate(n_ind: float, r2: float, de: float, takeup_diff: float, attrition: float) -> float:
"""Per-arm enrollment needed so the analyzed sample delivers n_ind of information."""
return n_ind * (1.0 - r2) * de / (takeup_diff ** 2) / (1.0 - attrition)
def deflate(n_enrolled: float, r2: float, de: float, takeup_diff: float, attrition: float) -> float:
"""Information-equivalent individual-level n from an enrolled per-arm sample."""
return n_enrolled * (takeup_diff ** 2) * (1.0 - attrition) / ((1.0 - r2) * de)
def mdes_continuous(n_eff: float, z_a: float, z_b: float) -> float:
return (z_a + z_b) * math.sqrt(2.0 / n_eff)
def mdes_binary(p0: float, n_eff: float, z_a: float, z_b: float, direction: str) -> float:
"""Smallest |p1 - p0| detectable with n_eff per arm, by bisection."""
sign = 1.0 if direction == "increase" else -1.0
lo, hi = 1e-6, (1.0 - p0 - 1e-6) if sign > 0 else (p0 - 1e-6)
if hi <= lo:
return float("nan")
for _ in range(200):
mid = 0.5 * (lo + hi)
if n_ind_binary(p0, p0 + sign * mid, z_a, z_b) > n_eff:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def retrodesign(true_effect: float, se: float, z_a: float) -> dict:
"""Gelman and Carlin (2014): power, Type S, and Type M for a true effect and SE.
The quantities are symmetric in the sign of the effect, so a decrease is
handled by working with its size."""
true_effect = abs(true_effect)
t = true_effect / se
p_hi = 1.0 - norm_cdf(z_a - t)
p_lo = norm_cdf(-z_a - t)
power = p_hi + p_lo
type_s = p_lo / power if power > 0 else float("nan")
# E[|estimate| | significant] in closed form from truncated-normal moments.
a_hi = (z_a * se - true_effect) / se
a_lo = (-z_a * se - true_effect) / se
e_hi = true_effect * (1.0 - norm_cdf(a_hi)) + se * norm_pdf(a_hi)
e_lo = -true_effect * norm_cdf(a_lo) + se * norm_pdf(a_lo)
exaggeration = (e_hi + e_lo) / (power * true_effect) if power > 0 and true_effect != 0 else float("nan")
return {"power": power, "type_s": type_s, "type_m": exaggeration}
# ---------------------------------------------------------------------------
# Driver
# ---------------------------------------------------------------------------
def fmt_effect(args, value: float) -> str:
if args.outcome == "binary":
return f"{100 * value:.1f} pp"
if args.sd:
return f"{value * args.sd:.3f} raw ({value:.3f} SD)"
return f"{value:.3f} SD"
def planned_effect(args) -> float:
if args.outcome == "binary":
return args.p1 - args.p0
return args.effect / args.sd if args.sd else args.effect
def n_ind_for(args, effect: float, z_a: float, z_b: float) -> float:
if args.outcome == "binary":
return n_ind_binary(args.p0, args.p0 + effect, z_a, z_b)
return n_ind_continuous(effect, z_a, z_b)
def required_sample(args, effect: float, icc: float, z_a: float, z_b: float) -> dict:
de = design_effect(args.cluster_size, icc)
n_ind = n_ind_for(args, effect, z_a, z_b)
n = inflate(n_ind, args.r2, de, args.takeup - args.control_takeup, args.attrition)
return {
"n_ind": n_ind,
"de": de,
"n_per_arm": math.ceil(n),
"clusters_per_arm": math.ceil(n / args.cluster_size),
}
def mdes_for(args, n_enrolled: float, icc: float, z_a: float, z_b: float) -> float:
de = design_effect(args.cluster_size, icc)
n_eff = deflate(n_enrolled, args.r2, de, args.takeup - args.control_takeup, args.attrition)
if args.outcome == "binary":
return mdes_binary(args.p0, n_eff, z_a, z_b, args.direction)
return mdes_continuous(n_eff, z_a, z_b)
def se_for(args, effect: float, n_enrolled: float, icc: float) -> float:
de = design_effect(args.cluster_size, icc)
n_eff = deflate(n_enrolled, args.r2, de, args.takeup - args.control_takeup, args.attrition)
if args.outcome == "binary":
p1 = args.p0 + effect
return math.sqrt((args.p0 * (1 - args.p0) + p1 * (1 - p1)) / n_eff)
return math.sqrt(2.0 / n_eff)
def parse_grid(text: Optional[str], default: List[float]) -> List[float]:
if not text:
return default
return [float(x) for x in text.split(",") if x.strip()]
def run(args) -> int:
z_a = norm_ppf(1.0 - args.alpha / 2.0)
z_b = norm_ppf(args.power)
effect = planned_effect(args)
takeup_diff = args.takeup - args.control_takeup
if takeup_diff <= 0:
sys.stderr.write("take-up in treatment must exceed take-up in control\n")
return 2
fixed = args.n_per_arm or (args.clusters_per_arm * args.cluster_size if args.clusters_per_arm else None)
print(f"outcome: {args.outcome}; alpha {args.alpha} two-sided (z = {z_a:.3f}); power {args.power} (z = {z_b:.3f})")
if args.outcome == "binary":
print(f"baseline p0 = {args.p0:.3f}; planned p1 = {args.p1:.3f}; planned effect = {fmt_effect(args, effect)}")
else:
print(f"planned effect = {fmt_effect(args, effect)}")
print(f"cluster size m = {args.cluster_size}; icc = {args.icc}; design effect = {design_effect(args.cluster_size, args.icc):.3f}")
print(f"take-up diff = {takeup_diff:.2f}; attrition = {args.attrition:.2f}; covariate r2 = {args.r2:.2f}")
print()
req = required_sample(args, effect, args.icc, z_a, z_b)
print("REQUIRED SAMPLE for the planned effect")
print(f" individual-level n per arm (no adjustments): {req['n_ind']:.1f}")
print(f" x (1 - r2) = {1 - args.r2:.2f}; x DE = {req['de']:.3f}; / takeup_diff^2 = {takeup_diff ** 2:.3f}; / (1 - attrition) = {1 - args.attrition:.2f}")
print(f" enrolled per arm: {req['n_per_arm']}")
if args.cluster_size > 1:
print(f" clusters per arm: {req['clusters_per_arm']} (total {2 * req['clusters_per_arm']})")
print()
if fixed:
md = mdes_for(args, fixed, args.icc, z_a, z_b)
print(f"MINIMUM DETECTABLE EFFECT for {fixed:.0f} enrolled per arm"
+ (f" ({args.clusters_per_arm} clusters per arm)" if args.clusters_per_arm else ""))
print(f" MDES = {fmt_effect(args, md)}")
if args.outcome == "binary":
sd0 = math.sqrt(args.p0 * (1 - args.p0))
print(f" = {md / sd0:.3f} SD of the baseline outcome (sd = sqrt(p0(1-p0)) = {sd0:.3f})")
verdict = "CAN" if md <= abs(effect) + 1e-12 else "CANNOT"
print(f" verdict: the fixed sample {verdict} detect the planned effect of {fmt_effect(args, effect)} at the stated power")
print()
if args.sensitivity:
iccs = parse_grid(args.icc_grid, [0.01, 0.05, 0.10, 0.20] if args.cluster_size > 1 else [args.icc])
mults = parse_grid(args.effect_grid, [0.5, 0.75, 1.0, 1.5])
unit = "clusters per arm" if args.cluster_size > 1 else "enrolled per arm"
print(f"SENSITIVITY: required {unit} by icc (rows) and effect (columns)")
header = "icc".ljust(8) + "".join(fmt_effect(args, effect * k).rjust(20) for k in mults)
print(" " + header)
for icc in iccs:
row = f"{icc:<8.3f}"
for k in mults:
if args.outcome == "binary" and not 0.0 < args.p0 + effect * k < 1.0:
row += "n/a (rate > 1 or < 0)".rjust(22)
continue
r = required_sample(args, effect * k, icc, z_a, z_b)
row += str(r["clusters_per_arm"] if args.cluster_size > 1 else r["n_per_arm"]).rjust(20)
print(" " + row)
if fixed:
print(f" MDES for the fixed sample by icc: "
+ "; ".join(f"icc {icc:g}: {fmt_effect(args, mdes_for(args, fixed, icc, z_a, z_b))}" for icc in iccs))
print()
if args.true_effect is not None:
if not fixed:
print("TYPE S / TYPE M: give --n-per-arm or --clusters-per-arm so the design is fixed")
else:
te = args.true_effect / args.sd if (args.outcome == "continuous" and args.sd) else args.true_effect
se = se_for(args, te, fixed, args.icc)
rd = retrodesign(te, se, z_a)
print(f"TYPE S / TYPE M RISK if the true effect is {fmt_effect(args, te)} (Gelman and Carlin 2014)")
print(f" standard error of the estimate: {fmt_effect(args, se)}")
print(f" power at that true effect: {rd['power']:.2f}")
print(f" Type S: P(wrong sign | significant) = {rd['type_s']:.3f}")
print(f" Type M: expected |estimate| / true effect, given significance = {rd['type_m']:.2f}")
print()
return 0
def self_test() -> int:
z_a, z_b = norm_ppf(0.975), norm_ppf(0.80)
checks = []
n1 = math.ceil(n_ind_continuous(0.20, z_a, z_b))
checks.append(("continuous d=0.20 -> 393 per arm", n1 == 393, n1))
n2 = math.ceil(n_ind_binary(0.30, 0.40, z_a, z_b))
checks.append(("binary 0.30 -> 0.40 -> 356 per arm", n2 == 356, n2))
de = design_effect(40, 0.10)
n3 = math.ceil(n_ind_continuous(0.20, z_a, z_b) * de)
checks.append(("cluster m=40 icc=0.10 -> DE 4.9, 1923 per arm, 49 clusters", abs(de - 4.9) < 1e-9 and n3 == 1923 and math.ceil(n3 / 40) == 49, (de, n3, math.ceil(n3 / 40))))
md = mdes_continuous(393, z_a, z_b)
checks.append(("MDES at 393 per arm -> 0.200 SD", abs(md - 0.20) < 0.001, round(md, 4)))
rd = retrodesign(0.20, 0.20 / 2.802, z_a)
checks.append(("retrodesign power ~0.80 when effect = 2.80 SE", abs(rd["power"] - 0.80) < 0.005, round(rd["power"], 3)))
neg = retrodesign(-0.20, 0.20 / 2.802, z_a)
checks.append(("retrodesign is the same for a decrease", all(abs(neg[k] - rd[k]) < 1e-12 for k in ("power", "type_s", "type_m")), (round(neg["type_s"], 4), round(neg["type_m"], 3))))
ok = True
for label, passed, got in checks:
print(("PASS " if passed else "FAIL ") + label + f" (got {got})")
ok = ok and passed
print("self-test " + ("passed" if ok else "FAILED"))
return 0 if ok else 1
def main(argv: Optional[List[str]] = None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter, epilog="\n".join(__doc__.split("\n\n")[1:]))
ap.add_argument("--outcome", choices=["continuous", "binary"], help="outcome type")
ap.add_argument("--effect", type=float, help="continuous: planned effect in SD units, or raw units if --sd is given")
ap.add_argument("--sd", type=float, help="continuous: outcome SD, so --effect and --true-effect are read as raw units")
ap.add_argument("--p0", type=float, help="binary: control-arm rate (0-1)")
ap.add_argument("--p1", type=float, help="binary: treatment-arm rate (0-1)")
ap.add_argument("--alpha", type=float, default=0.05, help="two-sided significance level (default 0.05)")
ap.add_argument("--power", type=float, default=0.80, help="target power (default 0.80)")
ap.add_argument("--icc", type=float, default=0.0, help="intracluster correlation (default 0)")
ap.add_argument("--cluster-size", type=float, default=1, help="units measured per cluster (default 1 = individual randomization)")
ap.add_argument("--takeup", type=float, default=1.0, help="share of the treatment arm that takes up the treatment (default 1)")
ap.add_argument("--control-takeup", type=float, default=0.0, help="share of the control arm that gets the treatment anyway (default 0)")
ap.add_argument("--attrition", type=float, default=0.0, help="share of enrolled units lost before outcome measurement (default 0)")
ap.add_argument("--r2", type=float, default=0.0, help="share of outcome variance explained by covariates (default 0)")
ap.add_argument("--n-per-arm", type=float, help="fixed enrolled sample per arm: report the MDES instead of required n")
ap.add_argument("--clusters-per-arm", type=float, help="fixed clusters per arm (with --cluster-size): report the MDES")
ap.add_argument("--direction", choices=["increase", "decrease"], default="increase", help="binary MDES: direction of the effect (default increase)")
ap.add_argument("--sensitivity", action="store_true", help="print the required sample over an icc x effect grid")
ap.add_argument("--icc-grid", help="comma-separated icc values for --sensitivity")
ap.add_argument("--effect-grid", help="comma-separated multipliers of the planned effect for --sensitivity (default 0.5,0.75,1,1.5)")
ap.add_argument("--true-effect", type=float, help="report Type S / Type M risk if this is the true effect (needs a fixed sample)")
ap.add_argument("--self-test", action="store_true", help="run the known-case checks and exit")
args = ap.parse_args(argv)
if args.self_test:
return self_test()
if not args.outcome:
ap.error("--outcome is required (or use --self-test)")
if args.outcome == "binary":
if args.p0 is None or args.p1 is None:
ap.error("binary outcome needs --p0 and --p1")
if not (0 < args.p0 < 1 and 0 < args.p1 < 1) or args.p0 == args.p1:
ap.error("--p0 and --p1 must be between 0 and 1 and differ")
else:
if args.effect is None or args.effect == 0:
ap.error("continuous outcome needs a non-zero --effect")
if not (0 < args.alpha < 1 and 0 < args.power < 1):
ap.error("--alpha and --power must be between 0 and 1")
if args.cluster_size < 1 or not (0 <= args.icc < 1):
ap.error("--cluster-size must be >= 1 and --icc in [0, 1)")
if not (0 <= args.attrition < 1 and 0 <= args.r2 < 1):
ap.error("--attrition and --r2 must be in [0, 1)")
return run(args)
if __name__ == "__main__":
sys.exit(main())
Version history
What changed in each version, newest first. An entry that answers an issue or review links to it.
CHANGELOG.mdView on GitHub
0.3.0 - 2026-11-11
Follows the conversational-voice standard. The calculation opens with a few plain sentences to the user (whether the feasible sample can detect the planned effect, the input it moves on most, and what would change the verdict) and is titled "How big the sample must be" instead of "Power calculation". Alpha, power, ICC, attrition, covariate R², and the design effect are glossed in the output; "Individual-level sample per arm" is "Sample per arm before adjustments"; the minimum detectable effect, sensitivity, and Type S and Type M headings say in plain words what they show. The script and every number in the worked example are unchanged. The output ends with next moves and their reasons, chosen from candidates listed in the closing, and the skill carries the shared voice block. The method is unchanged. Edited with Claude.
0.2.0 - 2026-11-11
Rewritten to the November 2026 standard. The skill still runs scripts/power_calc.py, unchanged, for every number; it now passes --true-effect as a positive value and keeps the sensitivity grid between rates of 0 and 1, because the script misreports Type S and Type M for a negative effect and does not check the grid's bounds. Sources were re-verified and the uncheckable ones dropped; sub-Saharan African and South Asian ICC compilations now sit beside the US one. Rewritten with Claude.
0.1.0 - 2026-10-12
First draft. Drafted with Claude from a verified evidence dossier for Zezhen Wu's review; four evals; not yet reviewed.
Reviews
Expert reviews come from behavioral scientists at The Agency Fund and Irrational Labs and are kept as issues on GitHub; each shows whether a later version of the skill answered it. Ratings and comments come from anyone who has used the skill.
Expert reviews
Expert reviews of this skill are kept as issues on GitHub.