Generated banner for Statistical Power
Generated logo for Statistical Power

Statistical Power

K-DenseCommunityCreated by K-Dense Inc.

  • Skill
  • Research and analysis
  • Science and research
  • MIT
  • Low risk
  • Has scripts

From the author

Calculates sample sizes and statistical power for study planning. Applies when 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 complex designs — logistic/Poisson regression, mixed models, cluster-randomized trials, survival, and interactions. Also handles requests that only mention 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.
— the description by K-Dense Inc.

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a robust framework for conducting a priori power analysis to determine the necessary sample size for scientific studies. It supports both closed-form analytical calculations for standard tests (t-tests, ANOVA, proportions, correlations, regression) and simulation-based (Monte Carlo) methods for complex designs like mixed models, cluster-randomized trials, and survival analysis. The skill emphasizes defensible effect size selection, sensitivity analysis, and proper accounting for study design factors such as attrition, clustering, and multiple comparisons.

What it does

  • Calculates required sample sizes for various statistical tests.
  • Determines minimum detectable effects (MDE) for fixed sample sizes.
  • Generates power curves to visualize the relationship between sample size and power.
  • Performs simulation-based power analysis for complex or non-standard study designs.
  • Provides guidance on selecting and justifying effect sizes based on scientific relevance.
  • Offers a standardized reporting template for grant and IRB documentation.

When to use it

  • Before collecting data to ensure a study is adequately powered.
  • When justifying sample size requirements for grant applications or IRB protocols.
  • When planning complex experiments involving clustering, repeated measures, or survival analysis.
  • When you need to perform a sensitivity analysis to understand how sample size requirements change with different effect size assumptions.
  • When you need to account for expected participant attrition or dropout in your study design.

Advantages

  • Promotes rigorous study planning by discouraging arbitrary effect size selection.
  • Supports both simple analytical tests and complex simulation-based designs.
  • Encourages sensitivity analysis over single-point estimates to better reflect uncertainty.
  • Provides a consistent interface for multiple statistical tests.
  • Helps prevent common pitfalls like pseudoreplication and ignoring attrition.

Usage examples

“Calculate the sample size needed for a two-sample t-test to detect a Cohen's d of 0.5 with 80% power and alpha 0.05.”
The skill returns the required number of subjects per group, accounting for the specified effect size and power parameters.
“I am planning a cluster-randomized trial. How can I estimate power?”
The skill provides a simulation harness to model the cluster structure, ICC, and planned analysis to estimate power via Monte Carlo methods.
“Generate a power curve for a one-way ANOVA with 4 groups to detect an effect size f of 0.25.”
The skill produces a plot showing how power increases as the total sample size varies, useful for grant proposal figures.
“What is the minimum detectable effect for a study with 30 subjects per group at 80% power?”
The skill calculates the smallest effect size (MDE) that the study is capable of detecting given the fixed sample size and power constraints.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/k-dense-ai/statistical-power/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip statistical-power.zip -d .agents/skills

Documentation by K-Dense Inc.

Statistical Power & Sample Size

Overview

Power analysis plans the probability of rejecting a specified null under an assumed alternative. It answers how many independent experimental units are needed to detect a scientifically important effect, or what effects a feasible sample could detect. Choose the inferential goal first: precision, equivalence, noninferiority, or sequential monitoring need their own calculations; the bundled superiority-test helpers do not cover them.

Four quantities are locked together for any given test: sample size (n), effect size, significance level (α), and power (1 − β). For a fixed design, analysis, and nuisance parameters, fixing three permits solving for the fourth when a solution exists. Every calculation in this skill is some rearrangement of that relationship.

This skill covers the two ways to do power analysis:

  • Analytical power calculations (exact under some standard-test assumptions; asymptotic approximations for others) — see references/closed_form_recipes.md.

  • Simulation / Monte Carlo (requires a credible data-generating process and a calibrated planned analysis) — 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

  • Planning complex mixed models, GLMs, clustering, survival, mediation, and interactions through simulation when simpler approximations do not fit

  • Accounting for multiple comparisons, attrition/dropout, or clustering in the sample-size estimate

Installation

The local examples were checked on Python 3.13 with statsmodels 0.15.0, SciPy 1.18.1, NumPy 2.5.3, pandas 2.3.3, and Matplotlib 3.11.2. Use an environment separate from the repository's development environment:

