Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Update version to 2.50.0 and increment skill count to 146

Timothy Kassisfdf52effe2df
diff --git a/README.md b/README.md
index 66698c30..9a8c27d8 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,8 @@
# Scientific Agent Skills
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE.md)
-[![Version](https://img.shields.io/badge/Version-2.43.0-blue.svg)](pyproject.toml)
-[![Skills](https://img.shields.io/badge/Skills-144-brightgreen.svg)](#-whats-included)
+[![Version](https://img.shields.io/badge/Version-2.50.0-blue.svg)](pyproject.toml)
+[![Skills](https://img.shields.io/badge/Skills-146-brightgreen.svg)](#-whats-included)
[![Databases](https://img.shields.io/badge/Databases-100%2B-orange.svg)](#-whats-included)
[![Agent Skills](https://img.shields.io/badge/Standard-Agent_Skills-blueviolet.svg)](https://agentskills.io/)
[![Security Scan](https://github.com/K-Dense-AI/scientific-agent-skills/actions/workflows/security-scan.yml/badge.svg)](https://github.com/K-Dense-AI/scientific-agent-skills/actions/workflows/security-scan.yml)
@@ -17,11 +17,11 @@
> **🔔 Claude Scientific Skills is now Scientific Agent Skills.** Same skills, broader compatibility — now works with any AI agent that supports the open [Agent Skills](https://agentskills.io/) standard, not just Claude.
-> **New: [K-Dense BYOK](https://github.com/K-Dense-AI/k-dense-byok)** — A free, open-source AI co-scientist that runs on your desktop, powered by Scientific Agent Skills. Bring your own API keys, pick from 40+ models, and get a full research workspace with web search, file handling, 100+ scientific databases, and access to all 144 skills in this repo. Your data stays on your computer, and you can optionally scale to cloud compute via [Modal](https://modal.com/) for heavy workloads. [Get started here.](https://github.com/K-Dense-AI/k-dense-byok)
+> **New: [K-Dense BYOK](https://github.com/K-Dense-AI/k-dense-byok)** — A free, open-source AI co-scientist that runs on your desktop, powered by Scientific Agent Skills. Bring your own API keys, pick from 40+ models, and get a full research workspace with web search, file handling, 100+ scientific databases, and access to all 146 skills in this repo. Your data stays on your computer, and you can optionally scale to cloud compute via [Modal](https://modal.com/) for heavy workloads. [Get started here.](https://github.com/K-Dense-AI/k-dense-byok)
> **Stay up to date:** Follow K-Dense on [X](https://x.com/k_dense_ai), [LinkedIn](https://www.linkedin.com/company/k-dense-inc), and [YouTube](https://www.youtube.com/@K-Dense-Inc) for new skills, release announcements, walkthroughs, research workflow demos, and examples you can use with your own AI agent.
-A comprehensive collection of **144 ready-to-use scientific and research skills** (covering cancer genomics, drug-target binding, molecular dynamics, RNA velocity, geospatial science, time series forecasting, scientific ML resource discovery via Hugging Science, 78+ scientific databases, and more) for any AI agent that supports the open [Agent Skills](https://agentskills.io/) standard, created by [K-Dense](https://k-dense.ai). Works with **Cursor, Claude Code, Codex, Google Antigravity, and more**. Transform your AI agent into a research assistant capable of executing complex multi-step scientific workflows across biology, chemistry, medicine, and beyond.
+A comprehensive collection of **146 ready-to-use scientific and research skills** (covering cancer genomics, drug-target binding, molecular dynamics, RNA velocity, geospatial science, time series forecasting, scientific ML resource discovery via Hugging Science, 78+ scientific databases, and more) for any AI agent that supports the open [Agent Skills](https://agentskills.io/) standard, created by [K-Dense](https://k-dense.ai). Works with **Cursor, Claude Code, Codex, Google Antigravity, and more**. Transform your AI agent into a research assistant capable of executing complex multi-step scientific workflows across biology, chemistry, medicine, and beyond.
> ⭐ **Help make AI for science easier to discover:** If Scientific Agent Skills saves you time, teaches your agent a workflow, or helps your lab move faster, please [star this repository](https://github.com/K-Dense-AI/scientific-agent-skills). A star is a public signal that these open, reusable research skills are worth maintaining: it helps scientists, engineers, and open-source contributors find the project, shows which agent-skill standards are gaining real adoption, and gives us a clear reason to keep expanding the collection for the community.
@@ -55,7 +55,7 @@ These skills enable your AI agent to seamlessly work with specialized scientific
## 📦 What's Included
-This repository provides **144 scientific and research skills** organized into the following categories:
+This repository provides **146 scientific and research skills** organized into the following categories:
- **100+ Scientific & Financial Databases** - A unified database-lookup skill provides direct access to 78 public databases (PubChem, ChEMBL, UniProt, COSMIC, ClinicalTrials.gov, FRED, USPTO, and more), plus dedicated skills for DepMap, Imaging Data Commons, PrimeKG, U.S. Treasury Fiscal Data, and Hugging Science (curated catalog of scientific datasets, models, and demos across 17 scientific domains on Hugging Face). Multi-database packages like BioServices (~40 bioinformatics services), BioPython (38 NCBI sub-databases via Entrez), and gget (20+ genomics databases) add further coverage
- **70+ Optimized Python Package Skills** - Explicitly defined skills for RDKit, Scanpy, PyTorch Lightning, scikit-learn, BioPython, pyzotero, BioServices, PennyLane, Qiskit, Molecular Dynamics (OpenMM/MDAnalysis), scVelo, TimesFM, and others — with curated documentation, examples, and best practices. Note: the agent can write code using *any* Python package, not just these; these skills simply provide stronger, more reliable performance for the packages listed
@@ -100,7 +100,7 @@ Each skill includes:
- **Multi-Step Workflows** - Execute complex pipelines with a single prompt
### 🎯 **Comprehensive Coverage**
-- **144 Skills** - Extensive coverage across all major scientific domains
+- **146 Skills** - Extensive coverage across all major scientific domains
- **100+ Databases** - Unified access to 78+ databases via database-lookup, plus dedicated data access skills and multi-database packages like BioServices, BioPython, and gget
- **70+ Optimized Python Package Skills** - RDKit, Scanpy, PyTorch Lightning, scikit-learn, BioServices, PennyLane, Qiskit, Molecular Dynamics (OpenMM/MDAnalysis), scVelo, TimesFM, and others (the agent can use any Python package; these are the pre-documented, higher-performing paths)
@@ -185,7 +185,7 @@ git clone https://github.com/K-Dense-AI/scientific-agent-skills.git .agents/skil
hermes skills tap add K-Dense-AI/scientific-agent-skills
```
-These skills stay portable across all of them: `metadata` is single-line JSON (so OpenClaw's line-based reader parses it), credentialed skills declare a top-level `required_environment_variables` field (so Hermes prompts for keys), and unknown fields are ignored everywhere else. Because 144 skills add up to a lot of standing context, consider installing a topical subset rather than the whole collection.
+These skills stay portable across all of them: `metadata` is single-line JSON (so OpenClaw's line-based reader parses it), credentialed skills declare a top-level `required_environment_variables` field (so Hermes prompts for keys), and unknown fields are ignored everywhere else. Because 146 skills add up to a lot of standing context, consider installing a topical subset rather than the whole collection.
> **NemoClaw note:** NemoClaw runs agents inside NVIDIA OpenShell with default-deny outbound networking. Skills are discovered and loaded normally, but any skill that needs the network — package installs via `uv`, or API calls (Exa, Parallel, Benchling, NCBI, Materials Project, …) — only works once the operator pre-approves the relevant domains in the OpenShell TUI.
@@ -410,7 +410,7 @@ networks, and search GEO for similar patterns.
## 📚 Available Skills
-This repository contains **144 scientific and research skills** organized across multiple domains. Each skill provides comprehensive documentation, code examples, and best practices for working with scientific libraries, databases, and tools.
+This repository contains **146 scientific and research skills** organized across multiple domains. Each skill provides comprehensive documentation, code examples, and best practices for working with scientific libraries, databases, and tools.
### Skill Categories
@@ -474,7 +474,7 @@ This repository contains **144 scientific and research skills** organized across
- Discrete-event simulation: SimPy
- Symbolic math: SymPy
-#### 📊 **Data Analysis & Visualization** (19 skills)
+#### 📊 **Data Analysis & Visualization** (21 skills)
- Visualization: Matplotlib, Seaborn, Scientific Visualization
- Geospatial analysis: GeoPandas, GeoMaster (remote sensing, GIS, satellite imagery, spatial ML, 500+ examples)
- Data processing: Dask, Polars, Vaex
@@ -484,6 +484,8 @@ This repository contains **144 scientific and research skills** organized across
- Diagrams: Markdown & Mermaid Writing (text-based diagrams as default documentation standard)
- Exploratory data analysis: EDA workflows
- Statistical analysis: Statistical Analysis workflows
+- Experimental design: Experimental Design (randomization, blocking, factorial/fractional-factorial DOE, crossover, cluster, sequential designs; pyDOE3)
+- Statistical power: Statistical Power (sample-size & power for t-tests, ANOVA, proportions, correlation, regression — closed-form plus simulation-based for GLMs, mixed models, and cluster designs)
#### 🧪 **Laboratory Automation** (6 skills)
- Liquid handling: PyLabRobot and Opentrons
@@ -734,7 +736,7 @@ Recommended practice:
title = {Scientific Agent Skills: A Comprehensive Collection of Scientific Tools for AI Agents},
year = {2026},
url = {https://github.com/K-Dense-AI/scientific-agent-skills},
- note = {144 skills covering databases, packages, integrations, and analysis tools}
+ note = {146 skills covering databases, packages, integrations, and analysis tools}
}
```
diff --git a/docs/open-source-sponsors.md b/docs/open-source-sponsors.md
index 9a5b080b..16eea190 100644
--- a/docs/open-source-sponsors.md
+++ b/docs/open-source-sponsors.md
@@ -1,6 +1,6 @@
# Support the Open Source Projects We Depend On
-Scientific Agent Skills is built on the shoulders of giants. The 144 skills in this repository leverage dozens of incredible open source projects created and maintained by dedicated developers and research communities around the world.
+Scientific Agent Skills is built on the shoulders of giants. The 146 skills in this repository leverage dozens of incredible open source projects created and maintained by dedicated developers and research communities around the world.
**If you find value in these skills, please consider supporting the underlying open source projects that make them possible.**
diff --git a/docs/skills.md b/docs/skills.md
index d27b7e8b..32476220 100644
--- a/docs/skills.md
+++ b/docs/skills.md
@@ -196,6 +196,7 @@
## Scientific Thinking & Analysis
### Analysis & Methodology
+- **Experimental Design** - Design studies before data collection: choosing a design, randomization (simple, block, stratified, cluster), blocking and stratification, factorial and fractional-factorial designs (DOE), screening (Plackett-Burman), response-surface designs (central composite, Box-Behnken), Latin hypercube, crossover/repeated-measures/split-plot/Latin-square, sequential and adaptive designs, and avoiding pseudoreplication. Includes seeded allocation-schedule and DOE-matrix generators (numpy, pandas, pyDOE3). For sample size see Statistical Power; for analysis see Statistical Analysis
- **Exploratory Data Analysis** - Comprehensive EDA toolkit with automated statistics, visualizations, and insights for any tabular dataset
- **Hypothesis Generation** - Structured frameworks for generating and evaluating scientific hypotheses
- **Literature Review** - Systematic literature search and review toolkit with support for multiple scientific databases (PubMed, bioRxiv, Google Scholar), citation management with multiple citation styles (APA, AMA, Vancouver, Chicago, IEEE, Nature, Science), citation verification and deduplication, search strategies (Boolean operators, MeSH terms, field tags), PDF report generation with formatted references, and comprehensive templates for conducting systematic reviews following PRISMA guidelines
@@ -204,7 +205,8 @@
- **Scientific Critical Thinking** - Tools and approaches for rigorous scientific reasoning and evaluation
- **Scientific Visualization** - Best practices and templates for creating publication-quality scientific figures with matplotlib and seaborn, including statistical plots with automatic confidence intervals, colorblind-safe palettes, multi-panel figures, heatmaps, and journal-specific formatting
- **Scientific Writing** - Comprehensive toolkit for writing, structuring, and formatting scientific research papers using IMRAD format, multiple citation styles (APA, AMA, Vancouver, Chicago, IEEE), reporting guidelines (CONSORT, STROBE, PRISMA), effective figures and tables, field-specific terminology, venue-specific structure expectations, and core writing principles for clarity, conciseness, and accuracy across all scientific disciplines
-- **Statistical Analysis** - Guided hypothesis testing, assumption checks, effect sizes, power analysis, and APA reporting (Pingouin, SciPy, statsmodels, PyMC). For dedicated model APIs see statsmodels and pymc skills
+- **Statistical Analysis** - Guided hypothesis testing, assumption checks, effect sizes, power analysis, and APA reporting (Pingouin, SciPy, statsmodels, PyMC). For dedicated model APIs see statsmodels and pymc skills; for in-depth sample-size/power planning see Statistical Power; for designing the study see Experimental Design
+- **Statistical Power** - Sample-size and statistical power analysis for planning studies: required n, minimum detectable effect (MDE), and power curves for t-tests, ANOVA, proportions, correlation, chi-square, and regression via a unified closed-form interface, plus a Monte Carlo harness for designs with no formula (logistic/Poisson regression, mixed models, cluster-randomized trials, survival). Covers effect-size choice (SESOI), and adjustments for multiplicity, dropout, and clustering (statsmodels, scipy, pingouin, numpy). For laying out the design see Experimental Design; for post-collection analysis see Statistical Analysis
### Decision & Scenario Analysis
- **Consciousness Council** - Run a multi-perspective Mind Council deliberation on any question, decision, or creative challenge. Use for diverse viewpoints, tough decisions, devil's advocate analysis, exploring problems from multiple angles, or when facing dilemmas, trade-offs, and complex choices with no obvious answer
diff --git a/pyproject.toml b/pyproject.toml
index 04595e0e..bda3f677 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "scientific-agent-skills"
-version = "2.49.0"
+version = "2.50.0"
description = "A set of ready to use Agent Skills for research, science, engineering, analysis, finance and writing."
readme = "README.md"
requires-python = ">=3.13"
diff --git a/skills/experimental-design/SKILL.md b/skills/experimental-design/SKILL.md
new file mode 100644
index 00000000..88ca7610
--- /dev/null
+++ b/skills/experimental-design/SKILL.md
@@ -0,0 +1,232 @@
+---
+name: experimental-design
+description: Design experiments and studies BEFORE data is collected — choosing a design, randomizing, blocking, and laying out treatment combinations so the results will actually be interpretable. Use whenever someone is planning a study, asks how to assign subjects/samples to groups, mentions randomization, blocking, stratification, controls, factorial or fractional-factorial designs, design of experiments (DOE), screening many factors, response-surface optimization, crossover or repeated-measures or split-plot designs, cluster/group randomization, Latin squares, plate layouts, batch/run-order effects, replication vs. pseudoreplication, or sequential/adaptive/group-sequential designs. Trigger this even for informal phrasings like "how should I set up this experiment", "how do I avoid confounding", "what's the best way to test these 6 factors", or "assign these mice to conditions". For computing the sample size or power once the design is chosen, use statistical-power; for analyzing data already collected, use statistical-analysis.
+allowed-tools: Read Write Edit Bash
+compatibility: Requires Python >=3.10. Scripts use numpy, pandas, and pyDOE3 (DOE matrices). Install with uv as shown below.
+license: MIT license
+metadata: {"version": "1.0", "skill-author": "K-Dense Inc."}
+---
+
+# Experimental Design
+
+## Overview
+
+The design of a study — how units are assigned to conditions, what is held constant, what is varied, and in what structure — determines what questions the data can answer. No analysis can rescue a confounded or pseudoreplicated design after the fact. This skill is about the decisions made *before* data collection: picking a design that isolates the effect of interest, randomizing to license causal claims, blocking to remove known nuisance variation, and structuring multi-factor experiments so effects are estimable rather than tangled together.
+
+The three ideas behind almost every good design (Fisher's principles):
+- **Randomization** — assign treatments at random so that confounders, known and unknown, are balanced in expectation. This is what turns a comparison into a causal claim.
+- **Replication** — independent repetition at the right level, so you can estimate variability and your effects aren't artifacts of a single unit. The most common fatal error is **pseudoreplication**: counting repeated measurements on the same unit as independent replicates.
+- **Blocking / local control** — group similar units (by batch, day, site, litter) and randomize within blocks, removing that nuisance variation from the error term instead of letting it inflate noise.
+
+This skill helps you choose among design types, generate the actual randomization or DOE layout (with reproducible scripts), and avoid the structural mistakes that make data uninterpretable.
+
+## When to Use This Skill
+
+- Planning any comparative experiment or trial and deciding how to assign units
+- Randomizing subjects/samples to arms (simple, blocked, stratified, or cluster)
+- Removing nuisance variation by blocking or stratification
+- Designing multi-factor experiments: full or fractional factorial, screening designs
+- Optimizing a response over continuous factors (response-surface designs)
+- Within-subject / repeated-measures, crossover, split-plot, or Latin-square designs
+- Cluster- or group-randomized designs (sites, clinics, classrooms, litters)
+- Deciding the number and level of replicates and avoiding pseudoreplication
+- Sequential, group-sequential, or adaptive designs with interim analyses
+- Laying out plates/batches and randomizing run order to defeat drift
+
+## Installation
+
+```bash
+uv pip install "numpy>=1.26" "pandas>=2.0" pyDOE3
+```
+
+`pyDOE3` is the maintained successor to pyDOE/pyDOE2 and supplies factorial,
+fractional-factorial, Plackett-Burman, central-composite, Box-Behnken, and
+Latin-hypercube generators. The bundled scripts wrap it to return designs in real
+factor units with named columns and randomized run order.
+
+---
+
+## Choosing a design
+
+Start from the question and the structure of your units, not from a favorite design.
+
+```
+What are you trying to learn?
+│
+├─ Compare a few predefined conditions (A vs B vs C)?
+│ ├─ Units independent, possibly with a known nuisance factor (day, batch, site)?
+│ │ → Completely randomized (no nuisance) or RANDOMIZED BLOCK design.
+│ ├─ Each unit can receive every condition in sequence (washout possible)?
+│ │ → CROSSOVER / repeated-measures design (more power, watch carry-over).
+│ └─ You can only randomize groups, not individuals (schools, clinics)?
+│ → CLUSTER-randomized design (analyze at the cluster level; see pseudoreplication).
+│
+├─ Screen MANY factors (5+) to find the few that matter?
+│ → FRACTIONAL FACTORIAL or PLACKETT-BURMAN screening design.
+│
+├─ Quantify main effects AND interactions among a handful of factors?
+│ → FULL 2^k FACTORIAL design.
+│
+├─ Find the settings that OPTIMIZE a response (curvature matters)?
+│ → RESPONSE-SURFACE design: central composite or Box-Behnken.
+│
+└─ Explore a simulation/computer model over a continuous space?
+ → SPACE-FILLING design: Latin hypercube.
+```
+
+Detailed guidance per branch:
+- **Randomization, blocking, stratification, controls** → `references/randomization_and_blocking.md`
+- **Factorial, fractional-factorial, screening, response-surface, DOE concepts (aliasing, resolution)** → `references/factorial_and_doe.md`
+- **Crossover, repeated-measures, split-plot, Latin-square, cluster, nested designs** → `references/design_types.md`
+- **Sequential, group-sequential, and adaptive designs (interim analyses)** → `references/sequential_and_adaptive.md`
+
+---
+
+## Generating the design
+
+Two scripts produce ready-to-use, reproducible layouts. Run them from the skill's
+`scripts/` directory or add it to `sys.path`. Everything is seeded so the exact
+schedule can be archived and regenerated — a requirement for trial registration
+and good lab practice.
+
+### Randomization / allocation schedules — `scripts/randomization.py`
+
+```python
+from randomization import (
+ simple_randomization, block_randomization,
+ stratified_block_randomization, cluster_randomization,
+ assign_factorial_runs, arm_balance,
+)
+
+# Permuted blocks keep the arms balanced throughout enrollment (use for n < ~100
+# or sequential intake — simple randomization can drift out of balance with small n)
+sched = block_randomization(n=60, arms=["treatment", "control"], seed=42)
+
+# Balance a prognostic variable across arms by randomizing within each stratum
+sched = stratified_block_randomization({"siteA": 30, "siteB": 30},
+ arms=["drug", "placebo"], ratio=(2, 1), seed=42)
+
+# Randomize whole clusters, not individuals (the cluster is the unit)
+sched = cluster_randomization(["clinic1", "clinic2", "clinic3", "clinic4"], seed=42)
+
+arm_balance(sched) # sanity-check the counts per arm
+sched.to_csv("allocation_schedule.csv", index=False)
+```
+
+Choosing among them: **simple** is fine for large n but can produce imbalance with
+small n; **block** guarantees balance throughout; **stratified block** additionally
+balances a known prognostic factor; **cluster** is mandatory when the intervention
+is delivered at a group level. See `references/randomization_and_blocking.md`.
+
+### DOE matrices — `scripts/doe_designs.py`
+
+```python
+from doe_designs import (
+ full_factorial, two_level_factorial, fractional_factorial,
+ plackett_burman, central_composite, box_behnken, latin_hypercube,
+)
+
+# Factors as real-world (low, high) ranges -> design comes back in real units
+factors = {"temp_C": (20, 60), "conc_mM": (1, 10), "pH": (6, 8)}
+
+# Full 2^3: all main effects + all interactions (8 runs), run order randomized
+design = two_level_factorial(factors, seed=42)
+
+# Screen 7 factors cheaply (main effects only)
+many = {f"factor_{i}": (0, 1) for i in range(7)}
+design = plackett_burman(many, seed=42)
+
+# Optimize over 2 factors with curvature (response-surface)
+design = central_composite({"temp_C": (20, 60), "conc_mM": (1, 10)}, seed=42)
+
+design.to_csv("experimental_runs.csv", index=False)
+```
+
+Run order is randomized by default so factors aren't confounded with time/drift
+(machine warm-up, reagent aging). See `references/factorial_and_doe.md` for picking
+generators, reading the alias structure, and choosing resolution.
+
+---
+
+## The mistakes that ruin studies
+
+These are structural — they can't be fixed in analysis, only in design.
+
+1. **Pseudoreplication.** Treating repeated measurements of one unit as independent
+ replicates: 3 mice with 100 cells each is n = 3 (mice), not n = 300 (cells), for
+ any treatment applied to the mouse. The replicate must be at the level the
+ treatment is randomized. This single error invalidates a large share of published
+ experiments. Randomize and replicate at the right level; analyze with the nesting
+ respected (mixed model). See `references/design_types.md`.
+2. **Confounding by a nuisance variable.** Running all treatment samples on Monday
+ and all controls on Tuesday confounds treatment with day. Randomize across, or
+ block on, every nuisance factor you can name (batch, day, plate, technician,
+ instrument, position).
+3. **No or broken randomization.** Convenience assignment (first-come → treatment)
+ lets confounders sneak in. Use a seeded schedule and follow it.
+4. **No proper control.** Without a concurrent control (and, where relevant, a
+ vehicle/sham and blinding), you can't separate the treatment effect from time,
+ placebo, or handling effects.
+5. **Batch effects mistaken for biology.** In omics especially, process samples in a
+ randomized/blocked order across batches; never let batch align with the condition.
+6. **Edge/position effects on plates.** Evaporation and thermal gradients make plate
+ edges differ. Randomize or block sample positions; don't put all controls in
+ column 1.
+7. **Aliasing ignored in fractional designs.** A low-resolution fractional factorial
+ confounds main effects with interactions; know your alias structure before
+ concluding a factor "has no effect."
+8. **Optimizing without curvature.** A two-level factorial can't detect a curved
+ response; you'll miss an interior optimum. Use a response-surface design.
+
+---
+
+## Workflow
+
+1. **State the question, the unit, and the response.** What is randomized? What is
+ measured? At what level is a true independent replicate? This determines everything.
+2. **List nuisance factors** (batch, day, site, operator, position) — plan to block,
+ stratify, or randomize across each.
+3. **Pick the design** using the decision tree and reference files.
+4. **Decide replication** at the correct level (and get n from the
+ **statistical-power** skill for the chosen design).
+5. **Generate the layout** with `randomization.py` / `doe_designs.py`, seeded.
+6. **Randomize run/processing order** and plate/batch positions.
+7. **Document** the design, seed, and schedule (pre-register if possible) so the
+ analysis is confirmatory and the layout is auditable.
+8. **Match the analysis to the design** — blocks, strata, clusters, and nesting must
+ appear in the model (hand off to **statistical-analysis** / **statsmodels**).
+
+---
+
+## Resources
+
+### Scripts
+- `scripts/randomization.py` — seeded allocation schedules: `simple_randomization`,
+ `block_randomization`, `stratified_block_randomization`, `cluster_randomization`,
+ `assign_factorial_runs`, `arm_balance`.
+- `scripts/doe_designs.py` — DOE matrices in real units: `full_factorial`,
+ `two_level_factorial`, `fractional_factorial`, `plackett_burman`,
+ `central_composite`, `box_behnken`, `latin_hypercube`.
+
+### References
+- `references/randomization_and_blocking.md` — randomization methods, blocking,
+ stratification, controls, blinding, batch/plate layout.
+- `references/factorial_and_doe.md` — factorial and fractional designs, resolution
+ and aliasing, screening, and response-surface methodology.
+- `references/design_types.md` — completely randomized, randomized block, crossover,
+ repeated-measures, split-plot, Latin-square, cluster, and nested designs; the
+ pseudoreplication problem in depth.
+- `references/sequential_and_adaptive.md` — group-sequential designs, alpha spending,
+ interim stopping, and adaptive sample-size re-estimation.
+
+### Related skills
+- **statistical-power** — required sample size / power for the design you've chosen.
+- **statistical-analysis** — running and reporting the analysis after collection.
+- **statsmodels** / **pymc** — fitting the models the design implies.
+
+### Key references
+- Fisher, R. A. (1935). *The Design of Experiments*.
+- Montgomery, D. C. (2019). *Design and Analysis of Experiments* (10th ed.).
+- Hurlbert, S. H. (1984). Pseudoreplication and the design of ecological field
+ experiments. *Ecological Monographs*, 54(2), 187–211.
+- Lazic, S. E. (2016). *Experimental Design for Laboratory Biologists*.
diff --git a/skills/experimental-design/references/design_types.md b/skills/experimental-design/references/design_types.md
new file mode 100644
index 00000000..f52ebc83
--- /dev/null
+++ b/skills/experimental-design/references/design_types.md
@@ -0,0 +1,129 @@
+# Design Types and the Replication Structure
+
+Choosing the right design structure is mostly about matching the *unit of
+randomization* and the *unit of replication* to your question, and respecting any
+nesting in the analysis. This file walks through the standard structures and then
+treats the single most common fatal error — pseudoreplication — in depth.
+
+## Table of contents
+- [Completely randomized design](#completely-randomized-design)
+- [Randomized complete block design](#randomized-complete-block-design)
+- [Latin square](#latin-square)
+- [Repeated-measures and crossover](#repeated-measures-and-crossover)
+- [Split-plot designs](#split-plot-designs)
+- [Cluster / group-randomized designs](#cluster--group-randomized-designs)
+- [Nested designs and pseudoreplication](#nested-designs-and-pseudoreplication)
+
+## Completely randomized design
+
+Units are assigned to treatments purely at random, no blocking. Simplest design;
+appropriate when units are homogeneous and there's no identifiable nuisance factor.
+Analyze with one-way ANOVA / regression. If units are *not* homogeneous, the
+nuisance variation inflates error — block instead.
+
+## Randomized complete block design
+
+Group units into **blocks** of similar units (day, batch, litter), and randomize all
+treatments *within* each block. Every treatment appears once per block. The
+between-block variation is removed from the error term, sharply increasing precision
+when blocks differ. Analyze with `treatment + block` in the model. This is the
+default upgrade over a completely randomized design whenever a nuisance factor exists.
+
+## Latin square
+
+Controls **two** nuisance factors simultaneously with a square layout: each treatment
+appears exactly once in every row and every column. Classic uses: row = day, column =
+position/order, cell = treatment. Requires #treatments = #rows = #columns, and assumes
+no interactions between the blocking factors and treatment. Efficient when both
+nuisance dimensions matter and runs are limited. (Graeco-Latin squares extend this to
+three nuisance factors.)
+
+## Repeated-measures and crossover
+
+Each subject receives more than one condition, serving as its own control. This
+removes between-subject variation — usually the largest noise source — so these
+designs are far more powerful per subject.
+
+- **Repeated measures:** the same units measured under several conditions or over
+ time.
+- **Crossover:** each subject receives each treatment in sequence, with **washout**
+ periods between to clear carry-over. Subjects are randomized to treatment *orders*
+ (e.g. an AB/BA crossover; or a Williams square for ≥3 treatments to balance order).
+
+Watch for:
+- **Carry-over / residual effects** — an effect of the previous treatment persisting
+ into the next period. Adequate washout is essential; otherwise the design is biased.
+- **Period effects** — systematic change over time (learning, fatigue, disease
+ progression). Balanced orders let you separate period from treatment.
+- **Correlation within subject** — the repeated observations are not independent; the
+ analysis must model it (mixed model / repeated-measures ANOVA). Sample-size/power
+ for these depends on the within-subject correlation — use simulation in the
+ **statistical-power** skill.
+
+## Split-plot designs
+
+Arises when some factors are **hard to change** (applied to large units) and others
+are **easy to change** (applied to sub-units). The hard-to-change factor is randomized
+to whole plots; the easy factor is randomized to subplots within each whole plot.
+Example: oven temperature (whole plot — you can't re-set it per sample) × coating type
+(subplot — applied per sample). Crucially there are **two different error terms** — one
+for whole-plot factors, one for subplot factors — and the analysis must use both.
+Treating a split-plot as a completely randomized factorial gives wrong (usually
+anticonservative) tests for the whole-plot factor. Industrial DOE and agricultural
+trials are full of accidental split-plots; recognize when a factor can't be reset per
+run.
+
+## Cluster / group-randomized designs
+
+When the intervention is delivered to a *group* (a clinic's protocol, a classroom
+curriculum, a village water supply), you can only randomize at the group level. The
+**cluster is the unit of randomization**, and because members of a cluster are
+correlated, it is effectively the unit of replication too.
+
+- Power depends on the number of **clusters** far more than the number of individuals,
+ and on the **intraclass correlation (ICC)**. Adding people to existing clusters
+ helps much less than adding clusters.
+- The **design effect** `DEFF = 1 + (m − 1)·ICC` (m = cluster size) quantifies how
+ much the effective sample size shrinks; even a small ICC with large clusters costs
+ dearly. Power these by simulation (see **statistical-power**).
+- Analyze with a method that accounts for clustering (mixed model with a cluster
+ random effect, or GEE). Analyzing individuals as independent is pseudoreplication.
+
+## Nested designs and pseudoreplication
+
+**Pseudoreplication** is treating non-independent measurements as independent
+replicates. It is the most common and most damaging design error in experimental
+biology, and it cannot be fixed after data collection — only by designing and
+analyzing at the correct level.
+
+The principle: **the replicate is whatever the treatment is independently applied
+and randomized to.** Measurements taken below that level are *technical replicates* —
+they improve the precision of a single unit's value but do **not** add degrees of
+freedom for testing the treatment.
+
+Worked examples:
+- **One dish per treatment, 50 cells imaged.** Treatment applied to the dish ⇒ n = 1
+ per treatment. The 50 cells describe that one dish; they are not 50 independent
+ tests of the treatment. You need multiple independently treated dishes.
+- **3 mice per group, 100 cells each.** n = 3 (mice) for a treatment given to the
+ mouse, not 300 (cells). Average within mouse, or use a mixed model with mouse as a
+ random effect.
+- **One tank of fish given a diet, every fish measured.** The tank is the unit (the
+ diet was randomized to the tank) ⇒ n = number of tanks, not number of fish. Shared
+ tank water, temperature, and social effects make fish within a tank correlated.
+- **Repeated measurements over time on the same subject** are nested within subject;
+ the subject is the replicate.
+
+How to avoid it:
+1. **Identify the experimental unit** = the smallest physical entity to which a
+ treatment level is independently and randomly assigned.
+2. **Replicate at that level** — more independently treated units, not more
+ measurements per unit (though technical replicates can reduce measurement noise).
+3. **Analyze with the nesting respected** — average to the unit level, or fit a mixed
+ model with random effects for the nesting (cells in mice, fish in tanks, time in
+ subjects). The fixed-effect treatment test then uses the correct, larger error and
+ correct degrees of freedom.
+
+Technical replicates are still worth taking — they sharpen each unit's estimate — but
+report and analyze them as what they are, never as independent biological replicates.
+For sample size of nested/clustered designs, use simulation in **statistical-power**.
diff --git a/skills/experimental-design/references/factorial_and_doe.md b/skills/experimental-design/references/factorial_and_doe.md
new file mode 100644
index 00000000..5f0574bb
--- /dev/null
+++ b/skills/experimental-design/references/factorial_and_doe.md
@@ -0,0 +1,130 @@
+# Factorial and Design-of-Experiments (DOE)
+
+When several factors might affect a response, testing them **one factor at a time
+(OFAT)** is both wasteful and blind to interactions. Factorial designs vary factors
+*together*, so you estimate every main effect and interaction from the same runs,
+with better precision per run. This file covers the family of DOE designs and the
+concepts (resolution, aliasing) needed to read them. Generate them with
+`scripts/doe_designs.py`.
+
+## Table of contents
+- [Why factorial beats OFAT](#why-factorial-beats-ofat)
+- [Full factorial (2^k)](#full-factorial)
+- [Fractional factorial (2^(k-p))](#fractional-factorial)
+- [Resolution and aliasing](#resolution-and-aliasing)
+- [Screening designs (Plackett-Burman)](#screening-designs)
+- [Response-surface designs](#response-surface-designs)
+- [Space-filling designs](#space-filling-designs)
+- [Choosing a design](#choosing-a-design)
+
+## Why factorial beats OFAT
+
+Vary one factor while holding others fixed and you (1) spend runs inefficiently and
+(2) can never see **interactions** — cases where the effect of A depends on the level
+of B, which are the rule, not the exception, in real systems. A factorial varies all
+factors simultaneously across runs; each effect is estimated using *all* the data, so
+a 2^k factorial is more precise than k separate OFAT studies of the same size.
+
+## Full factorial
+
+A **2^k** design runs every combination of k factors at two levels (low/high, coded
+−1/+1). It estimates all k main effects and all 2^k − k − 1 interactions.
+
+- Runs = 2^k: 8 for 3 factors, 16 for 4, 32 for 5. Practical to ~5 factors.
+- Use when you have a handful of factors and want a full picture including
+ interactions.
+- `two_level_factorial({"temp": (20,60), "conc": (1,10), "pH": (6,8)})` → 8 runs.
+- For factors with more than two levels, use `full_factorial` with explicit level
+ lists (runs = product of level counts — grows fast).
+
+Add **center points** (all factors at their midpoint) to a two-level design to get a
+cheap check for curvature: if the center response departs from the factorial average,
+a linear model is inadequate and you need a response-surface design.
+
+## Fractional factorial
+
+When k is large, 2^k is too many runs — but most high-order interactions are
+negligible (the *sparsity-of-effects* principle). A **2^(k−p)** fractional factorial
+runs a carefully chosen fraction (1/2, 1/4, ...) of the full design, trading the
+ability to estimate some interactions for far fewer runs.
+
+- `fractional_factorial(factors, generator="a b c abc")` builds a half-fraction of 4
+ factors in 8 runs. The generator string (Yates notation) assigns each factor to a
+ column; a multi-letter token aliases that factor with an interaction.
+- The price is **aliasing**: some effects become indistinguishable. You must know
+ which.
+
+## Resolution and aliasing
+
+**Aliasing** (confounding) means two effects are estimated by the same contrast — the
+data cannot separate them. Which effects are aliased is summarized by the design's
+**resolution**:
+
+| Resolution | Aliasing | Interpretation |
+|------------|----------|----------------|
+| **III** | main effects aliased with 2-factor interactions | Screening only; a "significant" main effect might be an interaction |
+| **IV** | main effects clear of 2FI, but 2FIs aliased with each other | Good for screening; main effects trustworthy |
+| **V** | main effects and 2FIs all clear of each other (aliased with 3FI+) | Can model main effects and 2-factor interactions confidently |
+
+Always state the resolution and inspect the alias structure before interpreting a
+fractional design. Concluding "factor C has no effect" is unsafe if C is aliased with
+a real interaction (it could cancel out). When in doubt, choose a higher-resolution
+generator (more runs) or add runs to **de-alias** (fold-over / augment the design).
+
+## Screening designs
+
+When the goal is to **find the vital few** factors out of many (5, 10, 20+), use a
+screening design that estimates main effects only, as cheaply as possible:
+- **Plackett-Burman** (`plackett_burman`): runs = the next multiple of 4 above k
+ (e.g. 12 runs for up to 11 factors). Resolution III — two-factor interactions are
+ heavily confounded with main effects. Perfect for triage: run it, keep the few
+ factors with large effects, then study those with a full or higher-resolution
+ factorial.
+- Resolution III fractional factorials serve the same purpose.
+
+Screen first, optimize later — don't try to learn interactions and find the optimum
+in one cheap design.
+
+## Response-surface designs
+
+Two-level designs fit only a flat (linear + interaction) model; they cannot locate an
+interior optimum or describe **curvature**. To fit a quadratic and optimize, use a
+response-surface methodology (RSM) design over continuous factors:
+
+- **Central composite design (CCD)** (`central_composite`): a 2^k factorial + center
+ points + axial ("star") points. The axial points add the levels needed to estimate
+ quadratic terms. With `face="circumscribed"` (default) the axial points sit
+ *outside* the factorial box (so actual factor levels exceed your stated low/high);
+ use `face="inscribed"` or `"faced"` to keep everything within the original range.
+- **Box-Behnken** (`box_behnken`, needs ≥3 factors): a quadratic design that avoids
+ the extreme all-low/all-high corners — useful when those corners are unsafe,
+ expensive, or infeasible. More economical than a CCD for 3–5 factors.
+
+Workflow: screen → factorial (find important factors & rough region) → response
+surface (model curvature, locate optimum), often moving the experimental region
+between steps (path of steepest ascent).
+
+## Space-filling designs
+
+For **computer experiments / simulations** (deterministic or expensive models) where
+classical replication and blocking don't apply, you want even coverage of a
+high-dimensional input space:
+- **Latin hypercube** (`latin_hypercube`): each factor's range is divided into
+ n_samples equal bins, sampled once each, arranged to spread points apart
+ (`criterion="maximin"`). Gives good coverage with relatively few points and is the
+ standard input design for surrogate/emulator modeling and sensitivity analysis.
+
+## Choosing a design
+
+| Goal | Factors | Design | Script function |
+|------|---------|--------|-----------------|
+| Screen many factors | 5–20+ | Plackett-Burman / Res III | `plackett_burman` |
+| Main effects, some interactions, few runs | 4–8 | Res IV/V fractional | `fractional_factorial` |
+| All effects + interactions | 2–5 | Full 2^k factorial | `two_level_factorial` |
+| Multi-level categorical | few | Full factorial | `full_factorial` |
+| Optimize a response (curvature) | 2–5 | Central composite / Box-Behnken | `central_composite`, `box_behnken` |
+| Cover a simulation input space | any | Latin hypercube | `latin_hypercube` |
+
+In all cases, **randomize run order** (the scripts do by default) so factors aren't
+confounded with time-related drift, and add center points to two-level designs as a
+curvature check.
diff --git a/skills/experimental-design/references/randomization_and_blocking.md b/skills/experimental-design/references/randomization_and_blocking.md
new file mode 100644
index 00000000..9c9e15e0
--- /dev/null
+++ b/skills/experimental-design/references/randomization_and_blocking.md
@@ -0,0 +1,116 @@
+# Randomization, Blocking, Stratification, and Controls
+
+These are the tools of *local control*: removing or balancing nuisance variation so
+the comparison you care about is clean. Randomization handles the unknown
+confounders; blocking and stratification handle the known ones; controls and
+blinding handle the systematic biases.
+
+## Randomization — why and how
+
+Randomization assigns treatments to units by chance, so that in expectation every
+confounder (measured or not, known or unknown) is balanced across arms. This is the
+foundation of causal inference: without it, an observed difference could always be
+due to some variable that happened to track the grouping.
+
+Use a **seeded, reproducible** schedule (see `scripts/randomization.py`) and follow
+it exactly. Record the seed. "I randomized somehow" is neither auditable nor
+reproducible.
+
+### Methods (and when each is right)
+
+| Method | What it does | Use when |
+|--------|--------------|----------|
+| **Simple** | Independent random assignment per unit | n is large (≳100); simplicity matters; imbalance is tolerable |
+| **Permuted block** | Within each block, arms appear in fixed ratio; order shuffled | You need balance throughout enrollment, or n is small/moderate, or intake is sequential |
+| **Stratified block** | Separate blocks within each level of a prognostic factor | A known covariate (site, sex, stage) must be balanced across arms |
+| **Cluster** | Whole groups (clinics, classes) assigned to arms | The intervention is delivered at a group level |
+| **Minimization** | Adaptively assign to minimize imbalance across several covariates | Many prognostic factors and small n (specialized; not in the script) |
+
+**Simple randomization caveat:** with small n it behaves like flipping a few coins —
+you can easily get 12 vs. 8 instead of 10 vs. 10, and worse for subgroups. Blocking
+fixes this.
+
+**Block size:** must be a multiple of the ratio unit (e.g. for 1:1, sizes 2, 4, 6).
+Smaller blocks balance more tightly but are more predictable in unblinded trials
+(a clinician who knows the block size can guess the last allocation). Vary block
+size or keep it concealed when predictability is a concern.
+
+## Blocking — removing known nuisance variation
+
+A **block** is a group of units expected to be similar (same day, batch, litter,
+plate, instrument run). You randomize treatments *within* each block. The nuisance
+variation between blocks is then removed from the error term, so the treatment
+comparison is more precise — often dramatically so.
+
+Block on anything that (a) you can identify before the experiment and (b) you
+expect to affect the response but isn't of interest itself:
+- **Time:** day, week, session, processing batch.
+- **Space:** plate, plate position/edge, shelf, cage rack, field plot.
+- **Material:** reagent lot, animal litter, cell passage, donor.
+- **People/instruments:** technician, machine, sequencing run.
+
+Rule of thumb: *"Block what you can, randomize what you cannot."* If you suspect a
+factor matters but can't block it, at least randomize across it and record it as a
+covariate.
+
+**Randomized complete block design (RCBD):** every treatment appears once in every
+block. This is the workhorse design — analyze with treatment + block in the model.
+
+## Stratification vs. blocking vs. covariate adjustment
+
+These overlap; the distinction is about *when* you control the variable:
+- **Stratify / block at design time** when the factor is known before assignment and
+ you want guaranteed balance (the safest, since it doesn't rely on a model).
+- **Adjust as a covariate at analysis time** (ANCOVA, regression) when the factor is
+ continuous or measured after assignment. Often you do both: stratify on the big
+ ones, adjust for the rest.
+
+A few strata are better than many: stratifying on too many factors at once leaves
+strata with too few units to block effectively. For many covariates and small n,
+minimization is the alternative.
+
+## Controls
+
+A comparison needs a concurrent baseline. Match the control to the threat you're
+ruling out:
+- **Untreated / standard-of-care control** — isolates the treatment effect from time.
+- **Vehicle / sham control** — isolates the active ingredient from the delivery
+ (injection stress, vehicle solvent, sham surgery).
+- **Positive control** — a treatment known to produce the effect, to confirm the
+ assay can detect one at all.
+- **Concurrent, not historical** — controls run at the same time as the treatment;
+ historical controls reintroduce time confounding.
+
+## Blinding
+
+Blinding prevents expectation from biasing measurement and behavior:
+- **Single-blind:** the subject doesn't know the assignment.
+- **Double-blind:** neither subject nor experimenter/assessor knows.
+- **Blinded outcome assessment:** at minimum, whoever measures the outcome shouldn't
+ know the group — cheap and high-value even in animal/bench work.
+Allocation concealment (the person enrolling can't foresee the next assignment) is
+distinct from blinding and just as important; a sealed seeded schedule provides it.
+
+## Batch effects and plate layout (especially omics / HTS)
+
+Batch effects are systematic technical differences between processing groups and are
+a leading cause of irreproducible high-throughput results.
+- **Never let batch align with the biological condition.** If all cases are in batch
+ 1 and all controls in batch 2, condition and batch are perfectly confounded and
+ no normalization can separate them.
+- **Randomize or block sample-to-batch and position-within-plate.** Spread each
+ condition across all batches and across plate positions.
+- **Avoid edge effects:** evaporation and thermal gradients make outer wells differ;
+ don't load all controls into edge columns. Randomize positions, or include
+ replicates spanning edge and interior.
+- **Include anchor/reference samples** in every batch to estimate and correct batch
+ shifts.
+- Use `assign_factorial_runs()` / the randomization functions to generate a
+ randomized processing order and position map.
+
+## Documentation
+
+Record, and ideally pre-register: the randomization method, the seed, block sizes,
+stratification factors, the schedule itself, and the planned analysis (which must
+include block/stratum/cluster terms). This is what makes the study auditable and the
+primary analysis confirmatory rather than exploratory.
diff --git a/skills/experimental-design/references/sequential_and_adaptive.md b/skills/experimental-design/references/sequential_and_adaptive.md
new file mode 100644
index 00000000..7574996c
--- /dev/null
+++ b/skills/experimental-design/references/sequential_and_adaptive.md
@@ -0,0 +1,97 @@
+# Sequential and Adaptive Designs
+
+A fixed design commits to a single sample size and one analysis at the end.
+**Sequential** and **adaptive** designs allow looks at the data *during* the study and
+let you stop early (for benefit, harm, or futility) or modify the design — saving
+participants, time, and money. The catch: every interim look at the data is another
+chance to cross the significance threshold by luck, so the error rate must be
+controlled explicitly. Peeking at accumulating data and stopping the first time
+p < 0.05 inflates the Type I error rate badly (to ~0.20+ with a few looks) — this is
+the core problem these methods solve.
+
+## Why naive peeking fails
+
+If you test at α = 0.05 at each of K interim analyses and stop at the first
+significant result, the *overall* false-positive rate is far above 0.05 — roughly
+0.08 for 2 looks, ~0.14 for 5, ~0.20 for 10. The fix is to spend your total α across
+the looks so the *cumulative* Type I error stays at 0.05.
+
+## Group-sequential designs
+
+Pre-plan a fixed number of interim analyses (e.g. after 25%, 50%, 75%, 100% of data)
+and use **adjusted, more stringent boundaries** at each look so the overall α is
+preserved. Common boundary families:
+
+- **Pocock:** constant (equally stringent) nominal significance level at every look.
+ Easier to stop early, but pays a larger penalty at the final analysis.
+- **O'Brien–Fleming:** very stringent early (hard to stop in the first looks), relaxing
+ toward the planned final α. Most popular in confirmatory trials because the final
+ boundary is close to the unadjusted 0.05 and early stopping is reserved for dramatic
+ effects.
+- **Alpha-spending functions (Lan–DeMets):** generalize the above by defining how much
+ α is "spent" as a function of information accrued, so the number and timing of looks
+ need not be fixed in advance — only the spending function is.
+
+You can stop for:
+- **Efficacy** — the effect crosses the upper boundary.
+- **Futility** — the effect is so small that continuing is unlikely to ever reach
+ significance (a non-binding or binding lower boundary / conditional power threshold).
+- **Harm** — safety boundary crossed.
+
+Group-sequential designs require a modestly larger maximum sample size than a fixed
+design (to pay for the looks), but the *expected* sample size is usually smaller
+because many trials stop early.
+
+### Tooling
+
+Python support is thinner than for fixed designs; common options:
+- **statsmodels** has limited sequential utilities; for full boundary computation,
+ most practitioners call R packages via `rpy2` or a subprocess:
+ - R `gsDesign` — the standard for group-sequential boundaries and spending functions.
+ - R `rpact` — confirmatory adaptive and group-sequential designs.
+- For custom rules, **simulate** the whole sequential procedure (generate data, apply
+ the boundaries look by look, repeat) to confirm the realized Type I error and to
+ estimate expected sample size and power. This mirrors the simulation approach in the
+ **statistical-power** skill and is the most flexible route.
+
+## Adaptive designs
+
+Broader than group-sequential: the design itself can change at an interim based on
+accumulating data, within a pre-specified plan that still controls error. Main types:
+
+- **Sample-size re-estimation:** recompute the required n at an interim using the
+ observed nuisance parameter (e.g. the variance or control-arm rate), without
+ unblinding the treatment effect. Protects against a misjudged variance at planning.
+- **Adaptive randomization:** shift allocation probabilities toward the better-
+ performing arm as data accrue (response-adaptive), or to improve covariate balance.
+- **Drop-the-loser / arm selection:** start with several arms or doses and drop
+ inferior ones at interims (seamless phase II/III).
+- **Adaptive enrichment:** narrow enrollment to a subgroup that appears to benefit.
+
+Adaptive designs are powerful but easy to get wrong: any adaptation that uses the
+unblinded treatment effect can inflate Type I error and bias the final effect estimate
+unless the method explicitly corrects for it. Two non-negotiables:
+1. **Pre-specify** the adaptation rule and the error-control method before the study.
+2. **Validate by simulation** that the *entire* procedure preserves the Type I error
+ rate and yields acceptable power and unbiased-enough estimates.
+
+## When to use them
+
+- **Confirmatory trials, expensive or risky enrollment** — group-sequential with
+ O'Brien–Fleming boundaries to allow ethical early stopping.
+- **Uncertain nuisance parameters at planning** — blinded sample-size re-estimation.
+- **Many candidate doses/arms** — adaptive arm selection / seamless designs.
+- **Pure exploration / fixed cheap data** — usually not worth the overhead; a fixed
+ design is simpler and the analysis is unambiguous.
+
+## Practical checklist
+
+- Decide the **number and timing** of interim analyses (or the spending function).
+- Choose a **boundary family** matched to how eager you are to stop early.
+- Specify **futility** rules if you want to stop for lack of effect.
+- Inflate the **maximum** sample size to cover the looks; report the **expected**
+ sample size too.
+- Pre-register the full sequential/adaptive plan, including the stopping rules.
+- Have an independent **data monitoring committee** look at unblinded interims in
+ human trials, not the study team.
+- **Simulate** the design end to end to confirm error control before running it.
diff --git a/skills/experimental-design/scripts/doe_designs.py b/skills/experimental-design/scripts/doe_designs.py
new file mode 100644
index 00000000..fcb558f6
--- /dev/null
+++ b/skills/experimental-design/scripts/doe_designs.py
@@ -0,0 +1,181 @@
+"""Design-of-experiments (DOE) matrices as labeled, decoded pandas DataFrames.
+
+pyDOE3 returns designs in *coded* units (-1/+1, or 0..k-1). Researchers want the
+design in *real* factor units (temperature in C, concentration in mM) with named
+columns, randomized run order, and a clear sense of what each design is for. This
+module wraps pyDOE3 to do exactly that.
+
+A `factors` spec maps factor names to their real-world levels:
+ - two-level / continuous: {"temp": (20, 60), "conc": (1, 10)} # (low, high)
+ - multi-level categorical: {"catalyst": ["A", "B", "C"]}
+
+Functions:
+ full_factorial every combination of given levels (cost grows fast)
+ two_level_factorial 2^k full factorial (screening + interactions)
+ fractional_factorial 2^(k-p) fraction (screening many factors cheaply)
+ plackett_burman very economical main-effects-only screening
+ central_composite response-surface design (curvature / optimization)
+ box_behnken response-surface design, no extreme corners
+ latin_hypercube space-filling sample for simulation / computer experiments
+
+Each returns a DataFrame in real units; pass randomize=True (default) to also get
+a randomized 'run_order'. Requires: pyDOE3, numpy, pandas.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import pandas as pd
+
+
+def _decode_two_level(coded, factors):
+ """Map a -1/+1 coded matrix to real (low/high) units per factor."""
+ names = list(factors)
+ out = {}
+ for j, name in enumerate(names):
+ lvl = factors[name]
+ low, high = lvl[0], lvl[1]
+ mid, half = (high + low) / 2.0, (high - low) / 2.0
+ out[name] = mid + coded[:, j] * half
+ return pd.DataFrame(out)
+
+
+def _randomize(df, randomize, seed):
+ if not randomize:
+ return df.reset_index(drop=True)
+ rng = np.random.default_rng(seed)
+ order = rng.permutation(len(df)) + 1
+ df = df.copy()
+ df.insert(0, "run_order", order)
+ return df.sort_values("run_order").reset_index(drop=True)
+
+
+def full_factorial(factors, randomize=True, seed=0):
+ """Every combination of the listed levels.
+
+ factors values are explicit level lists, e.g.
+ {"temp": [20, 40, 60], "catalyst": ["A", "B"]} -> 3*2 = 6 runs.
+ Runs = product of level counts, so this explodes quickly with many factors.
+ """
+ from pyDOE3 import fullfact
+ names = list(factors)
+ levels = [list(factors[n]) for n in names]
+ counts = [len(l) for l in levels]
+ coded = fullfact(counts).astype(int)
+ data = {n: [levels[j][coded[i, j]] for i in range(len(coded))]
+ for j, n in enumerate(names)}
+ return _randomize(pd.DataFrame(data), randomize, seed)
+
+
+def two_level_factorial(factors, randomize=True, seed=0):
+ """Full 2^k factorial: all main effects and all interactions, estimable.
+
+ Each factor needs a (low, high) pair. Use for k up to ~5; beyond that the
+ run count (2^k) gets expensive — switch to fractional_factorial or
+ plackett_burman for screening.
+ """
+ from pyDOE3 import ff2n
+ coded = ff2n(len(factors))
+ return _randomize(_decode_two_level(coded, factors), randomize, seed)
+
+
+def fractional_factorial(factors, generator, randomize=True, seed=0):
+ """2^(k-p) fractional factorial from a generator string.
+
+ `generator` is pyDOE3's Yates notation, e.g. for 4 factors in 8 runs (one of
+ them aliased): "a b c abc". Each token defines a column; multi-letter tokens
+ alias a factor with an interaction (this is the tradeoff — fewer runs, some
+ effects confounded). Choose a higher-resolution generator if you need to
+ separate main effects from two-factor interactions.
+ """
+ from pyDOE3 import fracfact
+ coded = fracfact(generator)
+ if coded.shape[1] != len(factors):
+ raise ValueError(f"generator defines {coded.shape[1]} factors but "
+ f"{len(factors)} were named")
+ return _randomize(_decode_two_level(coded, factors), randomize, seed)
+
+
+def plackett_burman(factors, randomize=True, seed=0):
+ """Plackett-Burman screening design: main effects only, very few runs.
+
+ Ideal for screening many factors (run count is the next multiple of 4 above k)
+ to find the vital few. Two-factor interactions are heavily confounded with main
+ effects, so use it to screen, not to model interactions.
+ """
+ from pyDOE3 import pbdesign
+ coded = pbdesign(len(factors)) # may include extra dummy columns
+ coded = coded[:, :len(factors)]
+ return _randomize(_decode_two_level(coded, factors), randomize, seed)
+
+
+def central_composite(factors, center=(0, 1), alpha="orthogonal",
+ face="circumscribed", randomize=True, seed=0):
+ """Central composite design (CCD) for response-surface / optimization work.
+
+ Adds axial ("star") points and center points to a 2^k factorial so you can fit
+ a quadratic model and locate an optimum. With face='circumscribed' the axial
+ points sit OUTSIDE the (low, high) box (so real levels exceed your stated
+ range); use face='inscribed' or 'faced' to keep everything within range.
+ `center` = (n center pts in factorial block, n in axial block).
+ """
+ from pyDOE3 import ccdesign
+ coded = ccdesign(len(factors), center=center, alpha=alpha, face=face)
+ return _randomize(_decode_two_level(coded, factors), randomize, seed)
+
+
+def box_behnken(factors, center=1, randomize=True, seed=0):
+ """Box-Behnken response-surface design (needs >= 3 factors).
+
+ Like a CCD it fits a quadratic, but it never uses the extreme corner
+ combinations (all-low or all-high), which is useful when those corners are
+ unsafe or infeasible. More economical than a CCD for 3-5 factors.
+ """
+ from pyDOE3 import bbdesign
+ if len(factors) < 3:
+ raise ValueError("box_behnken requires at least 3 factors")
+ coded = bbdesign(len(factors), center=center)
+ return _randomize(_decode_two_level(coded, factors), randomize, seed)
+
+
+def latin_hypercube(factors, n_samples, criterion="maximin", seed=0,
+ randomize=False):
+ """Space-filling Latin hypercube sample over continuous factor ranges.
+
+ For computer experiments / simulations where you want even coverage of a
+ high-dimensional space with relatively few points. Each factor needs a
+ (low, high) range. `criterion`: 'maximin' spreads points apart;
+ 'center'/'centermaximin'/'correlation' are alternatives.
+ """
+ from pyDOE3 import lhs
+ rng_state = int(seed) # pyDOE3 lhs uses numpy global RNG; seed it for repeatability
+ np.random.seed(rng_state)
+ names = list(factors)
+ unit = lhs(len(names), samples=n_samples, criterion=criterion) # in [0,1]
+ out = {}
+ for j, n in enumerate(names):
+ low, high = factors[n][0], factors[n][1]
+ out[n] = low + unit[:, j] * (high - low)
+ df = pd.DataFrame(out)
+ return _randomize(df, randomize, seed)
+
+
+if __name__ == "__main__":
+ f2 = {"temp": (20, 60), "conc": (1, 10), "ph": (6, 8)}
+
+ print("== 2^3 full factorial ==")
+ print(two_level_factorial(f2, seed=1).to_string(index=False))
+
+ print("\n== fractional 2^(4-1), generator 'a b c abc' ==")
+ f4 = {"A": (-1, 1), "B": (-1, 1), "C": (-1, 1), "D": (-1, 1)}
+ print(fractional_factorial(f4, "a b c abc", seed=1).to_string(index=False))
+
+ print("\n== Plackett-Burman screening, 5 factors ==")
+ f5 = {f"x{i}": (0, 1) for i in range(1, 6)}
+ print(f"runs = {len(plackett_burman(f5, randomize=False))}")
+
+ print("\n== central composite (2 factors) ==")
+ print(central_composite({"temp": (20, 60), "conc": (1, 10)}, seed=1).round(2).to_string(index=False))
+
+ print("\n== Latin hypercube, 8 samples over 3 factors ==")
+ print(latin_hypercube(f2, 8, seed=1).round(2).to_string(index=False))
diff --git a/skills/experimental-design/scripts/randomization.py b/skills/experimental-design/scripts/randomization.py
new file mode 100644
index 00000000..8f340eeb
--- /dev/null
+++ b/skills/experimental-design/scripts/randomization.py
@@ -0,0 +1,171 @@
+"""Reproducible randomization / allocation schedules for experiments and trials.
+
+Randomization is what licenses causal inference: it breaks the link between
+treatment assignment and any confounder, measured or not. But "I shuffled it"
+is not enough — the *method* matters (simple vs. blocked vs. stratified) and the
+schedule must be reproducible (seeded) and auditable. This module produces
+allocation tables as pandas DataFrames, with a fixed seed so the exact schedule
+can be regenerated and archived.
+
+Functions:
+ simple_randomization independent coin-flip per unit (can yield imbalance)
+ block_randomization permuted blocks -> balance throughout enrollment
+ stratified_block_randomization blocks within strata -> balance per subgroup
+ cluster_randomization randomize whole clusters (sites/classes), not units
+ assign_factorial_runs randomize the RUN ORDER of a list of design rows
+
+Requires: numpy, pandas.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import pandas as pd
+
+
+def _normalize_ratio(arms, ratio):
+ """Turn arms + integer ratio into a block template list, e.g.
+ arms=['A','B'], ratio=(2,1) -> ['A','A','B']."""
+ if ratio is None:
+ ratio = [1] * len(arms)
+ if len(ratio) != len(arms):
+ raise ValueError("ratio must have one entry per arm")
+ if any(r <= 0 for r in ratio):
+ raise ValueError("ratio entries must be positive integers")
+ template = []
+ for arm, r in zip(arms, ratio):
+ template += [arm] * int(r)
+ return template
+
+
+def simple_randomization(n, arms=("treatment", "control"), ratio=None, seed=0):
+ """Independent random assignment per unit.
+
+ Simplest method; with small n it can produce noticeable arm-size imbalance
+ (like flipping few coins). Fine for large n. Use block_randomization when you
+ need balance, especially for n < ~100 or sequential enrollment.
+ """
+ rng = np.random.default_rng(seed)
+ arms = list(arms)
+ template = _normalize_ratio(arms, ratio)
+ probs = np.array([template.count(a) for a in arms], dtype=float)
+ probs /= probs.sum()
+ assign = rng.choice(arms, size=n, p=probs)
+ return pd.DataFrame({"unit_id": np.arange(1, n + 1), "arm": assign})
+
+
+def block_randomization(n, arms=("treatment", "control"), block_size=None,
+ ratio=None, seed=0):
+ """Permuted-block randomization: balance is maintained throughout enrollment.
+
+ Within each block every arm appears in the specified ratio; the order inside
+ a block is shuffled. block_size must be a multiple of sum(ratio). Leaving it
+ None picks a small valid size. Mild caveat: fixed small blocks are slightly
+ predictable in unblinded trials — vary block size if that matters.
+ """
+ rng = np.random.default_rng(seed)
+ arms = list(arms)
+ template = _normalize_ratio(arms, ratio)
+ unit = len(template)
+ if block_size is None:
+ block_size = unit * 2 # two of each ratio-unit per block
+ if block_size % unit != 0:
+ raise ValueError(f"block_size ({block_size}) must be a multiple of "
+ f"sum(ratio)={unit}")
+ reps = block_size // unit
+
+ out = []
+ block_id = 0
+ while len(out) < n:
+ block = template * reps
+ rng.shuffle(block)
+ for a in block:
+ out.append((len(out) + 1, block_id, a))
+ block_id += 1
+ df = pd.DataFrame(out[:n], columns=["unit_id", "block", "arm"])
+ return df
+
+
+def stratified_block_randomization(strata, arms=("treatment", "control"),
+ block_size=None, ratio=None, seed=0):
+ """Block-randomize independently within each stratum.
+
+ Use when a prognostic variable (site, sex, disease stage) must be balanced
+ across arms. `strata` is a dict {stratum_label: n_in_that_stratum} or a
+ sequence of stratum labels (one per unit). Each stratum gets its own permuted
+ blocks, guaranteeing balance within every subgroup.
+ """
+ if isinstance(strata, dict):
+ items = list(strata.items())
+ else: # sequence of labels
+ s = pd.Series(list(strata))
+ items = list(s.value_counts().sort_index().items())
+
+ frames = []
+ for i, (label, count) in enumerate(items):
+ df = block_randomization(count, arms=arms, block_size=block_size,
+ ratio=ratio, seed=seed + 1 + i)
+ df.insert(1, "stratum", label)
+ frames.append(df)
+ out = pd.concat(frames, ignore_index=True)
+ out["unit_id"] = np.arange(1, len(out) + 1)
+ return out
+
+
+def cluster_randomization(clusters, arms=("treatment", "control"), ratio=None,
+ block_size=None, seed=0):
+ """Randomize whole clusters (clinics, schools, litters) to arms.
+
+ The cluster — not the individual — is the unit of randomization AND the unit
+ of analysis-level independence. `clusters` is a list of cluster IDs (or an int
+ count). Returns one row per cluster. Analyze with a method that accounts for
+ clustering (mixed model / GEE); treating members as independent is
+ pseudoreplication. Uses blocking across clusters for arm balance.
+ """
+ if isinstance(clusters, int):
+ clusters = [f"cluster_{i+1}" for i in range(clusters)]
+ clusters = list(clusters)
+ df = block_randomization(len(clusters), arms=arms, ratio=ratio,
+ block_size=block_size, seed=seed)
+ df = df.drop(columns=["unit_id"])
+ df.insert(0, "cluster_id", clusters)
+ return df
+
+
+def assign_factorial_runs(design_df, seed=0):
+ """Randomize the execution order of a set of design runs (e.g. a DOE matrix).
+
+ Run order matters: executing a factorial design in a systematic order
+ confounds the factors with time/drift (the machine warms up, the reagent
+ degrades). Randomizing run order protects against that. Returns the design
+ with a 'run_order' column and rows sorted by it.
+ """
+ rng = np.random.default_rng(seed)
+ df = design_df.copy().reset_index(drop=True)
+ order = rng.permutation(len(df)) + 1
+ df["run_order"] = order
+ return df.sort_values("run_order").reset_index(drop=True)
+
+
+def arm_balance(df, arm_col="arm", by=None):
+ """Quick check: counts per arm (optionally within each stratum/block)."""
+ if by:
+ return df.groupby([by, arm_col]).size().unstack(fill_value=0)
+ return df[arm_col].value_counts()
+
+
+if __name__ == "__main__":
+ print("== simple (n=10) ==")
+ print(arm_balance(simple_randomization(10, seed=1)).to_dict())
+
+ print("\n== permuted blocks, 2:1 treatment:control, n=12 ==")
+ d = block_randomization(12, arms=["treatment", "control"], ratio=(2, 1), seed=1)
+ print(d.to_string(index=False))
+ print("balance:", arm_balance(d).to_dict())
+
+ print("\n== stratified by site (A=8, B=6) ==")
+ d = stratified_block_randomization({"siteA": 8, "siteB": 6}, seed=1)
+ print(arm_balance(d, by="stratum").to_string())
+
+ print("\n== cluster randomization (6 clinics) ==")
+ print(cluster_randomization(6, seed=1).to_string(index=False))
diff --git a/skills/statistical-power/SKILL.md b/skills/statistical-power/SKILL.md
new file mode 100644
index 00000000..fee7d103
--- /dev/null
+++ b/skills/statistical-power/SKILL.md
@@ -0,0 +1,198 @@
+---
+name: statistical-power
+description: Sample-size and statistical power calculations for planning studies. Use whenever someone asks "how many subjects/samples/replicates do I need", wants an a priori power analysis, a minimum detectable effect (MDE), a power curve, or needs to justify a sample size for a grant, IRB protocol, or pre-registration. Covers closed-form power for t-tests, ANOVA, proportions, correlations, chi-square, and regression, plus simulation-based (Monte Carlo) power for designs with no formula — logistic/Poisson regression, mixed models, cluster-randomized trials, survival, and interactions. Use this skill even when the request only mentions an effect size, alpha, or "80% power" without saying "power analysis" explicitly. For laying out the study (randomization, blocking, factorial/DOE, crossover, sequential designs) use experimental-design; for analyzing data already collected and reporting it use statistical-analysis.
+allowed-tools: Read Write Edit Bash
+compatibility: Requires Python >=3.10. Examples target statsmodels >=0.14.6, scipy >=1.11, pingouin >=0.6, numpy >=1.26, and matplotlib. Optional extras are statsmodels mixed models and lifelines for simulation-based power.
+license: MIT license
+metadata: {"version": "1.0", "skill-author": "K-Dense Inc."}
+---
+
+# Statistical Power & Sample Size
+
+## Overview
+
+Power analysis answers one of the most consequential questions in study planning: **how large a sample do you need to reliably detect an effect of a given size, and what could you detect with the sample you can afford?** An underpowered study wastes resources and produces inconclusive or irreproducible results; an overpowered one wastes participants, money, and (in clinical work) exposes more people to risk than necessary. Getting this right *before* data collection is the single highest-leverage statistical decision in a project.
+
+Four quantities are locked together for any given test: **sample size (n)**, **effect size**, **significance level (α)**, and **power (1 − β)**. Fix any three and the fourth is determined. Every calculation in this skill is some rearrangement of that relationship.
+
+This skill covers the two ways to do power analysis:
+- **Closed-form** formulas (fast, exact for standard tests) — see `references/closed_form_recipes.md`.
+- **Simulation / Monte Carlo** (works for *any* design or model you can simulate and analyze) — see `references/simulation_based_power.md`.
+
+For choosing and converting effect sizes — usually the hardest part — see `references/effect_sizes.md`.
+
+## When to Use This Skill
+
+- Determining required sample size before collecting data (a priori power analysis)
+- Finding the minimum detectable effect (MDE) for a fixed, already-determined sample size
+- Producing power curves (power vs. n, or power vs. effect size) for a grant or protocol
+- Justifying a sample size for an IRB submission, grant, or pre-registration
+- Powering designs with unequal group sizes or non-1:1 allocation
+- Powering anything without a textbook formula (mixed models, logistic/Poisson regression, cluster-randomized trials, survival analysis, mediation, interactions) via simulation
+- Accounting for multiple comparisons, attrition/dropout, or clustering in the sample-size estimate
+
+## Installation
+
+Use **uv**. Pin versions in production; unpinned is fine for exploration.
+
+```bash
+uv pip install "statsmodels>=0.14.6" "scipy>=1.11" "pingouin>=0.6" "numpy>=1.26" matplotlib pandas
+# For simulation-based power of advanced models (optional, add as needed):
+uv pip install lifelines # survival
+# mixed models and GLMs come with statsmodels
+```
+
+**Compatibility note:** use `statsmodels>=0.14.6` with `scipy>=1.11` to avoid `_lazywhere` import errors on SciPy 1.16+. Pingouin 0.5+ renamed power-function arguments to match the names used below.
+
+---
+
+## The one decision that drives everything: the effect size
+
+Power calculations are only as trustworthy as the effect size you feed them. **Do not invent a number.** Use, in rough order of preference:
+
+1. A **minimally important effect** — the smallest effect that would actually change a decision or matter scientifically/clinically (the "smallest effect size of interest", SESOI). This is the most defensible basis: you power to detect what matters, not what you hope to see.
+2. A **pilot or prior-study estimate**, but shrink it — published and pilot effects are inflated by publication bias and the winner's curse. Powering on a raw pilot estimate routinely underpowers the real study.
+3. A **convention** (Cohen's small/medium/large) only as a last resort, and say so explicitly.
+
+Whatever you pick, run a **sensitivity analysis**: report how required n changes across a plausible range of effect sizes, not a single point. A power analysis presented as one number hides its biggest source of uncertainty. See `references/effect_sizes.md` for benchmarks and conversions between d, f, r, η², odds ratios, and Cohen's h/w.
+
+> **Avoid post-hoc ("observed") power.** Computing power from the effect size you just estimated is circular: it is a deterministic function of the p-value and tells you nothing new. If a study is already done and you want to know what it could have detected, report a **sensitivity analysis** (MDE at the achieved n) or, better, the confidence interval around the observed effect. This is a common reviewer complaint — do not produce observed power even if asked without flagging the issue.
+
+---
+
+## Quick recipes (closed-form)
+
+The bundled `scripts/power.py` wraps statsmodels into one consistent interface so you don't have to remember which solver belongs to which test. Run from the skill directory or add `scripts/` to `sys.path`.
+
+```python
+from power import sample_size, power, mde, power_curve
+
+# 1. How many per group to detect Cohen's d = 0.5, two-sided, 80% power?
+sample_size(test="t_ind", effect_size=0.5, power=0.80, alpha=0.05)
+# -> required n per group
+
+# 2. Two groups, 3:1 allocation (e.g. more controls than cases)
+sample_size(test="t_ind", effect_size=0.5, power=0.80, ratio=3.0)
+
+# 3. Fixed n=30/group — what's the minimum detectable d at 80% power?
+mde(test="t_ind", nobs1=30, power=0.80, alpha=0.05)
+
+# 4. One-way ANOVA, 4 groups, detect Cohen's f = 0.25
+sample_size(test="anova", effect_size=0.25, k_groups=4, power=0.80)
+
+# 5. Two proportions: 0.40 vs 0.55 (auto-converts to Cohen's h)
+sample_size(test="two_proportions", prop1=0.40, prop2=0.55, power=0.80)
+
+# 6. Correlation: detect r = 0.30
+sample_size(test="correlation", effect_size=0.30, power=0.80)
+
+# 7. Power curve for the grant figure
+power_curve(test="t_ind", effect_size=0.5, n_range=range(10, 120, 5),
+ save="power_curve.png")
+```
+
+Supported `test=` values: `t_ind` (two independent means), `t_paired`/`t_one` (paired or one-sample mean), `anova` (one-way), `two_proportions`, `one_proportion`, `correlation`, `chi2` (goodness-of-fit / contingency via effect size *w*), `linear_regression` (R² increment / f²). Full argument tables and the underlying statsmodels calls are in `references/closed_form_recipes.md`.
+
+---
+
+## When there is no formula: simulate
+
+Closed-form power exists only for a handful of simple tests. For **logistic/Poisson regression, mixed-effects / repeated-measures models, cluster-randomized trials, survival analysis, mediation, multi-way interactions, or any non-standard analysis**, the right tool is simulation. The logic is always the same three steps:
+
+1. **Simulate** a dataset from your assumed truth (the effect you want to detect, plus realistic noise, baseline rates, cluster structure, etc.).
+2. **Analyze** it with the *exact* test/model you plan to use on the real data.
+3. **Repeat** many times (≥1,000; 5,000–10,000 for a stable estimate near 80%). Power is the fraction of replicates in which the test is significant.
+
+`scripts/simulate_power.py` provides a reusable harness plus worked examples (two-group difference, logistic regression, cluster-randomized trial with an ICC, and a linear mixed model). The core is just:
+
+```python
+from simulate_power import simulate_power
+
+def gen_and_test(n, rng):
+ # build a dataset of size n under the assumed effect, run the planned test,
+ # return True if the result is significant
+ ...
+
+est = simulate_power(gen_and_test, n=200, n_sims=2000, alpha=0.05)
+print(f"Power at n=200: {est.power:.3f} (95% CI {est.ci_low:.3f}-{est.ci_high:.3f})")
+```
+
+Report the **Monte Carlo confidence interval** on the estimate (the harness returns it) so the reader knows whether 0.81 vs. 0.79 is signal or simulation noise. See `references/simulation_based_power.md` for the full patterns, including how to search for the n that hits target power and how to model dropout and clustering.
+
+---
+
+## Adjustments people forget
+
+These routinely make the difference between an adequately powered study and an underpowered one. Apply them explicitly and state that you did.
+
+- **Multiple comparisons.** If the analysis tests *m* hypotheses with a Bonferroni-style correction, power each test at the corrected α (e.g. α/m), which raises n. Better: power on the family-wise or FDR-controlled procedure directly via simulation. Ignoring this silently underpowers every secondary endpoint.
+- **Attrition / dropout / unusable samples.** Power gives the n you need *analyzed*. Inflate the *enrolled* n: `n_enroll = ceil(n_analyzed / (1 − dropout_rate))`. A 20% dropout rate means enrolling 25% more than the formula returns.
+- **Clustering (design effect).** When observations are nested (patients within clinics, cells within animals, repeated measures within subject), the effective sample size is smaller than the raw count. Inflate by the design effect `DEFF = 1 + (m − 1)·ICC`, where *m* is cluster size and ICC the intraclass correlation. Treating clustered data as independent is **pseudoreplication** and badly overstates power — for cluster-randomized designs, simulate instead.
+- **One- vs. two-sided.** Two-sided is the default and almost always the right choice; a one-sided test buys power only by refusing to detect an effect in the unexpected direction. Justify any one-sided test.
+- **Unequal allocation.** Equal groups are most efficient for a fixed total n. If allocation is fixed by design (e.g. 2:1 treatment:control), pass `ratio=` so the calculation reflects it.
+
+---
+
+## Workflow
+
+1. **State the design and the planned analysis.** The test you will run determines the power method. If the analysis is a mixed model or GLM, go straight to simulation.
+2. **Choose the effect size** on a defensible basis (SESOI > shrunk pilot > convention) and write down the justification.
+3. **Set α and target power.** Conventional defaults are α = 0.05 (two-sided) and power = 0.80; 0.90 is common for confirmatory/clinical work. State them.
+4. **Compute** with `scripts/power.py` (closed-form) or `scripts/simulate_power.py` (simulation).
+5. **Sensitivity analysis.** Recompute across a range of plausible effect sizes and produce a power curve. This is the deliverable, not a single number.
+6. **Apply adjustments** for dropout, clustering, and multiplicity.
+7. **Report** following the template below.
+
+---
+
+## Reporting template
+
+A defensible power statement contains every input, so a reader could reproduce it. Adapt:
+
+```
+A priori power analysis was conducted to determine the sample size needed to detect
+a [between-group difference of Cohen's d = 0.50], which we considered the smallest
+effect of clinical interest. With α = .05 (two-sided) and power = .80, a two-sample
+t-test requires n = 64 per group (128 total; computed with statsmodels 0.14).
+Allowing for 20% attrition, we will enrol 160 participants. A sensitivity analysis
+showed required n ranges from 45 to 105 per group across plausible effects
+d = 0.40–0.60 (Figure X).
+```
+
+For simulation: also state the data-generating assumptions (baseline rate, residual SD, ICC, cluster sizes), the number of simulations, and the Monte Carlo CI.
+
+---
+
+## Common pitfalls
+
+1. **Inventing the effect size** or copying an inflated pilot estimate — the most common way power analyses go wrong.
+2. **Reporting a single n** instead of a sensitivity range / power curve.
+3. **Post-hoc / observed power** — circular and uninformative; use sensitivity analysis or the effect-size CI instead.
+4. **Ignoring clustering** (pseudoreplication) — counting cells/measurements as if they were independent subjects.
+5. **Forgetting dropout** — powering the analyzed n but enrolling the same number.
+6. **Confusing α with power**, or one-sided with two-sided.
+7. **Powering only the primary endpoint** while reporting secondary/interaction tests that need far larger n.
+8. **Using a t-test formula for a model you won't actually fit** (e.g. planning a logistic regression with a means-based calculation) — match the power method to the planned analysis.
+
+---
+
+## Resources
+
+### Scripts
+- `scripts/power.py` — unified closed-form interface (`sample_size`, `power`, `mde`, `power_curve`) over statsmodels/pingouin for all standard tests.
+- `scripts/simulate_power.py` — Monte Carlo power harness with `simulate_power()` and `find_sample_size()`, plus worked examples (two-group, logistic regression, cluster-randomized, linear mixed model).
+
+### References
+- `references/closed_form_recipes.md` — per-test argument tables and exact statsmodels/pingouin calls, including proportions, chi-square, and regression.
+- `references/simulation_based_power.md` — full simulation patterns for GLMs, mixed models, cluster designs, survival, and dropout.
+- `references/effect_sizes.md` — choosing effect sizes (SESOI), Cohen's benchmarks, and conversions between d, f, r, η²/f², OR, h, and w.
+
+### Related skills
+- **experimental-design** — once you know n, lay out the actual study (randomization, blocking, factorial/DOE, crossover, sequential designs).
+- **statistical-analysis** — assumption checks, running the test, effect sizes, and APA reporting after data collection.
+- **statsmodels** / **pymc** — fitting the models referenced here.
+
+### Key references
+- Cohen, J. (1988). *Statistical Power Analysis for the Behavioral Sciences* (2nd ed.).
+- Lakens, D. (2022). *Sample Size Justification*. Collabra: Psychology, 8(1).
+- Arnold, B. F. et al. (2011). Simulation methods to estimate design power. *BMC Medical Research Methodology*, 11:94.
diff --git a/skills/statistical-power/references/closed_form_recipes.md b/skills/statistical-power/references/closed_form_recipes.md
new file mode 100644
index 00000000..2289457d
--- /dev/null
+++ b/skills/statistical-power/references/closed_form_recipes.md
@@ -0,0 +1,174 @@
+# Closed-Form Power Recipes
+
+Exact argument tables and the underlying statsmodels/scipy calls for every test
+the `scripts/power.py` helper supports. Use this when you need to call statsmodels
+directly, understand an argument, or handle a case the wrapper doesn't cover.
+
+The four solver quantities — `effect_size`, sample size, `alpha`, `power` — obey
+one identity: pass three, set the fourth to `None`, and `solve_power` returns it.
+
+## Table of contents
+- [Two independent means (t-test)](#two-independent-means)
+- [Paired / one-sample mean](#paired--one-sample-mean)
+- [One-way ANOVA](#one-way-anova)
+- [Two proportions](#two-proportions)
+- [One proportion](#one-proportion)
+- [Correlation](#correlation)
+- [Chi-square (goodness-of-fit / contingency)](#chi-square)
+- [Multiple regression (R² increment)](#multiple-regression)
+- [Effect-size argument cheat sheet](#effect-size-units-per-test)
+
+---
+
+## Two independent means
+
+Effect size = **Cohen's d** = (μ₁ − μ₂) / σ_pooled.
+
+```python
+from statsmodels.stats.power import TTestIndPower
+analysis = TTestIndPower()
+
+# n per group for d=0.5, 80% power, two-sided
+n1 = analysis.solve_power(effect_size=0.5, alpha=0.05, power=0.80,
+ ratio=1.0, alternative="two-sided")
+
+# achieved power at n1=64 per group
+pw = analysis.solve_power(effect_size=0.5, nobs1=64, alpha=0.05,
+ ratio=1.0, alternative="two-sided")
+
+# minimum detectable d at n1=30 per group, 80% power
+d_min = analysis.solve_power(nobs1=30, alpha=0.05, power=0.80, ratio=1.0,
+ alternative="two-sided")
+```
+
+`ratio = nobs2 / nobs1`. For 2:1 allocation set `ratio=2.0`; the returned `nobs1`
+is the smaller group. `alternative` ∈ `"two-sided"`, `"larger"`, `"smaller"`.
+
+## Paired / one-sample mean
+
+Effect size = **Cohen's dz** for paired (mean difference / SD of the differences),
+or d for one-sample. Use `TTestPower` (single-sample solver); `nobs` is the number
+of pairs / observations.
+
+```python
+from statsmodels.stats.power import TTestPower
+TTestPower().solve_power(effect_size=0.4, alpha=0.05, power=0.80,
+ alternative="two-sided") # -> number of pairs
+```
+
+Note: for paired designs dz depends on the within-pair correlation ρ:
+`dz = d_raw / sqrt(2(1−ρ))`. Higher ρ ⇒ larger dz ⇒ smaller n. If you only know
+the raw mean difference and SDs, estimate ρ or simulate.
+
+## One-way ANOVA
+
+Effect size = **Cohen's f** = sqrt(η² / (1 − η²)). `nobs` here is **total** n
+across all groups; divide by `k_groups` for per-group n.
+
+```python
+from statsmodels.stats.power import FTestAnovaPower
+total_n = FTestAnovaPower().solve_power(effect_size=0.25, k_groups=4,
+ alpha=0.05, power=0.80)
+per_group = total_n / 4
+```
+
+Conversions: f = 0.10 (small), 0.25 (medium), 0.40 (large). From η²:
+`f = sqrt(eta2/(1-eta2))`. From R²: same formula with R².
+
+## Two proportions
+
+Effect size = **Cohen's h** = 2·asin(√p₁) − 2·asin(√p₂). Convert proportions to h,
+then use the normal approximation `NormalIndPower`.
+
+```python
+from statsmodels.stats.power import NormalIndPower
+from statsmodels.stats.proportion import proportion_effectsize
+h = proportion_effectsize(0.40, 0.55)
+n1 = NormalIndPower().solve_power(effect_size=h, alpha=0.05, power=0.80,
+ ratio=1.0, alternative="two-sided")
+```
+
+Alternative (exact-ish, gives per-group n directly, handles unequal n via `ratio`):
+
+```python
+from statsmodels.stats.proportion import samplesize_proportions_2indep_onetail
+# one-sided; double alpha intent by passing alpha/... per your convention
+```
+
+For small samples or rare events, prefer **simulation** with the exact test you'll
+run (Fisher's exact, or a chi-square with continuity correction).
+
+## One proportion
+
+Test p against a fixed reference p₀. Convert both to the arcsine scale via Cohen's h
+and treat the reference group as infinite (`ratio=0`).
+
+```python
+from statsmodels.stats.power import NormalIndPower
+from statsmodels.stats.proportion import proportion_effectsize
+h = proportion_effectsize(0.60, 0.50)
+n = NormalIndPower().solve_power(effect_size=h, alpha=0.05, power=0.80, ratio=0.0)
+```
+
+For exact binomial planning use `statsmodels.stats.proportion.proportion_effectsize`
+with the exact-test power via simulation if the sample is small.
+
+## Correlation
+
+Effect size = **Pearson r**. No statsmodels solver; use the Fisher z transform
+(implemented in `power.py`). Required n for r at power 1−β, two-sided:
+
+```
+z_r = arctanh(r)
+n = ((z_{1-α/2} + z_{1-β}) / z_r)^2 + 3
+```
+
+`pingouin.power_corr(r=0.3, power=0.8, alternative="two-sided")` gives the same
+answer if you prefer a library call.
+
+## Chi-square
+
+Effect size = **Cohen's w** = sqrt(Σ (p_i − p0_i)² / p0_i). For a contingency table,
+`w = sqrt(χ²/N)` and equals Cramér's V·sqrt(min(r−1, c−1)). Degrees of freedom:
+goodness-of-fit `dof = k − 1`; contingency `dof = (r−1)(c−1)`. `n_bins = dof + 1`.
+
+```python
+from statsmodels.stats.power import GofChisquarePower
+n = GofChisquarePower().solve_power(effect_size=0.3, n_bins=5, alpha=0.05, power=0.80)
+```
+
+w benchmarks: 0.10 (small), 0.30 (medium), 0.50 (large).
+
+## Multiple regression
+
+Effect size = **Cohen's f²** = R²/(1−R²) for the overall model, or
+ΔR²/(1−R²_full) for a set of added predictors. `power.py` solves this directly via
+the noncentral F (noncentrality λ = f²·n), which is more reliable than
+statsmodels' `FTestPower` for sample-size search.
+
+```python
+from power import sample_size, power
+# detect f^2 = 0.15 from 3 tested predictors (3 total in the model)
+sample_size("linear_regression", effect_size=0.15, df_num=3, k_total=3, power=0.80)
+```
+
+- `df_num` = number of predictors being **tested** (the numerator df).
+- `k_total` = total predictors in the model (including controls). `df_denom = n − k_total − 1`.
+
+f² benchmarks: 0.02 (small), 0.15 (medium), 0.35 (large).
+
+## Effect-size units per test
+
+| Test | `power.py` `test=` | Effect size | Small / Medium / Large |
+|------|--------------------|-------------|------------------------|
+| Two independent means | `t_ind` | Cohen's d | 0.2 / 0.5 / 0.8 |
+| Paired / one-sample | `t_paired`, `t_one` | Cohen's d (dz) | 0.2 / 0.5 / 0.8 |
+| One-way ANOVA | `anova` | Cohen's f | 0.1 / 0.25 / 0.4 |
+| Two proportions | `two_proportions` | Cohen's h (auto from props) | 0.2 / 0.5 / 0.8 |
+| One proportion | `one_proportion` | Cohen's h (auto) | 0.2 / 0.5 / 0.8 |
+| Correlation | `correlation` | Pearson r | 0.1 / 0.3 / 0.5 |
+| Chi-square | `chi2` | Cohen's w | 0.1 / 0.3 / 0.5 |
+| Regression (ΔR²) | `linear_regression` | Cohen's f² | 0.02 / 0.15 / 0.35 |
+
+Benchmarks are last-resort conventions — prefer a smallest-effect-of-interest.
+See `effect_sizes.md`.
diff --git a/skills/statistical-power/references/effect_sizes.md b/skills/statistical-power/references/effect_sizes.md
new file mode 100644
index 00000000..f82a54d6
--- /dev/null
+++ b/skills/statistical-power/references/effect_sizes.md
@@ -0,0 +1,121 @@
+# Choosing and Converting Effect Sizes
+
+The effect size is the input that makes or breaks a power analysis, and it is the
+one people most often get wrong. Power computed from a guessed or inflated effect
+is worse than no power analysis, because it carries false authority. This file
+covers how to pick a defensible value and how to convert between the metrics
+different tests use.
+
+## How to choose (in order of preference)
+
+### 1. Smallest effect size of interest (SESOI) — best
+Power to detect the smallest effect that would actually **change a decision** or
+matter scientifically/clinically, not the effect you hope or expect to see. Ways to
+set it:
+- **Anchor-based:** the smallest difference patients/users can perceive or that
+ crosses a clinical threshold (e.g. a 5-point change on a validated scale).
+- **Resource/decision-based:** the smallest effect that would justify adopting the
+ intervention given its cost.
+- **Benchmark-based:** an effect smaller than which you'd treat the result as
+ practically null.
+
+Powering on the SESOI is the most defensible choice: if the true effect is larger,
+you're even better powered; if it's smaller, you've decided it doesn't matter.
+
+### 2. Prior estimate — but shrink it
+Pilot studies and published effects are **biased upward** (publication bias, the
+"winner's curse," and the fact that significant pilots are the ones that get
+followed up). Powering on a raw pilot d routinely underpowers the real study. If
+you must use a prior estimate:
+- Use the **lower bound of its confidence interval**, or
+- Apply a **shrinkage / safeguard** (e.g. Perugini et al.'s safeguard power uses the
+ CI lower limit), and
+- Never rely on a single small pilot (n < ~50) for a point estimate of the effect.
+
+### 3. Convention — last resort, and say so
+Cohen's small/medium/large are arbitrary and field-blind. They were never meant as
+substitutes for domain knowledge. Use them only when nothing better exists, state
+explicitly that you did, and prefer "small" unless you have a reason — most real
+effects in many fields are small.
+
+## Always do a sensitivity analysis
+Whatever you pick, report how required n varies across a plausible range of effects
+(e.g. a power curve, or a small table of n at d = 0.3, 0.4, 0.5). A single n hides
+the dominant source of uncertainty. This is the actual deliverable of a good power
+analysis.
+
+## Benchmark table (Cohen's conventions)
+
+| Metric | Used for | Small | Medium | Large |
+|--------|----------|-------|--------|-------|
+| d | mean differences (t-tests) | 0.20 | 0.50 | 0.80 |
+| f | ANOVA | 0.10 | 0.25 | 0.40 |
+| f² | regression / multiple R² | 0.02 | 0.15 | 0.35 |
+| r | correlation | 0.10 | 0.30 | 0.50 |
+| η² (eta-squared) | ANOVA variance explained | 0.01 | 0.06 | 0.14 |
+| h | proportions (arcsine) | 0.20 | 0.50 | 0.80 |
+| w | chi-square | 0.10 | 0.30 | 0.50 |
+| OR | 2×2 odds ratio | ~1.5 | ~2.5 | ~4.3 |
+
+(OR benchmarks are very context-dependent and depend on the base rate — treat as
+rough only.)
+
+## Conversions
+
+**d ↔ r** (two-group comparison ↔ point-biserial)
+```
+r = d / sqrt(d^2 + 4) # equal groups
+d = 2r / sqrt(1 - r^2)
+```
+
+**d ↔ Cohen's f** (k groups; for two equal groups f = d/2)
+```
+f = d / 2 # two groups
+```
+
+**f ↔ η²**
+```
+f = sqrt(eta2 / (1 - eta2))
+eta2 = f^2 / (1 + f^2)
+```
+
+**f² ↔ R²** (regression)
+```
+f2 = R2 / (1 - R2) # whole model
+f2 = dR2 / (1 - R2_full) # increment from added predictors
+```
+
+**proportions → Cohen's h**
+```
+h = 2*asin(sqrt(p1)) - 2*asin(sqrt(p2))
+```
+In Python: `statsmodels.stats.proportion.proportion_effectsize(p1, p2)`.
+
+**proportions → Cohen's w** (for chi-square, against expected p0_i)
+```
+w = sqrt( sum( (p_i - p0_i)^2 / p0_i ) )
+```
+For a 2×2 table, `w = sqrt(chi2 / N)`, and `w = V * sqrt(min(r-1, c-1))` where V is
+Cramér's V.
+
+**odds ratio → log-odds** (for logistic-regression power by simulation)
+```
+beta = log(OR) # coefficient to plug into the simulated linear predictor
+```
+
+**standardized → raw**
+A standardized effect is only as good as the SD you divide by. If you know the raw
+difference and the SD, work in raw units and convert at the end:
+`d = (mean1 - mean2) / sd_pooled`. For paired designs, `dz` uses the SD of the
+*differences*, which depends on the within-pair correlation — see
+`closed_form_recipes.md`.
+
+## Common mistakes
+
+- **Using the observed/expected effect instead of the SESOI** — you end up powered
+ for your hopes, not for what matters.
+- **Copying a published d without shrinking** — inflated by publication bias.
+- **Mixing up d and f, or η² and f²** — they differ by the conversions above; a
+ factor-of-2 error in d quadruples or quarters the required n.
+- **Reporting one number** — always show the sensitivity range.
+- **Treating Cohen's benchmarks as truth** — they're conventions, not measurements.
diff --git a/skills/statistical-power/references/simulation_based_power.md b/skills/statistical-power/references/simulation_based_power.md
new file mode 100644
index 00000000..05f3be3f
--- /dev/null
+++ b/skills/statistical-power/references/simulation_based_power.md
@@ -0,0 +1,101 @@
+# Simulation-Based (Monte Carlo) Power
+
+Closed-form power exists for a handful of standard tests. For everything else,
+simulate. This is not a second-best approximation — for complex designs it is the
+*correct* method, and it has one big advantage: the power estimate uses the exact
+analysis you will run on the real data, so there is no mismatch between the
+planning model and the analysis model.
+
+## The recipe (always the same)
+
+1. **Simulate** a dataset of size *n* from your assumed truth: the effect you want
+ to detect, plus realistic structure (baseline rates, residual SD, cluster random
+ effects, dropout, covariate distributions).
+2. **Analyze** it with the *exact* model/test planned for the real study.
+3. **Repeat** R times. Power = fraction of replicates where the test is significant.
+ Use R ≥ 1,000; use 5,000–10,000 for a stable estimate near the 80% decision point.
+
+Always report the **Monte Carlo confidence interval** on the estimate (the
+`scripts/simulate_power.py` harness returns a Wilson interval). With R = 1,000 the
+±2 SE width near p = 0.8 is roughly ±0.025, so don't over-interpret 0.81 vs 0.79.
+
+## Using the harness
+
+`scripts/simulate_power.py` gives you `simulate_power()` and `find_sample_size()`.
+You supply a function `gen_and_test(n, rng) -> bool` that builds one dataset, runs
+the analysis, and returns whether it was significant. The `rng` is a seeded
+`numpy.random.Generator` so runs are reproducible and replicates are independent.
+
+```python
+from simulate_power import simulate_power, find_sample_size
+
+def gen_and_test(n, rng):
+ # ... simulate n observations under the assumed effect ...
+ # ... fit the planned model ...
+ return pvalue < 0.05
+
+# power at a fixed n
+print(simulate_power(gen_and_test, n=200, n_sims=2000))
+
+# search for the n that hits 80% power
+n, est = find_sample_size(gen_and_test, target_power=0.80, n_sims=2000)
+```
+
+The file ships four adaptable examples: two-group difference (a sanity check
+against the closed-form t-test), logistic regression, a cluster-randomized trial
+with an ICC, and a repeated-measures linear mixed model. Copy the closest one and
+edit the data-generating block.
+
+## When you must simulate
+
+| Design / analysis | Why no formula | What to simulate |
+|-------------------|----------------|------------------|
+| Logistic / Poisson regression | Power depends on the full covariate distribution | Generate predictors, compute the linear predictor, draw the outcome, fit the GLM |
+| Mixed-effects / repeated measures | Random effects + within-subject correlation | Draw subject/cluster random effects, then observations; fit `mixedlm` |
+| Cluster-randomized trial | ICC inflates variance; clusters are the unit | Cluster random intercepts via ICC; fit a mixed model or use the design effect |
+| Survival (Cox / log-rank) | Censoring and event-time distribution | Draw event and censoring times; fit `lifelines` CoxPH or run a log-rank test |
+| Interaction terms | Power for an interaction ≪ power for main effects | Generate the factorial structure and the interaction effect; test that coefficient |
+| Mediation | Product-of-coefficients null is non-normal | Simulate the path model; bootstrap or test the indirect effect |
+| Non-standard / custom test | No theory at all | Whatever your analysis script does |
+
+## Key correctness points
+
+- **Analyze exactly as planned.** If the real analysis adjusts for covariates,
+ include them in the simulation. If it uses a robust SE or a specific correction,
+ apply it in `gen_and_test`. The whole value of simulation is fidelity to the plan.
+- **Handle estimation failures.** GLMs and mixed models can fail to converge or hit
+ perfect separation. Wrap the fit in `try/except` and count a failure as
+ *not significant* (conservative). If failures are common, that itself is a
+ warning about the design or sample size.
+- **Watch Type I error too.** As a check, simulate under the *null* (effect = 0)
+ and confirm the rejection rate ≈ α. If it's inflated (common with small-cluster
+ mixed models or naive cluster SEs), your planned analysis is anticonservative and
+ the power number is meaningless until you fix the analysis.
+- **Seed it.** A fixed seed makes the search reproducible and stops `find_sample_size`
+ from chasing simulation noise around the boundary.
+
+## Modeling realistic complications
+
+- **Dropout.** Either simulate missingness directly (drop rows / occasions under
+ the assumed mechanism, then analyze the reduced data — captures the real power
+ loss including any bias), or compute the analyzed n and inflate the enrolled n by
+ `1/(1−dropout)`.
+- **Clustering / ICC.** Split total variance into between-cluster (τ²) and residual
+ (σ²) with `ICC = τ²/(τ²+σ²)`, draw a cluster random effect ~ N(0, τ), add it to
+ every member of the cluster. See `example_cluster_randomized`.
+- **Unequal allocation / stratification.** Generate the exact group sizes and strata
+ the design will produce; don't assume balance the design won't deliver.
+- **Repeated measures.** Subject random intercept (and slope, if relevant) plus a
+ within-subject residual; the within-subject correlation is `τ²/(τ²+σ²)`.
+
+## Reporting a simulation-based power analysis
+
+State enough that someone could rerun it:
+
+```
+Power was estimated by simulation (5,000 replicates per sample size). Data were
+generated assuming a baseline event rate of 20%, a treatment log-odds of 0.8, and
+analyzed with logistic regression adjusting for age and site, matching the planned
+analysis. A sample of n = 150 per arm yielded 82% power (95% Monte Carlo CI
+80.5-83.5%) at α = .05 (two-sided). Code is available at [link].
+```
diff --git a/skills/statistical-power/scripts/power.py b/skills/statistical-power/scripts/power.py
new file mode 100644
index 00000000..27949e44
--- /dev/null
+++ b/skills/statistical-power/scripts/power.py
@@ -0,0 +1,320 @@
+"""Unified closed-form power / sample-size interface over statsmodels and scipy.
+
+One function each for the three things people actually want:
+ - sample_size(...) : solve for n given effect size, alpha, power
+ - power(...) : solve for achieved power given n and effect size
+ - mde(...) : solve for the minimum detectable effect given n and power
+ - power_curve(...) : plot power vs. n (or vs. effect size) for planning figures
+
+Every call routes to the right statsmodels solver based on `test=`, so callers
+don't need to remember which Power class belongs to which test. All four solver
+quantities (effect_size, nobs, alpha, power) obey the identity "fix three, solve
+the fourth"; these helpers just expose that cleanly.
+
+Supported tests:
+ t_ind two independent means (Cohen's d)
+ t_paired/t_one paired or one-sample mean (Cohen's d)
+ anova one-way ANOVA, k groups (Cohen's f)
+ two_proportions two independent proportions (give prop1, prop2; uses Cohen's h)
+ one_proportion one proportion vs. a reference (give prop1, prop0)
+ correlation Pearson r (give effect_size=r)
+ chi2 goodness-of-fit / contingency (Cohen's w; give dof)
+ linear_regression added predictors via Cohen's f^2 (give f2 as effect_size, df_num)
+
+Requires: statsmodels>=0.14.6, scipy>=1.11, numpy, matplotlib.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+
+import numpy as np
+from statsmodels.stats.power import (
+ FTestAnovaPower,
+ GofChisquarePower,
+ NormalIndPower,
+ TTestIndPower,
+ TTestPower,
+)
+from statsmodels.stats.proportion import proportion_effectsize
+
+
+# --------------------------------------------------------------------------- #
+# internal: build the statsmodels solver and the kwargs for the given test
+# --------------------------------------------------------------------------- #
+def _resolve(test, effect_size, alpha, alternative, **kw):
+ """Return (solver, base_kwargs, n_key) for a test.
+
+ n_key is the keyword the solver uses for "number of observations" so the
+ sample_size/power/mde wrappers can fill in the right argument generically.
+ """
+ test = test.lower()
+
+ if test == "t_ind":
+ solver = TTestIndPower()
+ es = effect_size
+ base = dict(effect_size=es, alpha=alpha, alternative=alternative,
+ ratio=kw.get("ratio", 1.0))
+ return solver, base, "nobs1"
+
+ if test in ("t_paired", "t_one"):
+ solver = TTestPower()
+ base = dict(effect_size=effect_size, alpha=alpha, alternative=alternative)
+ return solver, base, "nobs"
+
+ if test == "anova":
+ solver = FTestAnovaPower()
+ k = kw.get("k_groups")
+ if k is None:
+ raise ValueError("anova requires k_groups=")
+ base = dict(effect_size=effect_size, alpha=alpha, k_groups=k)
+ return solver, base, "nobs" # nobs = TOTAL n across all groups
+
+ if test == "two_proportions":
+ # convert proportions to Cohen's h, then use the normal approximation
+ p1, p2 = kw.get("prop1"), kw.get("prop2")
+ if p1 is None or p2 is None:
+ raise ValueError("two_proportions requires prop1= and prop2=")
+ h = proportion_effectsize(p1, p2)
+ solver = NormalIndPower()
+ base = dict(effect_size=h, alpha=alpha, alternative=alternative,
+ ratio=kw.get("ratio", 1.0))
+ return solver, base, "nobs1"
+
+ if test == "one_proportion":
+ p1, p0 = kw.get("prop1"), kw.get("prop0")
+ if p1 is None or p0 is None:
+ raise ValueError("one_proportion requires prop1= and prop0=")
+ h = proportion_effectsize(p1, p0)
+ # one-sample: NormalIndPower with an effectively infinite second group
+ solver = NormalIndPower()
+ base = dict(effect_size=h, alpha=alpha, alternative=alternative, ratio=0.0)
+ return solver, base, "nobs1"
+
+ if test == "correlation":
+ # Power for Pearson r via Fisher z; handled analytically below, but we
+ # still route through a solver-shaped object for a uniform interface.
+ return "correlation", dict(effect_size=effect_size, alpha=alpha,
+ alternative=alternative), "nobs"
+
+ if test == "chi2":
+ solver = GofChisquarePower()
+ dof = kw.get("dof")
+ if dof is None:
+ raise ValueError("chi2 requires dof= (n_bins-1, or (r-1)(c-1))")
+ base = dict(effect_size=effect_size, alpha=alpha, n_bins=dof + 1)
+ return solver, base, "nobs"
+
+ if test == "linear_regression":
+ # Handled by a dedicated noncentral-F solver (statsmodels' FTestPower is
+ # unreliable when solving for sample size). See _reg_* helpers below.
+ df_num = kw.get("df_num")
+ if df_num is None:
+ raise ValueError("linear_regression requires df_num= (number of tested predictors)")
+ return "regression", dict(effect_size=effect_size, alpha=alpha,
+ df_num=df_num,
+ k_total=kw.get("k_total", df_num)), "nobs"
+
+ raise ValueError(f"unknown test '{test}'")
+
+
+# --------------------------------------------------------------------------- #
+# correlation power (Fisher z transform) -- closed form, no statsmodels solver
+# --------------------------------------------------------------------------- #
+def _corr_power(r, n, alpha, alternative):
+ from scipy import stats
+ z = math.atanh(r)
+ se = 1.0 / math.sqrt(n - 3)
+ if alternative == "two-sided":
+ zc = stats.norm.ppf(1 - alpha / 2)
+ else:
+ zc = stats.norm.ppf(1 - alpha)
+ return float(stats.norm.cdf(z / se - zc) + stats.norm.cdf(-z / se - zc))
+
+
+def _corr_sample_size(r, alpha, power, alternative):
+ from scipy import stats
+ z = abs(math.atanh(r))
+ if alternative == "two-sided":
+ zc = stats.norm.ppf(1 - alpha / 2)
+ else:
+ zc = stats.norm.ppf(1 - alpha)
+ zp = stats.norm.ppf(power)
+ return ((zc + zp) / z) ** 2 + 3
+
+
+# --------------------------------------------------------------------------- #
+# multiple-regression power via the noncentral F (Cohen's f^2)
+# --------------------------------------------------------------------------- #
+def _reg_power(f2, n, df_num, k_total, alpha):
+ """Power of the F-test for df_num tested predictors in a model with k_total
+ total predictors, total sample size n. Noncentrality lambda = f^2 * n."""
+ from scipy import stats
+ df_denom = n - k_total - 1
+ if df_denom < 1:
+ return 0.0
+ ncp = f2 * n
+ crit = stats.f.ppf(1 - alpha, df_num, df_denom)
+ return float(1 - stats.ncf.cdf(crit, df_num, df_denom, ncp))
+
+
+def _reg_sample_size(f2, df_num, k_total, alpha, power):
+ n = k_total + 2 # smallest n with df_denom >= 1
+ while _reg_power(f2, n, df_num, k_total, alpha) < power:
+ n += 1
+ if n > 1_000_000:
+ raise RuntimeError("sample size did not converge below 1e6")
+ return n
+
+
+def _reg_mde(n, df_num, k_total, alpha, power):
+ """Smallest detectable f^2 at fixed n (bisection)."""
+ lo, hi = 1e-6, 100.0
+ for _ in range(200):
+ mid = (lo + hi) / 2
+ if _reg_power(mid, n, df_num, k_total, alpha) < power:
+ lo = mid
+ else:
+ hi = mid
+ return (lo + hi) / 2
+
+
+# --------------------------------------------------------------------------- #
+# public API
+# --------------------------------------------------------------------------- #
+def sample_size(test, effect_size=None, alpha=0.05, power=0.80,
+ alternative="two-sided", round_up=True, **kw):
+ """Solve for required sample size.
+
+ For per-group tests (t_ind, two_proportions) returns n PER GROUP.
+ For anova returns TOTAL n across all groups. For chi2/regression returns total n.
+ """
+ solver, base, n_key = _resolve(test, effect_size, alpha, alternative, **kw)
+
+ if solver == "correlation":
+ n = _corr_sample_size(effect_size, alpha, power, alternative)
+ return math.ceil(n) if round_up else n
+
+ if solver == "regression":
+ return _reg_sample_size(base["effect_size"], base["df_num"],
+ base["k_total"], alpha, power)
+
+ base["power"] = power
+ base[n_key] = None
+ n = solver.solve_power(**base)
+ if round_up:
+ n = math.ceil(n)
+ return n
+
+
+def power(test, effect_size=None, nobs1=None, nobs=None, alpha=0.05,
+ alternative="two-sided", **kw):
+ """Solve for achieved power given the sample size.
+
+ Pass nobs1 for per-group tests (t_ind, two_proportions), nobs for total-n tests.
+ """
+ solver, base, n_key = _resolve(test, effect_size, alpha, alternative, **kw)
+
+ n = nobs1 if nobs1 is not None else nobs
+ if n is None:
+ raise ValueError("provide nobs1= (per-group tests) or nobs= (total-n tests)")
+
+ if solver == "correlation":
+ return _corr_power(effect_size, n, alpha, alternative)
+
+ if solver == "regression":
+ return _reg_power(base["effect_size"], n, base["df_num"],
+ base["k_total"], alpha)
+
+ base[n_key] = n
+ return float(solver.solve_power(**base))
+
+
+def mde(test, nobs1=None, nobs=None, alpha=0.05, power=0.80,
+ alternative="two-sided", **kw):
+ """Solve for the minimum detectable effect (standardized) at a fixed n.
+
+ Returns the effect size in the test's native units (d, f, h, w, r, ...).
+ """
+ solver, base, n_key = _resolve(test, None, alpha, alternative, **kw)
+
+ n = nobs1 if nobs1 is not None else nobs
+ if n is None:
+ raise ValueError("provide nobs1= or nobs=")
+
+ if solver == "correlation":
+ # invert the Fisher-z sample-size formula
+ from scipy import stats
+ zc = stats.norm.ppf(1 - alpha / 2) if alternative == "two-sided" \
+ else stats.norm.ppf(1 - alpha)
+ zp = stats.norm.ppf(power)
+ z = (zc + zp) / math.sqrt(n - 3)
+ return float(math.tanh(z))
+
+ if solver == "regression":
+ return _reg_mde(n, base["df_num"], base["k_total"], alpha, power)
+
+ base["power"] = power
+ base["effect_size"] = None
+ base[n_key] = n
+ return float(solver.solve_power(**base))
+
+
+def power_curve(test, effect_size=None, n_range=None, alpha=0.05, power_target=0.80,
+ alternative="two-sided", save=None, show=False, **kw):
+ """Plot power vs. sample size. Returns (n_array, power_array).
+
+ n_range iterates the per-group n for per-group tests, total n otherwise.
+ """
+ import matplotlib.pyplot as plt
+
+ if n_range is None:
+ n_range = range(5, 205, 5)
+ ns = np.array(list(n_range), dtype=float)
+
+ pwr = []
+ for n in ns:
+ if test in ("t_ind", "two_proportions"):
+ pwr.append(power(test, effect_size=effect_size, nobs1=n, alpha=alpha,
+ alternative=alternative, **kw))
+ else:
+ pwr.append(power(test, effect_size=effect_size, nobs=n, alpha=alpha,
+ alternative=alternative, **kw))
+ pwr = np.array(pwr)
+
+ fig, ax = plt.subplots(figsize=(7, 4.5))
+ ax.plot(ns, pwr, lw=2)
+ ax.axhline(power_target, ls="--", color="crimson", lw=1,
+ label=f"target power = {power_target:g}")
+ ax.set_xlabel("Sample size" + (" per group" if test in ("t_ind", "two_proportions") else " (total)"))
+ ax.set_ylabel("Power (1 - β)")
+ ax.set_ylim(0, 1.02)
+ es_label = effect_size if effect_size is not None else ""
+ ax.set_title(f"Power curve: {test} (effect = {es_label}, α = {alpha:g})")
+ ax.legend()
+ ax.grid(alpha=0.3)
+ fig.tight_layout()
+
+ if save:
+ fig.savefig(save, dpi=150)
+ if show:
+ plt.show()
+ plt.close(fig)
+ return ns, pwr
+
+
+if __name__ == "__main__":
+ # quick smoke test of the main paths
+ print("t_ind d=0.5, 80% power -> n/group =",
+ sample_size("t_ind", effect_size=0.5, power=0.80))
+ print("anova f=0.25, k=4, 80% -> total n =",
+ sample_size("anova", effect_size=0.25, k_groups=4, power=0.80))
+ print("2 props 0.40 vs 0.55, 80% -> n/group =",
+ sample_size("two_proportions", prop1=0.40, prop2=0.55, power=0.80))
+ print("correlation r=0.30, 80% -> n =",
+ sample_size("correlation", effect_size=0.30, power=0.80))
+ print("MDE for t_ind at n=30/group, 80% power -> d =",
+ round(mde("t_ind", nobs1=30, power=0.80), 3))
+ print("power for t_ind d=0.5 at n=64/group ->",
+ round(power("t_ind", effect_size=0.5, nobs1=64), 3))
diff --git a/skills/statistical-power/scripts/simulate_power.py b/skills/statistical-power/scripts/simulate_power.py
new file mode 100644
index 00000000..8b55b376
--- /dev/null
+++ b/skills/statistical-power/scripts/simulate_power.py
@@ -0,0 +1,217 @@
+"""Monte Carlo power for designs with no closed-form formula.
+
+Closed-form power covers a handful of standard tests. For anything else --
+logistic/Poisson regression, mixed-effects models, cluster-randomized trials,
+survival analysis, mediation, interactions -- you estimate power by simulation:
+
+ 1. simulate a dataset under the assumed truth
+ 2. analyze it with the EXACT test/model you will use on real data
+ 3. repeat many times; power = fraction of replicates that reach significance
+
+This module provides the harness (`simulate_power`, `find_sample_size`) plus four
+worked, runnable examples. Copy an example and swap in your own data-generating
+process and analysis -- that is the intended workflow.
+
+Requires: numpy, scipy, statsmodels. The survival example also needs lifelines.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+
+import numpy as np
+
+
+@dataclass
+class PowerEstimate:
+ power: float
+ n_sims: int
+ n: int
+ ci_low: float
+ ci_high: float
+
+ def __str__(self):
+ return (f"n={self.n}: power={self.power:.3f} "
+ f"(95% MC CI {self.ci_low:.3f}-{self.ci_high:.3f}, {self.n_sims} sims)")
+
+
+def _wilson_ci(k, n, z=1.96):
+ """Wilson score interval for a proportion -- the right CI for a simulated rate."""
+ if n == 0:
+ return (0.0, 1.0)
+ p = k / n
+ denom = 1 + z**2 / n
+ center = (p + z**2 / (2 * n)) / denom
+ half = z * math.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denom
+ return (max(0.0, center - half), min(1.0, center + half))
+
+
+def simulate_power(gen_and_test, n, n_sims=2000, alpha=0.05, seed=0):
+ """Estimate power at sample size `n`.
+
+ gen_and_test(n, rng) -> bool : build a dataset of size n under the assumed
+ effect, run the planned analysis, and return True iff it is significant.
+ It receives a numpy Generator `rng` so results are reproducible and each
+ replicate is independent. (Take alpha into account inside the function,
+ or compare a returned p-value yourself; see examples.)
+
+ Returns a PowerEstimate including a Wilson confidence interval, so you can
+ tell whether 0.81 vs 0.79 is real or just simulation noise.
+ """
+ rng = np.random.default_rng(seed)
+ hits = 0
+ for _ in range(n_sims):
+ if gen_and_test(n, rng):
+ hits += 1
+ lo, hi = _wilson_ci(hits, n_sims)
+ return PowerEstimate(power=hits / n_sims, n_sims=n_sims, n=n,
+ ci_low=lo, ci_high=hi)
+
+
+def find_sample_size(gen_and_test, target_power=0.80, n_sims=2000, alpha=0.05,
+ lo=10, hi=2000, seed=0, verbose=True):
+ """Smallest n reaching target_power, via bisection over n.
+
+ Assumes power is (roughly) monotincreasing in n -- true for essentially all
+ real designs. Uses a fixed seed per n so the search is stable; widen n_sims
+ near the boundary if the curve is noisy. Returns (n, PowerEstimate).
+ """
+ # expand hi until it clears target (guards against too-small upper bound)
+ while True:
+ est_hi = simulate_power(gen_and_test, hi, n_sims, alpha, seed)
+ if est_hi.power >= target_power or hi >= 1_000_000:
+ break
+ lo, hi = hi, hi * 2
+
+ best = est_hi
+ while lo < hi:
+ mid = (lo + hi) // 2
+ est = simulate_power(gen_and_test, mid, n_sims, alpha, seed)
+ if verbose:
+ print(est)
+ if est.power >= target_power:
+ hi, best = mid, est
+ else:
+ lo = mid + 1
+ return hi, best
+
+
+# ========================================================================== #
+# Worked examples -- run this file directly to see them.
+# Each is a `gen_and_test(n, rng)` you can adapt.
+# ========================================================================== #
+
+def example_two_group_difference(effect=0.5, sd=1.0, alpha=0.05):
+ """Two-group difference in means (sanity check vs. the closed-form t-test)."""
+ from scipy import stats
+
+ def gen_and_test(n, rng): # n per group
+ a = rng.normal(0.0, sd, n)
+ b = rng.normal(effect, sd, n)
+ _, p = stats.ttest_ind(a, b)
+ return p < alpha
+
+ return gen_and_test
+
+
+def example_logistic_regression(beta=0.8, base_rate=0.2, x_sd=1.0, alpha=0.05):
+ """Power for a single coefficient in logistic regression.
+
+ beta is the log-odds change per 1-SD increase in a continuous predictor x.
+ No closed form -- this is the canonical reason to simulate.
+ """
+ import statsmodels.api as sm
+
+ intercept = math.log(base_rate / (1 - base_rate))
+
+ def gen_and_test(n, rng):
+ x = rng.normal(0, x_sd, n)
+ logit = intercept + beta * x
+ p = 1 / (1 + np.exp(-logit))
+ y = rng.binomial(1, p)
+ X = sm.add_constant(x)
+ try:
+ res = sm.Logit(y, X).fit(disp=0)
+ return res.pvalues[1] < alpha
+ except Exception:
+ return False # non-convergence / perfect separation -> not significant
+
+ return gen_and_test
+
+
+def example_cluster_randomized(effect=0.3, icc=0.05, cluster_size=20,
+ resid_sd=1.0, alpha=0.05):
+ """Cluster-randomized trial: clusters (not individuals) are randomized.
+
+ Ignoring the clustering (analyzing individuals as independent) would badly
+ overstate power -- that is pseudoreplication. Here `n` is the number of
+ clusters PER ARM; the analysis is a mixed model with a random cluster intercept.
+ """
+ import statsmodels.formula.api as smf
+ import pandas as pd
+
+ # split total variance into between-cluster (tau^2) and residual by the ICC
+ tau = math.sqrt(icc * resid_sd**2 / (1 - icc)) if icc > 0 else 0.0
+
+ def gen_and_test(n, rng): # n clusters per arm
+ rows = []
+ cid = 0
+ for arm in (0, 1):
+ for _ in range(n):
+ u = rng.normal(0, tau) # cluster random effect
+ for _ in range(cluster_size):
+ y = effect * arm + u + rng.normal(0, resid_sd)
+ rows.append((y, arm, cid))
+ cid += 1
+ df = pd.DataFrame(rows, columns=["y", "arm", "cluster"])
+ try:
+ res = smf.mixedlm("y ~ arm", df, groups=df["cluster"]).fit()
+ return res.pvalues["arm"] < alpha
+ except Exception:
+ return False
+
+ return gen_and_test
+
+
+def example_linear_mixed_repeated(effect=0.4, n_timepoints=3, subj_sd=0.7,
+ resid_sd=1.0, alpha=0.05):
+ """Repeated-measures: a linear time trend within subjects, random intercepts.
+
+ `n` is the number of subjects; each is measured at n_timepoints occasions.
+ `effect` is the slope per time unit. Tests whether the time slope != 0.
+ """
+ import statsmodels.formula.api as smf
+ import pandas as pd
+
+ def gen_and_test(n, rng): # n subjects
+ rows = []
+ for s in range(n):
+ b0 = rng.normal(0, subj_sd)
+ for t in range(n_timepoints):
+ y = b0 + effect * t + rng.normal(0, resid_sd)
+ rows.append((y, t, s))
+ df = pd.DataFrame(rows, columns=["y", "time", "subj"])
+ try:
+ res = smf.mixedlm("y ~ time", df, groups=df["subj"]).fit()
+ return res.pvalues["time"] < alpha
+ except Exception:
+ return False
+
+ return gen_and_test
+
+
+if __name__ == "__main__":
+ print("== two-group difference (compare to closed-form t-test n/group=64) ==")
+ g = example_two_group_difference(effect=0.5)
+ print(simulate_power(g, n=64, n_sims=2000))
+
+ print("\n== logistic regression, beta=0.8 ==")
+ g = example_logistic_regression(beta=0.8, base_rate=0.2)
+ print(simulate_power(g, n=150, n_sims=1000))
+
+ print("\n== search: subjects needed for repeated-measures slope=0.4 ==")
+ g = example_linear_mixed_repeated(effect=0.4, n_timepoints=3)
+ n, est = find_sample_size(g, target_power=0.80, n_sims=500, lo=10, hi=60,
+ verbose=False)
+ print(f"-> need ~{n} subjects ({est})")