Metadata-Version: 2.5
Name: gsdtrial
Version: 0.4.0
Summary: Group-sequential, adaptive and Bayesian design for two-arm clinical trials
Project-URL: Repository, https://github.com/rushadnihal/trialdesign
Project-URL: Changelog, https://github.com/rushadnihal/trialdesign/blob/main/CHANGELOG.md
Author: Rushad Nihal
License: MIT License
        
        Copyright (c) 2026 Rushad Nihal
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: adaptive design,alpha spending,biostatistics,clinical trials,group sequential,sample size
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Requires-Python: >=3.11
Requires-Dist: matplotlib>=3.8
Requires-Dist: numpy>=1.26
Requires-Dist: scipy>=1.11
Requires-Dist: typer>=0.12
Provides-Extra: dev
Requires-Dist: jsonschema>=4.18; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# trialdesign

[![CI](https://github.com/rushadnihal/trialdesign/actions/workflows/ci.yml/badge.svg)](https://github.com/rushadnihal/trialdesign/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/gsdtrial)](https://pypi.org/project/gsdtrial/)

Design a two-arm clinical trial before the data exist. `trialdesign` is a Python command-line
package for:

- fixed-design sample size (continuous, binary and time-to-event endpoints), for superiority,
  non-inferiority or equivalence (two one-sided tests),
- group-sequential boundaries with O'Brien-Fleming-type, Pocock-type, Hwang-Shih-DeCani,
  Kim-DeMets or user-specified spending, and non-binding (default) or binding futility,
- promising-zone sample size re-estimation at an interim, with the Cui-Hung-Wang test, and
  its survival counterpart that re-estimates the number of events,
- survival accrual, follow-up and dropout: patients, study duration and the calendar time of
  each look,
- a Bayesian beta-binomial go/no-go interim with predictive probability of success and assurance,
- graphical multiple testing (Bretz et al. 2009) for several hypotheses sharing one alpha, such
  as two doses with primary and secondary endpoints: rejections, adjusted p-values and power,
- inference at the end of a group-sequential trial: repeated confidence intervals and p-values,
  and the stage-wise p-value, median-unbiased estimate and confidence interval,
- exact and Monte Carlo operating characteristics, including a patient-level survival
  simulator (accrual, dropout, event-driven looks, log-rank test) that can also simulate
  delayed, waning or crossing treatment effects, Weibull event times and the
  Fleming-Harrington weighted log-rank test, and a Markdown design report.

Every number is checked against R (`rpact`, `gsDesign`, `stats`). See [Validated against](#validated-against).

## Install

```bash
pip install gsdtrial
```

The package is published on PyPI as `gsdtrial`, because the name `trialdesign` there belongs to
an unrelated project. You still `import trialdesign` and run `trialdesign`. That other project
also installs a `trialdesign` import, so don't install both in the same environment.

Python 3.11 or later; depends on numpy, scipy, typer and matplotlib. For the latest
development version: `pip install git+https://github.com/rushadnihal/trialdesign`.

## 30-second quickstart

A phase 3 survival trial with hazard ratio 0.70, 80% power, one-sided alpha 0.025, two interim
looks, O'Brien-Fleming-type efficacy and Pocock-type non-binding futility
([`examples/phase3_survival.toml`](https://github.com/rushadnihal/trialdesign/blob/main/examples/phase3_survival.toml)):

```bash
trialdesign design --endpoint survival --hr 0.7 --prob-event 0.75 \
    --looks 0.33,0.67,1 --spending obf --futility pocock
```

```text
trialdesign 0.4.0 | group-sequential design (output abridged) | alpha is one-sided
  fixed events (alpha_two_sided 0.05)  246.7871
  inflation_factor                     1.2437
  max_events                           307
  max_n_total                          410

Boundaries
Look  Info fraction  Cumulative events  Efficacy z  Nominal p (1-sided)  Cumulative alpha  Futility z
1            0.3300                102      3.7307             9.55e-05          9.55e-05      0.4530
2            0.6700                206      2.5039               0.0061            0.0062      1.3293
3            1.0000                307      1.9937               0.0231            0.0250      1.9937
```

Then simulate it and write a report with plots:

```bash
trialdesign simulate --config examples/phase3_survival.toml --nsim 200000 --seed 2026
trialdesign report --config examples/phase3_survival.toml --out results/
```

![Efficacy and futility z-boundaries against information fraction](https://raw.githubusercontent.com/rushadnihal/trialdesign/main/docs/img/boundaries.png)

Operating characteristics of this design. Exact values come from recursive numerical
integration; simulated values use 200,000 trials (seed 2026), each with its Monte Carlo SE and
z = (simulated − exact) / SE:

| Quantity | Exact | Simulated | MC SE | z vs exact |
| --- | --- | --- | --- | --- |
| Type I error (futility ignored) | 0.0250 | 0.0251 | 0.0003 | +0.33 |
| Power (futility followed) | 0.8000 | 0.7994 | 0.0009 | −0.63 |
| Expected events under H0 | 142.6 | 142.6 | 0.14 | +0.24 |
| Expected events under H1 | 227.0 | 226.9 | 0.15 | −0.59 |

Futility is non-binding: boundaries and type I error are computed as if futility were ignored,
so alpha is controlled whether or not the data monitoring committee stops. Following futility
cuts the expected number of events under H0 from 307 to 143.

A Bayesian phase 2 interim works the same way
([`examples/phase2_binary_bayes.toml`](https://github.com/rushadnihal/trialdesign/blob/main/examples/phase2_binary_bayes.toml)):

```bash
trialdesign bayes --pc 0.30 --pt 0.45 --n 60 --interim 30 --go 0.9 --nogo 0.1 --xc 6 --xt 12
```

[`docs/design_memo.md`](https://github.com/rushadnihal/trialdesign/blob/main/docs/design_memo.md)
uses it to design a fictional phase 2 trial, written the way it would be presented to a
clinical team, with an addendum that sizes the follow-on phase 3 with sample size
re-estimation.

For non-inferiority, give the effect under H0: `--delta0` for a difference in means or rates
(treatment minus control), `--hr0` for a hazard ratio. Here both arms respond at 85% and
treatment must not be worse by 10 points
([`examples/phase3_ni_binary.toml`](https://github.com/rushadnihal/trialdesign/blob/main/examples/phase3_ni_binary.toml)):

```bash
trialdesign design --endpoint binary --pc 0.85 --pt 0.85 --delta0 -0.10   # 207 per arm
trialdesign design --endpoint survival --hr 1.0 --hr0 1.3 --looks 3       # 504 events
```

For a survival design, an accrual model turns events into patients and calendar time
(Lachin-Foulkes, exponential events and dropout, as in `rpact`). Give the control median and
two of accrual time, accrual rate and follow-up; the third is solved
([`examples/phase3_survival_accrual.toml`](https://github.com/rushadnihal/trialdesign/blob/main/examples/phase3_survival_accrual.toml)):

```bash
trialdesign design --endpoint survival --hr 0.7 --looks 3 --median-control 12 \
    --accrual-time 24 --followup 12 --dropout 0.05
# 250 events, 391 patients; looks expected at months 16.6, 25.1 and 36.0
```

Piecewise accrual takes one rate per segment, e.g. `--accrual-time 6 --accrual-rate 10,25
--followup 12` for a 6-month ramp-up (the end of accrual is solved).

The non-inferiority test is one-sided in the direction of the alternative. For a binary endpoint the variance
under H0 uses the Farrington-Manning restricted maximum likelihood rates, as `rpact` and
`gsDesign::nBinomial` do.

For equivalence, `--margin` gives the margin on the difference T - C, symmetric (`0.1`) or as
`lower,upper`. Equivalence is concluded when both one-sided tests reject, each at
`alpha_two_sided / 2`, which is the 1 - alpha_two_sided confidence interval lying inside the
margins (Schuirmann 1987). Use `--alpha-two-sided 0.1` for the usual 90% interval:

```bash
trialdesign design --endpoint binary --pc 0.85 --pt 0.85 --margin 0.1 --alpha-two-sided 0.1
# 225 per arm
trialdesign design --endpoint normal --delta 0 --sd 1 --margin 0.5 --alpha-two-sided 0.1
# 69 per arm
```

Power counts both tests on the same estimate. For a normal endpoint (known SD) it is exact, and
with a zero true difference the sample size is the closed form with z_(1-beta/2). For a binary
endpoint each test uses the Farrington-Manning variance at its margin; simulation of the actual
tests shows the formula is conservative by up to half a point of power.

With `--looks` the equivalence design is group-sequential (Jennison and Turnbull 2000,
chapter 6): each one-sided test spends `--alpha-one-sided` (default 0.025) with the
`--efficacy` spending function, and equivalence is declared at the first look where both
reject, that is where the repeated confidence interval lies inside the margins. There is no
futility stop. With one look it is the fixed design above (to 1e-6):

```bash
trialdesign design --endpoint normal --delta 0 --sd 1 --margin 0.5 --looks 3 --power 0.9
# 106 per arm at most (fixed TOST: 104), 93 expected at zero difference
```

```text
Look    Info  n C  n T     c_k  RCI +/-   P(eq)  P(eq) at lo  P(eq) at hi
1     0.3333   36   36  3.7103   0.8864  0.0000       0.0000       0.0000
2     0.6667   71   71  2.5114   0.4242  0.3462       0.0057       0.0057
3     1.0000  106  106  1.9930   0.2749  0.5538       0.0193       0.0193
```

Per look the table gives the sizes, the critical value, the half-width of the repeated
confidence interval at the planned size and the probability of declaring equivalence at the
design difference and at each margin (at most alpha). In Python:
`equivalence.group_sequential_equivalence_normal` (or `_binary`), whose `simulate` checks the
probabilities with patient-level means.

### Inference at the end of the trial

`--analyse` takes the z-statistics observed so far, one per look, with positive favouring
treatment, and reports inference that respects the group-sequential design:

```bash
trialdesign design --endpoint survival --hr 0.7 --looks 3 --analyse 1.2,2.6
```

```text
Look    Info       z  Efficacy z  Estimate (HR)   Repeated 95% CI  Repeated p
1     0.3333  1.2000      3.7103         0.7688  0.3410 to 1.7333      0.3629
2     0.6667  2.6000      2.5114         0.6684  0.4530 to 0.9864      0.0209

Look 2 (efficacy boundary crossed). Stage-wise ordering: p = 0.004702, median-unbiased HR 0.6685, 95% CI 0.4934 to 0.9059.
```

Repeated confidence intervals (Jennison and Turnbull 1989) and repeated p-values are valid at
every look, whether or not the trial stops there. Once a boundary is crossed, or at the last
look, the stage-wise ordering gives the p-value, the median-unbiased estimate and its confidence
interval (Tsiatis, Rosner and Mehta 1984). These account for the looks already taken: the
estimate is median-unbiased over all the ways the trial could have stopped, and the p-value and
interval keep their error rates, which the fixed-sample ones do not. With O'Brien-Fleming-type
boundaries the difference is often small (in the example the naive and stage-wise values are
close), and at the first look the two coincide; it grows with Pocock-type boundaries. Effects are
mapped from the z-scale with the planned information, so for a hazard ratio they use
Schoenfeld's D/4. If the looks fell at other information fractions, rebuild the design with
`--looks` at the observed fractions first. A non-binding futility boundary is ignored, as it is
for the design's type I error. In Python, `trialdesign.inference.analyse` returns the same
quantities, and `trialdesign.equivalence` has the TOST functions.

### Sample size re-estimation

`trialdesign ssr` plans a two-look design and adds a promising-zone rule (Mehta and Pocock
2011): if the conditional power at the observed interim trend lies between `--cp-min` and
`--cp-target`, the second stage grows until it reaches `--cp-target`, up to `--max-factor`
times the planned maximum. The final test weights the stages by their planned information
(Cui, Hung and Wang 1999), so alpha is controlled exactly whatever the interim shows
([`examples/phase3_ssr.toml`](https://github.com/rushadnihal/trialdesign/blob/main/examples/phase3_ssr.toml)):

```bash
trialdesign ssr --config examples/phase3_ssr.toml            # zones and exact OCs
trialdesign ssr --config examples/phase3_ssr.toml --z1 1.5   # apply the rule to an interim
```

```text
Zone                 Interim z1  Observed / design effect  Total patients
Unfavourable            < 1.213                   < 0.611             352
Promising        1.213 to 1.813            0.611 to 0.913      352 to 704
Favourable       1.813 to 2.963                  >= 0.913             352
Efficacy (stop)        >= 2.963                                       176
```

Operating characteristics are exact (one-dimensional integration over the interim z), with a
simulated check. With these defaults (CP 0.36 to 0.8, cap 2x, interim at half), power at
the design effect rises from 0.800 to 0.834 for 37 more patients on average; at 70% of the
design effect, from 0.500 to 0.548. Pooling all patients in a naive final test would also hold
alpha for this promising-zone rule (0.0244), but not for a rule that adapts in every zone
(0.0303 with `--cp-min 0`), which is why the weighted test is always used.

![Re-estimated sample size against the interim z, and power curves](https://raw.githubusercontent.com/rushadnihal/trialdesign/main/docs/img/ssr.png)

#### Blinded re-estimation of the SD

`trialdesign ssr --blinded` (normal endpoint, fixed design) re-estimates the SD from an
internal pilot of `--pilot-n` patients **without unblinding** (Kieser and Friede 2003): the
one-sample variance of the pooled pilot data, optionally minus its bias at the design
difference (`--sd-adjusted`). The sample size is recomputed with the usual formula, kept
between the planned size (`--floor planned`, the default; or `--floor pilot`) and
`--max-factor` times it, and the final one-sided t-test uses all patients. Type I error,
power and the sample size distribution are simulated for true SDs of 0.75 to 1.5 times the
planning SD; `--pilot-sd` applies the rule to an observed pilot
([`examples/phase3_blinded_ssr.toml`](https://github.com/rushadnihal/trialdesign/blob/main/examples/phase3_blinded_ssr.toml)):

```bash
trialdesign ssr --config examples/phase3_blinded_ssr.toml
```

```text
True SD  Type I error   Power  Mean N  N 5%-95%  P(N at cap)
7.5000         0.0247  0.9604   126.0   126-126       0.0000
10.0000        0.0255  0.8259   140.5   126-178     8.00e-05
12.5000        0.0247  0.7947   203.0   148-252       0.1153
15.0000        0.0254  0.7380   245.6   210-252       0.7684

Pilot SD 12: variance used 144.0000; n_control 91, n_treatment 91, total 182
```

Planned for SD 10, the trial keeps about 80% power when the SD is really 12.5 (a fixed
design of 126 would have about 61%), until the cap of twice the planned size binds; the type
I error stays at alpha within simulation error. In Python: `trialdesign.blinded.BlindedSSR`.

### Spending functions and binding futility

`--efficacy` and `--futility` take any of these, in flags and in `[sequential]`:

| Value | Spending | Cumulative error spent by information fraction t |
| --- | --- | --- |
| `obf` | Lan-DeMets O'Brien-Fleming-type | 2 - 2 Phi(z_(1-a/2) / sqrt(t)) |
| `pocock` | Lan-DeMets Pocock-type | a log(1 + (e - 1) t) |
| `hsd:<gamma>` | Hwang-Shih-DeCani, e.g. `hsd:-4` | a (1 - exp(-gamma t)) / (1 - exp(-gamma)) |
| `kd:<rho>` | Kim-DeMets power, e.g. `kd:3` | a t^rho |
| `user:<f1>,...,1` | User-specified, e.g. `user:0.1,0.4,1` | a times the given fraction at each look |

Futility is non-binding unless you ask otherwise. `--binding-futility` (or
`binding_futility = true`) solves the efficacy and futility boundaries together, assuming every
futility stop is made: the efficacy boundaries drop and the trial gets smaller, but alpha holds
only if the committee always stops. The output then shows how far alpha rises if futility is
ignored. For the quickstart trial with `--efficacy hsd:-4 --futility hsd:-2`:

| | Max events | Final z | Type I error, futility followed | Type I error, futility ignored |
| --- | --- | --- | --- | --- |
| Non-binding | 264 | 1.9996 | 0.0233 | 0.0250 |
| Binding | 258 | 1.9648 | 0.0250 | 0.0268 |

Binding futility is not available with sample size re-estimation.

#### Survival: re-estimating the number of events

For a time-to-event endpoint, `trialdesign ssr` re-estimates the number of events instead
([`examples/phase3_survival_ssr.toml`](https://github.com/rushadnihal/trialdesign/blob/main/examples/phase3_survival_ssr.toml)).
The interim is at half the planned events and the cap (`--max-factor`, default 1.5 for
survival) applies to total events. The stage-2 statistic is the log-rank score increment
between the two analyses, which has independent increments (Tsiatis 1981), so the same
weighted test holds alpha. It needs the accrual model, which turns events into calendar time
and patients. `--extend followup` (default) follows the enrolled patients longer;
`--extend accrual` enrols more at the last accrual rate:

```bash
trialdesign ssr --endpoint survival --hr 0.7 --median-control 12 --accrual-time 18 \
  --followup 12 --z1 1.5 --nsim 10000
```

```text
Zone                 Interim z1  Observed / design effect  Total events
Unfavourable            < 1.213                   < 0.611           248
Promising        1.213 to 1.813            0.611 to 0.913    248 to 372
Favourable       1.813 to 2.963                  >= 0.913           248
Efficacy (stop)        >= 2.963                                     124
```

The output adds the expected study duration of each scenario and the month of the final
analysis at the cap. Following 396 patients until 372 events takes until month 69 here, against
37 with `--extend accrual`; check that before choosing the cap. `--nsim` checks the design with
the patient-level simulator, which re-estimates the events at the interim log-rank z. Alpha is
controlled only if the interim decision uses the log-rank statistic alone: using other data from
stage-1 patients (progression, biomarkers) breaks the independent increments (Bauer and Posch
2004; Jenkins, Stone and Jennison 2011).

The defaults come from a grid over the cap (1.25, 1.5, 2) and `--cp-min` (0.2, 0.36, 0.5) for
the same trial with 600 patients. At a hazard ratio of 0.75 against a design value of 0.7, the plain design has
power 0.618; cap 1.5 with CP 0.36 to 0.8 gives 0.656 for 21 more events and 1.4 more months on
average; a cap of 2 with `--cp-min 0.2` gives 0.699 for 51 more events and 4.6 more months. The
power per extra event is about the same across the grid, so the cap mostly trades duration
for power. The exact characteristics use the Schoenfeld information D r / (1 + r)^2; with
unequal allocation the log-rank test's power departs from it by about a point, and the
patient-level check is the better guide.

## Command line

| Command | Does |
| --- | --- |
| `trialdesign design` | Fixed or group-sequential sample size and boundaries, with exact operating characteristics; `--margin` for equivalence (group-sequential with `--looks`), `--analyse` for inference from observed z |
| `trialdesign simulate` | Monte Carlo operating characteristics under H0 and H1, next to the exact values; `--engine patient` simulates patients and the real test, and for survival `--delay`, `--waning`, `--hazard-times` or `--kappa` simulate another event-time model and `--test fh:0,1` the weighted log-rank test |
| `trialdesign bayes` | Bayesian go/no-go interim: exact OCs, posterior, PPoS and decision for observed data, assurance |
| `trialdesign ssr` | Promising-zone sample size (survival: event) re-estimation: zones, exact OCs, the rule applied to an interim z; `--blinded` re-estimates the SD from an internal pilot |
| `trialdesign graph` | Graphical multiple test: rejections, adjusted p-values and the path for observed p-values (`--p`), and power for given z-means and correlation (`--means`) |
| `trialdesign report` | `report.md` plus PNG plots of the boundaries and operating characteristics; `--engine patient` adds a patient-level check, `--analyse` an inference section, `--delay` (or another event model) a non-proportional hazards section, and a `[graph]` table a multiple-testing section |

Each command takes flags, a TOML design file (`--config`), or both; flags override the file.
Output is a plain table, or JSON with `--json`. Only `report --out` writes to disk, and every
simulation prints its seed and the package version. Alpha always names its sidedness: fixed
designs report two-sided alpha (default 0.05), group-sequential designs one-sided (default
0.025). Run `trialdesign COMMAND --help` for every option.

### JSON output

`--json` output is a stable contract for scripts and pipelines:

- every object carries `"schema_version": 1`, `"command"` and the package `"version"`;
- within a schema version keys are only **added**; removing or renaming a key, or changing
  its type, bumps `schema_version`;
- non-finite numbers (an infinite boundary, the hazard ratio of a non-proportional event
  model) are `null`, so any strict JSON parser reads the output;
- on an error, `--json` prints `{"error": "<message>", "code": 2}` to stderr and exits
  with status 2 (without `--json` the message is plain text).

JSON Schemas (draft 2020-12) for each command are in
[`docs/schema/`](https://github.com/rushadnihal/trialdesign/tree/main/docs/schema), one
sub-schema per kind of output (fixed or group-sequential design, blinded or promising-zone
re-estimation, and so on). They are generated from the cases in `tests/make_schemas.py`, and
the tests fail if a key recorded for the current version disappears.

```bash
trialdesign design --config examples/phase3_survival.toml --json | jq '.sample_size.max_events_ceil'
```

`simulate` has two engines. The default, `score`, draws the canonical z-scale process: fast,
and exactly what the boundaries assume. `--engine patient` (or `engine = "patient"` under
`[simulation]`) simulates patients and the test you would run on them: the t-test for a
normal endpoint, the Farrington-Manning z-test for a binary one (including non-inferiority),
and the log-rank test with accrual and dropout for survival. It defaults to 10,000 trials and
shows how far the large-sample theory holds for your design:

```bash
trialdesign simulate --endpoint survival --hr 0.7 --median-control 12 --accrual-time 24 \
  --followup 12 --looks 3 --engine patient --seed 1
```

For the phase 3 binary design of the
[design memo](https://github.com/rushadnihal/trialdesign/blob/main/docs/design_memo.md), 100,000
patient-level trials give a one-sided type I error of 0.0266 (MC SE 0.0005) rather than 0.025:
the z-test is slightly liberal at 172 patients. `report --nsim N --engine patient` keeps the
score-engine simulation of N trials and adds 10,000 patient-level trials beside it, with the
exact values, in a "Patient-level check" table.

### Non-proportional hazards

A survival design is sized under proportional hazards, but an immunotherapy often has no
effect for the first months. The patient engine simulates the design under another event-time
model while keeping its sample size and boundaries: a delayed effect (`--delay`, HR 1 for that
many months, then `--hr-after`, default `--hr`), a waning effect (`--waning`), any
piecewise-constant hazards per arm (`--hazard-times`, `--hazards-control`,
`--hazards-treatment`), or Weibull event times with proportional hazards (`--kappa`). H0 gives
both arms the control distribution, so the type I error is checked under the same model.

```bash
trialdesign simulate --config examples/phase3_survival_nph.toml
```

[`examples/phase3_survival_nph.toml`](https://github.com/rushadnihal/trialdesign/blob/main/examples/phase3_survival_nph.toml)
sizes a trial for HR 0.70 (248 events, 371 patients, one interim at half the events) and
simulates a 4-month delay. With 100,000 trials per scenario:

| Scenario | Test | Power | Type I error |
| --- | --- | --- | --- |
| Proportional hazards (`--delay 0`), interim at 50% | log-rank | 0.799 | 0.0258 |
| 4-month delay, interim at 50% | log-rank | 0.487 | 0.0256 |
| 4-month delay, one final analysis (`--looks 1`) | log-rank | 0.486 | 0.0249 |
| 4-month delay, one final analysis | FH(0,1) (`--test fh:0,1`) | 0.585 | 0.0254 |
| Proportional hazards, one final analysis | FH(0,1) | 0.671 | 0.0255 |

The delay costs about 30 points of power. FH(0,1), which weights late differences, wins back
10 of them, but under proportional hazards it would cost 13 (MC SE about 0.0016 for power and
0.0005 for type I error). The weighted test is supported for a single final analysis only: its
group-sequential correlation is not that of the log-rank test, so the usual boundaries would
not hold alpha. A `[hazards]` table in a design file takes the same settings
(`delay`, `waning`, `hr_after`, `hazard_times`, `hazards_control`, `hazards_treatment`,
`kappa`), and `test` goes under `[simulation]`.

`trialdesign report` takes the same flags (or `[hazards]` table) and adds a section that puts
the design under proportional hazards next to the scenario: power, the month and stopping
probabilities of each look, expected duration, patients and events (10,000 patient-level
trials each, same seed), with the survival curves per arm in `survival.png`:

```bash
trialdesign report --config examples/phase3_survival_accrual.toml --delay 4 --nsim 100000 --out results/
```

For that design (three looks, Pocock futility) the delay cuts power from 0.79 to 0.36, mostly
because the first futility look stops 40% of trials instead of 9%; see the
[design memo](https://github.com/rushadnihal/trialdesign/blob/main/docs/design_memo.md) addendum.

### Graphical multiple testing

A confirmatory trial with two doses, each with a primary and a key secondary endpoint, tests
four hypotheses and must hold the family-wise error rate at one-sided 0.025. A graph says how:
each hypothesis starts with a weight (its share of alpha), and when one is rejected its level
passes along the edges (Bretz et al. 2009). `trialdesign graph` tests observed p-values through
the graph and simulates its power:

```bash
trialdesign graph --config examples/two_doses_graph.toml
```

```text
Test
Hypothesis         p-value     Adjusted p  Rejected
H1 primary high    0.004       0.008       yes
H2 primary low     0.015       0.02        yes
H3 secondary high  0.011       0.022       yes
H4 secondary low   0.2         0.2         no

Path
1. reject H1 primary high (p 0.004 <= 0.0125); weights now H2 primary low 0.75, H3 secondary high 0.25
2. reject H2 primary low (p 0.015 <= 0.01875); weights now H3 secondary high 0.5, H4 secondary low 0.5
3. reject H3 secondary high (p 0.011 <= 0.0125); weights now H4 secondary low 1
```

Power comes from simulating the one-sided z-statistics as multivariate normal with the given
means (2.8 is 80% power for one test on its own at 0.025) and correlation (0.5 between two
doses that share a control arm). For the example, 200,000 trials give power 0.742, 0.654, 0.435
and 0.366 for H1 to H4, 0.814 to reject at least one and 0.293 to reject all four. Presets cover
the usual procedures: `--preset holm:3`, `bonferroni:3`, `fixed-sequence:3`,
`fallback:0.5,0.3,0.2` and `two-doses`. The graph is a Bonferroni-based shortcut of a closed
test, so it controls the family-wise error rate for any correlation; it is for fixed designs
(one analysis). A `[graph]` table in a file given to `trialdesign report` adds a multiple-testing
section, with the graph drawn (weights, transitions and the power of each hypothesis) in
`graph.png`.

## Python API

```python
from trialdesign import bayes, boundaries, fixed, simulate

d = boundaries.group_sequential_design(
    [1 / 3, 2 / 3, 1.0],
    alpha_one_sided=0.025,
    power=0.80,
    efficacy_spending="obf",
    futility_spending="obf",  # or "hsd:-2", "kd:2", "user:0.25,0.5,1"
    binding_futility=False,  # the default
)
d.efficacy, d.futility, d.inflation_factor
d.max_sample_size(fixed.events_survival(0.70).events)  # max events = fixed events x IF

sim = simulate.simulate_design(d, n_sim=200_000, seed=2026)
sim.type_i_error, sim.h0_ignore_futility.reject_prob_se  # futility ignored
sim.power, sim.h1.reject_prob_se

from trialdesign import accrual, patients

study = accrual.survival_study(250, 0.70, 12, accrual_time=24, followup=12)
ps = patients.simulate_survival(study, d.info_rates, d.efficacy, d.futility, n_sim=10_000, seed=1)
ps.reject_prob, ps.analysis_time, ps.expected_duration, ps.expected_patients
pd = patients.simulate_design_patients(  # H0 and H1, like simulate.simulate_design
    d, "binary", n_control=180, p_control=0.30, p_treatment=0.45, n_sim=10_000, seed=1
)
pd.type_i_error, pd.power

from trialdesign.hazards import EventModel

delayed = EventModel.delayed_effect(study.hazard_control, 0.70, delay=4)
study.look_times(d.info_rates, delayed)  # expected calendar time of each look under the model
nph = patients.simulate_survival(study, d.info_rates, d.efficacy, model=delayed, seed=1)
h0 = patients.simulate_survival(study, d.info_rates, d.efficacy, model=delayed.null(), seed=1)
fh = patients.simulate_survival(study, [1.0], [1.96], model=delayed, fh=(0, 1), seed=1)

from trialdesign import multiplicity

g = multiplicity.Graph.two_doses()  # or Graph(weights, transitions, names), Graph.holm(3), ...
t = multiplicity.graph_test([0.004, 0.015, 0.011, 0.2], g, alpha_one_sided=0.025)
t.rejected, t.adjusted_p, t.steps
pw = multiplicity.graph_power(g, means=[2.8, 2.5, 2.2, 2.0], correlation=0.5, seed=1)
pw.local_power, pw.any_power, pw.all_power

b = bayes.bayesian_interim_design(n_interim=30, n_final=60)  # control patients per analysis
b.ppos(6, 12), b.decide(6, 12)  # PPoS and go / no-go / continue at the interim
b.operating_characteristics(0.30, 0.30).prob_success  # exact type I error
b.assurance(0.30, (4.5, 5.5)).prob_success  # Beta(4.5, 5.5) design prior on p_T
bayes.calibrate_success_threshold(30, 60, alpha_one_sided=0.025)  # 0.9789
```

**Methods in one paragraph.** Every group-sequential design is reduced to a drift on the
canonical z-scale. Efficacy boundaries spend alpha with any of the spending functions above and
are solved by Jennison and Turnbull's recursive numerical integration, cross-checked against
`scipy`'s multivariate normal to 1e-4. Futility spends beta under the alternative; when it is
binding, efficacy and futility boundaries are solved look by look over the same continuation
region. The simulator draws independent increments of the score process, one
`(n_sim, looks)` matrix per batch, so 100,000 trials take well under a second. The
patient-level survival simulator checks that approximation with real patients: piecewise
accrual, permuted-block randomisation, exponential events and dropout, looks at the calendar
time of the planned event counts, and the log-rank test, vectorised over trials (10,000 trials
of 600 patients take a few seconds). The Bayesian
interim computes PPoS exactly by enumerating the beta-binomial posterior predictive, so
decisions carry no Monte Carlo error and operating characteristics and assurance are exact.
The default final success threshold, 0.98, is calibrated so the reference design (30 of 60
patients per arm at the interim) has a worst-case type I error of 0.0232, below one-sided
0.025, over common response rates from 0.05 to 0.95. `bayes --calibrate` re-calibrates it for
other designs.

## Validated against

Reference values were produced once in R and saved to JSON, so CI stays Python-only.

| What | Reference | Cases | Tolerance |
| --- | --- | --- | --- |
| Fixed sample size, normal | `stats::power.t.test` | 3 | 1e-4 |
| Fixed sample size, binary | `stats::power.prop.test`, `gsDesign::nBinomial` | 4 | 1e-4 |
| Events, time to event | `gsDesign::nEvents` (Schoenfeld) | 2 | 1e-4 |
| Spending functions | `gsDesign::sfLDOF`, `sfLDPocock` | 2 | 1e-9 |
| Efficacy boundaries and inflation factor | `rpact::getDesignGroupSequential` | 8 | 1e-3 |
| Non-binding futility boundaries | `gsDesign::gsDesign(test.type = 4)` | 4 | 1e-3 |
| Maximum events | `gsDesign::gsDesign(n.fix)` | 2 | 0.05 events |
| Expected sample size | `gsDesign` | 12 | 1e-3 |
| Posterior P(p_T > p_C), PPoS, exact OCs, assurance | independent base-R script | 20 | 1e-9 |
| Non-inferiority sample size and events | `rpact::getSampleSizeMeans`, `getSampleSizeRates`, `getSampleSizeSurvival` (`thetaH0`) | 9 | 1e-4 |
| Non-inferiority group-sequential maximum | `rpact` with a group-sequential design | 3 | 0.05 |
| Survival accrual: patients, accrual end, follow-up, study duration | `rpact::getSampleSizeSurvival` | 6 | 0.01 patients, 0.001 months |
| Conditional power at an interim (inverse normal) | `rpact::getConditionalPower` | 5 | 1e-6 |
| Re-estimation OCs: power, early stopping, expected patients | `rpact::getSimulationMeans` (100,000 runs) | 4 | 3 MC SE |
| Hwang-Shih-DeCani, Kim-DeMets and user-specified spending: boundaries, inflation factor, expected sample size | `rpact::getDesignGroupSequential` (`asHSD`, `asKD`, `asUser` and beta-spending versions) | 9 | 1e-5 |
| Binding futility boundaries, inflation factor, expected sample size | `rpact::getDesignGroupSequential(bindingFutility = TRUE)` | 5 | 1e-5 |
| Calendar time and patients at each look | `rpact::getSampleSizeSurvival` with a group-sequential design | 2 | 0.001 months, 0.05 patients |
| Patient-level survival simulation: power, type I error, look times, duration, expected patients and events | `rpact::getSimulationSurvival` (100,000 runs) | 6 | 2 MC SE (power), 3 MC SE (per look, calendar) |
| Log-rank statistic | `scipy.stats.logrank` | 5 | 1e-10 |
| Patient-level normal (t-test) and binary (Farrington-Manning) simulation, superiority and non-inferiority: power, type I error, per-look stopping, expected sample size | `rpact::getSimulationMeans`, `getSimulationRates` (100,000 runs) | 8 | 3 MC SE |
| Survival event re-estimation: conditional power given the interim log-rank z | `rpact::getConditionalPower` | 4 | 1e-6 |
| End-of-trial inference: repeated CIs and p-values, stage-wise p-value, median-unbiased estimate and CI (OBF, Pocock, HSD, Kim-DeMets; non-binding and binding futility) | `rpact::getRepeatedConfidenceIntervals`, `getRepeatedPValues`, `getFinalPValue`, `getFinalConfidenceInterval` | 6 | 1e-3 (agree to about 1e-6) |
| Equivalence (TOST) sample size and power | closed form at zero difference; simulation of the actual tests | 9 | 1e-4; 3 MC SE (normal), conservative within 1 point (binary) |
| Survival event re-estimation, patient level: power, type I error, interim stops, expected events, duration and patients | `rpact::getSimulationSurvival` with `conditionalPower` (100,000 runs) | 4 | 3 MC SE |
| Expected events under piecewise-exponential (delayed, waning, crossing; with dropout and piecewise accrual) and Weibull event times | `rpact::getEventProbabilities` | 6 | 1e-6 (share of patients) |
| Patient-level simulation under non-proportional hazards and Weibull events: power, type I error, per-look stopping, look times, duration, expected patients and events | `rpact::getSimulationSurvival` with `piecewiseSurvivalTime` or `kappa` (100,000 runs) | 4 | 2 MC SE (power), 3 MC SE (per look, calendar) |
| Graphical multiple testing: rejections and adjusted p-values (Bonferroni, Holm, fixed-sequence, fallback, two-dose and general graphs) | Closed test of weighted Bonferroni tests implemented in R; Holm also `stats::p.adjust` | 35 | exact / 1e-12 |
| Power of a graph: per hypothesis, at least one, all, expected rejections (including the global-null FWER) | Exact integration with `mvtnorm::pmvnorm` | 5 | 2 MC SE (at least one), 3 MC SE (per hypothesis, all) |
| Blinded SD re-estimation: re-estimated sizes; type I error, power and mean sample size (one-sample and bias-adjusted variance, floor at planned or pilot, 2:1) | Patient-level simulation in R (200,000 runs), t statistic checked against `stats::t.test` | 24 + 11 | exact; 3 SE of the difference |
| Group-sequential equivalence: critical values, sample size, per-look probability of declaring equivalence at the design difference and at both margins (normal and binary, OBF and Pocock) | `rpact::getDesignGroupSequential` and `mvtnorm::pmvnorm` rectangles; Farrington-Manning by numerical maximisation | 7 | 1e-6 (probabilities), 1e-5 (sample size) |
| Fleming-Harrington FH(rho, gamma) weighted log-rank statistic | Computed in R; FH(rho, 0) also `survival::survdiff(rho = ...)` | 15 | 1e-10 |

Values: [`tests/reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/reference_values.json) (R 4.5.3, gsDesign 3.11.0,
rpact 5.0.0), [`tests/bayes_reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/bayes_reference_values.json) and
[`tests/ni_reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/ni_reference_values.json) and
[`tests/accrual_reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/accrual_reference_values.json) and
[`tests/ssr_reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/ssr_reference_values.json) and
[`tests/spending_reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/spending_reference_values.json) and
[`tests/patients_reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/patients_reference_values.json) and
[`tests/patients_endpoints_reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/patients_endpoints_reference_values.json) and
[`tests/ssr_survival_reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/ssr_survival_reference_values.json) and
[`tests/inference_reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/inference_reference_values.json) and
[`tests/nph_reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/nph_reference_values.json) (rpact 3.4.0) and
[`tests/multiplicity_reference_values.json`](https://github.com/rushadnihal/trialdesign/blob/main/tests/multiplicity_reference_values.json) (mvtnorm 1.2.4).
Scripts: [`tests/r/`](https://github.com/rushadnihal/trialdesign/tree/main/tests/r/). On top of these, property tests check that one look gives
z = 1.96, that the per-look rejection probabilities under H0 sum to alpha, that PPoS is 0 or 1
with no patients left and increases with treatment responders, and that every simulated rate
lies within a few Monte Carlo SEs of its exact value.

To regenerate (needs `gsDesign` and `rpact`; the Bayesian script needs base R only):

```bash
Rscript tests/r/reference_values.R > ref.json && mv ref.json tests/reference_values.json
Rscript tests/r/bayes_reference_values.R > bayes.json && mv bayes.json tests/bayes_reference_values.json
Rscript tests/r/ni_reference_values.R > ni.json && mv ni.json tests/ni_reference_values.json
Rscript tests/r/accrual_reference_values.R > acc.json && mv acc.json tests/accrual_reference_values.json
Rscript tests/r/ssr_reference_values.R > ssr.json && mv ssr.json tests/ssr_reference_values.json
Rscript tests/r/spending_reference_values.R > sp.json && mv sp.json tests/spending_reference_values.json
Rscript tests/r/patients_reference_values.R > pat.json && mv pat.json tests/patients_reference_values.json
Rscript tests/r/patients_endpoints_reference_values.R > pe.json && mv pe.json tests/patients_endpoints_reference_values.json
Rscript tests/r/ssr_survival_reference_values.R > ssr.json && mv ssr.json tests/ssr_survival_reference_values.json
Rscript tests/r/inference_reference_values.R > inf.json && mv inf.json tests/inference_reference_values.json
Rscript tests/r/nph_reference_values.R > nph.json && mv nph.json tests/nph_reference_values.json
Rscript tests/r/multiplicity_reference_values.R > mult.json && mv mult.json tests/multiplicity_reference_values.json
Rscript tests/r/blinded_reference_values.R > blinded.json && mv blinded.json tests/blinded_reference_values.json
Rscript tests/r/gs_equivalence_reference_values.R > gseq.json && mv gseq.json tests/gs_equivalence_reference_values.json
```

## Development

```bash
pip install -e ".[dev]"
pytest
pytest -m slow   # on demand: 100,000-trial type I error check of the patient-level simulator
ruff check . && ruff format --check .
python tests/make_schemas.py   # after a deliberate change of the --json output
```

Changes are listed in [CHANGELOG.md](https://github.com/rushadnihal/trialdesign/blob/main/CHANGELOG.md).
Releases are built and published by [`.github/workflows/release.yml`](https://github.com/rushadnihal/trialdesign/blob/main/.github/workflows/release.yml)
when a `v*` tag is pushed; see [RELEASING.md](https://github.com/rushadnihal/trialdesign/blob/main/RELEASING.md).

## Future work

The package is deliberately narrow: two arms and one primary endpoint. Not yet covered:

- multi-arm, platform and basket trials;
- enrichment designs, and blinded re-estimation for binary and survival endpoints;
- group-sequential graphical testing (Maurer and Bretz 2013), and Simes or parametric tests
  inside a graph;
- response-adaptive randomisation;
- Stan or PyMC models and dynamic borrowing;
- designing for non-proportional hazards analytically (average hazard ratio, RMST or max-combo
  sample size), and group-sequential weighted log-rank tests.

## License

MIT