uv venv --python 3.13 .venv-power
uv pip install --python .venv-power/bin/python "statsmodels==0.15.0" "scipy==1.18.1" "numpy==2.5.3" "pandas==2.3.3" "matplotlib==3.11.2"
# Optional comparison / survival methods (also checked for current API use):
uv pip install --python .venv-power/bin/python "pingouin==0.7.0" "lifelines==0.30.3"

On Windows use .venv-power/Scripts/python.exe. Lifelines 0.30.3 requires pandas<3; the tested pin above accommodates it. Mixed models and GLMs are included in statsmodels. Record versions and seeds with the output; numerical smoke tests do not establish a study's effect assumptions or Type I error control.


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, with uncertainty and selection bias considered. Small pilots are imprecise; publication or significance-based selection can inflate effects. Use a justified uncertainty model or sensitivity range instead of an arbitrary shrinkage factor.

  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: for standard tests it largely restates the test statistic/p-value and adds no independent evidence of adequacy. 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 and SciPy into one consistent interface so you don't have to remember which solver belongs to which test. Run from skills/statistical-power/scripts/ or add that directory to sys.path.

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)
# -> 64 in sample 1; equal allocation gives 64 in sample 2

# 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")

For two-sample tests the return is n1, with n2 = ceil(ratio * n1); ratio=n2/n1. Recheck power using the realized integer ratio. ANOVA rounds total n to a multiple of k_groups; paired n counts pairs. One-sided alternatives use signed effects and "larger"/"smaller". Proportion MDEs return signed Cohen's h and need a baseline to convert to feasible probabilities.

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 analytical assumptions do not fit: simulate

Use an analytical method when its design and assumptions match the planned analysis. For logistic/Poisson regression, mixed-effects / repeated-measures models, cluster-randomized trials, survival analysis, mediation, or multi-way interactions, simulation is often useful when available approximations omit material design features. 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:

from simulate_power import simulate_power, example_two_group_difference

# Runnable software check: n is per group, effect is a raw mean difference.
gen_and_test = example_two_group_difference(effect=0.5, sd=1.0, alpha=0.05)
est = simulate_power(gen_and_test, n=64, n_sims=2000, alpha=0.05, seed=0)
print(est)  # power, 95% Monte Carlo CI, failure and warning counts

The callback must return a boolean rejection decision using the planned alpha internally. The harness's alpha argument does not threshold returned p-values or pass alpha into the callback; returning a raw p-value now raises TypeError instead of counting a nonzero float as rejection. The harness rejects nonpositive sample/replicate counts and invalid search bounds; an unmet target at the sample-size cap raises an explicit error. The examples check convergence and finite p-values. Expected failures raise SimulationFitError; the harness counts them as non-rejections and reports n_failures/failure_reasons, retaining every replicate in the denominator. It also reports warning counts; unexpected errors propagate. First check Type I error under the null. A noisy bisection search yields a candidate n: verify nearby sizes with more replicates and a fresh seed.

Report the Monte Carlo confidence interval on the estimate (the harness returns it) to quantify simulation sampling error; it does not cover uncertainty in the assumed effect, model, or adaptively chosen n. 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. Specify which primary, co-primary, secondary, or interaction claims need adequate power and which multiplicity procedure applies; secondary endpoints need not all be confirmatory.

  • 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). For equal-size parallel clusters with exchangeable correlation, DEFF = 1 + (m − 1)·ICC is a planning approximation. It is not a universal adjustment for repeated-measures contrasts, unequal cluster sizes, or few clusters. Model those structures directly. 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 the equal-variance, equal-cost two-mean design used here; different costs or variances can change the optimum. 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. Define the estimand, independent experimental unit, allocation, direction, nuisance assumptions, and exact planned analysis; choose a matching analytical method or 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
equal-variance t-test requires n = 64 per group (128 total; statsmodels 0.15.0).
Allowing for 20% attrition, we will enrol 160 participants. A sensitivity analysis
showed required n ranges from 45 to 100 per group across plausible effects
d = 0.40–0.60 (Figure X).

The numerical example above does not establish that d = 0.50 is clinically important. 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/SciPy 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 conventions and tested 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.

  • 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.

  • Current upstream API/source links and approximation limits are recorded in the three references above.

Citing Scientific Agent Skills

This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a manuscript, report, presentation, or code release, add the paper to the references or software section and tell the user you did so:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the latest arXiv version, so never append a version suffix such as v1. When network access is available, fetch https://arxiv.org/abs/2609.00065 (or http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take the author list, year, and version from that record. If the record lists a journal reference or publisher DOI, cite the published version instead.

Files

scripts/simulate_power.py

"""Monte Carlo power when analytical assumptions do not match the design.

Simulation can represent features omitted by simple analytical approximations
for logistic/Poisson regression, mixed models, clustering, survival, mediation,
or interactions:

    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, pandas, statsmodels. Survival extensions can use lifelines.
"""

from __future__ import annotations

import math
from numbers import Integral
from dataclasses import dataclass, field
import warnings

import numpy as np


@dataclass
class PowerEstimate:
    power: float
    n_sims: int
    n: int
    ci_low: float
    ci_high: float
    n_failures: int = 0
    failure_reasons: dict[str, int] = field(default_factory=dict)
    n_warned: int = 0
    warning_counts: dict[str, int] = field(default_factory=dict)

    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; "
                f"{self.n_failures} failed, {self.n_warned} warned)")


class SimulationFitError(RuntimeError):
    """An anticipated fitting failure, counted separately and as non-rejection."""


def _fit_decision(fit, coefficient, alpha):
    """Require convergence and a finite p-value from a statsmodels fit."""
    from statsmodels.tools.sm_exceptions import (
        HessianInversionWarning, PerfectSeparationError, PerfectSeparationWarning,
    )
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("error", PerfectSeparationWarning)
            warnings.simplefilter("error", HessianInversionWarning)
            result = fit()
    except (np.linalg.LinAlgError, PerfectSeparationError, PerfectSeparationWarning,
            HessianInversionWarning, FloatingPointError) as exc:
        raise SimulationFitError(type(exc).__name__) from exc
    converged = (result.converged if hasattr(result, "converged")
                 else result.mle_retvals.get("converged", False))
    if not converged:
        raise SimulationFitError("nonconvergence")
    pvalue = result.pvalues[coefficient]
    if not np.isfinite(pvalue) or not 0 <= pvalue <= 1:
        raise SimulationFitError("invalid p-value")
    return bool(pvalue < alpha)


def _check_example(alpha, **positive):
    if not np.isfinite(alpha) or not 0 < alpha < 1:
        raise ValueError("alpha must lie strictly between 0 and 1")
    for name, value in positive.items():
        if not np.isfinite(value) or value <= 0:
            raise ValueError(f"{name} must be finite and positive")


def _wilson_ci(k, n, z=1.96):
    """Wilson interval for a simulated rate conditional on fixed assumptions."""
    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 consumes fresh pseudorandom draws. Alpha must be used inside
        the callback; the harness alpha argument is validated but not forwarded.
        Raise SimulationFitError for an expected fit failure: it counts as a
        non-rejection in the full denominator and is reported separately.
        Other exceptions propagate so programming errors are not hidden.

    Returns a PowerEstimate including a Wilson confidence interval, so you can
    tell whether 0.81 vs 0.79 is real or just simulation noise.
    """
    if any(isinstance(value, bool) or not isinstance(value, Integral) or value < 1
           for value in (n, n_sims)):
        raise ValueError("n and n_sims must be positive integers")
    if not 0 < alpha < 1:
        raise ValueError("alpha must lie strictly between 0 and 1")
    rng = np.random.default_rng(seed)
    hits = 0
    failures = {}
    warning_counts = {}
    n_warned = 0
    for _ in range(n_sims):
        with warnings.catch_warnings(record=True) as caught:
            warnings.simplefilter("always")
            try:
                rejected = gen_and_test(n, rng)
            except SimulationFitError as exc:
                reason = str(exc) or "unspecified fit failure"
                failures[reason] = failures.get(reason, 0) + 1
                rejected = False
        if caught:
            n_warned += 1
        for warning in caught:
            name = warning.category.__name__
            warning_counts[name] = warning_counts.get(name, 0) + 1
        if not isinstance(rejected, (bool, np.bool_)):
            raise TypeError("gen_and_test must return a boolean rejection decision, not a p-value")
        if rejected:
            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, n_failures=sum(failures.values()),
                         failure_reasons=failures, n_warned=n_warned,
                         warning_counts=warning_counts)


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):
    """Candidate n reaching estimated target power, via noisy bisection over n.

    Requires a design whose power increases with n; discrete designs, rounding,
    and fit failures can violate this. A fixed seed makes the search reproducible
    but not monotone or noise-free. Validate the candidate and neighboring n with
    more replicates and a fresh seed. Returns (n, PowerEstimate); the reported CI
    at an adaptively selected n is not a selection-adjusted assurance interval.
    """
    if any(isinstance(value, bool) or not isinstance(value, Integral)
           for value in (lo, hi)) or not 1 <= lo <= hi <= 1_000_000:
        raise ValueError("bounds must be integers with 1 <= lo <= hi <= 1000000")
    if not 0 < target_power <= 1:
        raise ValueError("target_power must lie in (0, 1]")
    # 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:
            break
        if hi >= 1_000_000:
            raise ValueError("target power not reached by the sample-size cap of 1000000")
        lo, hi = hi, min(hi * 2, 1_000_000)

    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
    _check_example(alpha, sd=sd)
    if not np.isfinite(effect):
        raise ValueError("effect must be finite")

    def gen_and_test(n, rng):  # n per group
        if n < 2:
            raise ValueError("two-group t-test needs at least two observations per group")
        a = rng.normal(0.0, sd, n)
        b = rng.normal(effect, sd, n)
        _, p = stats.ttest_ind(a, b, equal_var=True, alternative="two-sided")
        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 one raw unit of x (SD is x_sd).
    base_rate is P(y=1 | x=0), not the marginal event rate.
    """
    import statsmodels.api as sm
    from scipy.special import expit

    _check_example(alpha, x_sd=x_sd)
    if not np.isfinite(beta) or not np.isfinite(base_rate) or not 0 < base_rate < 1:
        raise ValueError("beta must be finite and base_rate must lie in (0, 1)")

    intercept = math.log(base_rate / (1 - base_rate))

    def gen_and_test(n, rng):
        if n < 3:
            raise ValueError("logistic example requires at least three observations")
        x = rng.normal(0, x_sd, n)
        logit = intercept + beta * x
        p = expit(logit)
        y = rng.binomial(1, p)
        X = sm.add_constant(x)
        return _fit_decision(lambda: sm.Logit(y, X).fit(disp=0), 1, alpha)

    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
    _check_example(alpha, resid_sd=resid_sd)
    if not np.isfinite(effect) or not np.isfinite(icc) or not 0 <= icc < 1:
        raise ValueError("effect must be finite and icc must lie in [0, 1)")
    if isinstance(cluster_size, bool) or not isinstance(cluster_size, Integral) or cluster_size < 2:
        raise ValueError("cluster_size must be an integer >= 2")

    # 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
        if n < 2:
            raise ValueError("cluster example requires at least two 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"])
        return _fit_decision(
            lambda: smf.mixedlm("y ~ arm", df, groups=df["cluster"]).fit(reml=True),
            "arm", alpha)

    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
    _check_example(alpha, resid_sd=resid_sd)
    if not np.isfinite(effect) or not np.isfinite(subj_sd) or subj_sd < 0:
        raise ValueError("effect must be finite and subj_sd finite and nonnegative")
    if isinstance(n_timepoints, bool) or not isinstance(n_timepoints, Integral) or n_timepoints < 2:
        raise ValueError("n_timepoints must be an integer >= 2")

    def gen_and_test(n, rng):  # n subjects
        if n < 2:
            raise ValueError("repeated-measures example requires at least two 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"])
        return _fit_decision(
            lambda: smf.mixedlm("y ~ time", df, groups=df["subj"]).fit(reml=True),
            "time", alpha)

    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"-> candidate n={n} subjects; confirm with fresh simulations ({est})")

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Needs network access, Needs Python

The author says: Requires Python >=3.12 with statsmodels, scipy, numpy, pandas, and matplotlib. Optional comparison uses pingouin; survival extensions use lifelines (requires pandas<3). Installation needs network access unless packages are cached. Calculations run locally without credentials.

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
K-Dense Inc.
Publisher
K-Dense (Community)
Source
K-Dense-AI/scientific-agent-skills · skills/statistical-power · commit a25cf9e
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by K-Dense Inc. or K-Dense.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download statistical-power.zip