StatClaim tutorial

From a study description to a checked claim

Fourteen short lessons. Each one adds a few ideas to the previous one, so work through them in order. By the end you can plan a study, analyse its data and know exactly which guarantees were checked.

Before you start

You need basic statistics: hypothesis tests, p-values, power. You do not need to know Lean or any programming language.

Open the repository in GitHub Codespaces, or install it locally with make setup (see the quickstart). Every lesson has a file in examples/tutorial/. Commands are shown as statclaim ...; from the repository folder, type uv run --locked statclaim ....

In VS Code the same two actions are StatClaim: Show Claims and StatClaim: Verify Current File, and mistakes are underlined as you type.

  1. 1Your first checked claim
  2. 2Reading a result
  3. 3When StatClaim says no
  4. 4Analysing the data
  5. 5Several endpoints
  6. 6Why it passed, and what a change affects
  7. 7Choosing a sample size
  8. 8Better, or at least not worse
  9. 9A single-arm study
  10. 10Stopping early
  11. 11A Bayesian stopping rule
  12. 12A continuous outcome, and a cited guarantee
  13. 13Proved and cited tests under one error bound
  14. 14An interim look

Lesson 1

Your first checked claim

In this lesson

We describe a simple two-group study, choose a test, and ask StatClaim to check one guarantee: that the test's false-positive rate is at most 5%.

A .stat file is a list of declarations. It contains no data and runs no analysis by itself. It states what the study is and which guarantee you want.

examples/tutorial/01_first_claim.stat
# Lesson 1: declare a study and ask for one guarantee.
use models.two_arm_binomial
use sampling
use tests.fisher

let study = two_arm_binomial(n_control=50, n_treatment=50)
let design = fixed(model=study)
let null = equal_proportions(model=study)
let analysis = fisher(design=design, null=null, alpha=1/20)

let claim = typeI(analysis)
let verification = verify(claim)

Reading the file

use ...
Loads a module of vocabulary. models.two_arm_binomial gives us the study model, sampling the design, and tests.fisher the test.
let name = ...
Names an object. Names cannot be reassigned. Arguments are always written name=value.
study
Two groups of 50 participants, each with a yes/no outcome.
design
fixed means the sample sizes are set before any data are seen.
null
The hypothesis being tested: both groups have the same success rate. Declaring a null does not say it is true.
analysis
Fisher's exact test at level 1/20. Numbers are exact, so write 1/20 or 0.05; both mean the same fraction.
claim
typeI(analysis) is the statement "if the null is true, this test rejects it with probability at most 1/20".
verification
verify asks the Lean proof checker to establish the claim.

Run it

There are two commands. compile checks the file and lists what would be verified. It is instant and proves nothing. check runs the verification.

statclaim compile examples/tutorial/01_first_claim.stat
statclaim check   examples/tutorial/01_first_claim.stat
verified [verification]: typeI(analysis)
  The specified two-sided Fisher analysis has Type I error at most 1/20
  under the null, for every common success probability in [0, 1].
  Assumptions:
    The samples follow two independent binomial distributions.
    Positive arm sizes were fixed before outcomes were observed.
    The error bound is under the null of equal success probabilities.
  Certificate: .statclaim/programs/.../request-001
Program status: verified

verified means Lean checked a proof of the claim. The assumptions listed under it are part of the result: the claim holds if they do. StatClaim cannot check that your real study was randomised properly or that participants are independent.

What you learned

  • A file declares a study, a null, an analysis and a claim.
  • compile inspects; check verifies.
  • A verified claim always comes with its assumptions.

Try it

Change alpha to 1/100 and run check again. The bound in the output follows your declaration.

Lesson 2

Reading a result

In this lesson

A verification is an object like any other. We pull out its status, its evidence and its assumptions by name, and we start writing shorter files.

examples/tutorial/02_reading_results.stat
# Lesson 2: name the parts of a result.
use models.two_arm_binomial
use sampling
use tests.fisher

let study = two_arm_binomial(n_control=50, n_treatment=50)
let analysis = fisher(design=fixed(model=study), null=equal_proportions(model=study), alpha=1/20)
let verification = verify(typeI(analysis))

let status = verification.status
let evidence = verification.evidence
let assumptions = verification.evidence.required_assumptions
let level = analysis.alpha

Two things changed. First, constructors are nested: fixed(model=study) is written inside fisher(...) instead of being named. Use whichever reads better. Second, the last four lines read fields with a dot.

FieldValue after check
verification.statusverified
verification.evidenceThe checked claim and its certificate
verification.evidence.required_assumptionsThe three assumptions from lesson 1
analysis.alpha1/20

To see the values, ask for the full report:

statclaim check examples/tutorial/02_reading_results.stat --json

Evidence can be absent

evidence exists only after a successful verification. If verification fails or was never run, evidence is empty, and so is every field read from it. A file that merely compiles never has evidence.

Certificates. Each verified claim leaves a folder with the exact inputs, the Lean proof and a log. Anyone can replay it with statclaim check-certificate <folder>.

What you learned

  • Objects have named fields, read with a dot.
  • status says what happened; evidence exists only on success.
  • Certificates can be replayed.

Try it

Run compile --json on the same file. The fields are listed as not_executed: nothing has been proved yet.

Lesson 3

When StatClaim says no

In this lesson

We make two common mistakes on purpose and read the explanations. Knowing the two kinds of refusal is most of what you need to work with the tool.

Mistake 1: a question the test does not answer

Suppose the real question is whether the treatment improves the success rate by more than ten percentage points. We declare that null and keep the Fisher test.

examples/tutorial/03_wrong_null.stat
# Lesson 3a: a null the Fisher analysis does not support.
use models.two_arm_binomial
use sampling
use tests.fisher

let study = two_arm_binomial(n_control=50, n_treatment=50)
let design = fixed(model=study)
let null = proportion_difference(model=study, value=1/10)
let analysis = fisher(design=design, null=null, alpha=1/20)
03_wrong_null.stat:9:43: error [hypothesis_mismatch]: fisher: hypothesis contract mismatch.
Declared null: p_treatment - p_control = 1/10.
Supported null: p_treatment = p_control (equal arm success probabilities).
... replacing the null changes the statistical question.
Program status: invalid

invalid means the file itself is wrong and nothing can be verified. Fisher's test, as supported here, answers one question: are the two rates equal? The message does not tell you to switch to that null. Doing so would make the error go away by changing your question. Lesson 8 introduces a test that does support a margin.

Mistake 2: stopping when the result looks good

Now the null is fine, but the design is adaptive: the sample size depends on the data, for example by checking results as they come in.

examples/tutorial/03_optional_stopping.stat
# Lesson 3b: a design whose stopping depends on the data.
use models.two_arm_binomial
use sampling
use tests.fisher

let study = two_arm_binomial(n_control=50, n_treatment=50)
let design = adaptive(model=study)
let null = equal_proportions(model=study)
let analysis = fisher(design=design, null=null, alpha=1/20)
let verification = verify(typeI(analysis))
03_optional_stopping.stat:7:1: obligation [sampling_scope]: analysis: data-dependent
stopping needs a justified sampling law before the fixed-sample guarantee can be used.
This is not evidence of inflated error.
unresolved_obligation [verification]: typeI(analysis)
Program status: unresolved_obligation

unresolved is different from invalid. The file is well formed, but the 5% guarantee was proved for a fixed sample size and nothing here shows it survives early stopping. StatClaim does not claim the error rate is inflated. It says the justification is missing. Lesson 10 shows how to plan an early stop properly.

StatusMeaning
verifiedLean checked the claim under the listed assumptions.
calculatedA number was computed. No proof (lesson 4).
unresolvedSomething needed for the claim is missing. Not a disproof.
invalidThe declarations do not fit together.

What you learned

  • Each analysis supports specific nulls and designs, and says which.
  • Invalid is a mistake in the file; unresolved is a missing justification.
  • Neither says anything about whether your hypothesis is true.

Try it

In the second file, change adaptive back to fixed and confirm the claim verifies.

Lesson 4

Analysing the data

In this lesson

The study has finished. We enter the counts, compute the exact p-value, and have Lean confirm the number and the decision.

examples/tutorial/04_observed_data.stat
# Lesson 4: analyse the data.
use models.two_arm_binomial
use sampling
use tests.fisher

let study = two_arm_binomial(n_control=50, n_treatment=50)
let analysis = fisher(design=fixed(model=study), null=equal_proportions(model=study), alpha=1/20)

# 12 of 50 controls and 24 of 50 treated participants responded.
let data = observe(analysis=analysis, control_successes=12, treatment_successes=24)
let calculation = calculate(result(data))
let p_value = calculation.calculation.p_value
let decision = calculation.decision
let verification = verify(result(data))
observe
Attaches counts to an analysis. Counts outside the declared sample sizes are rejected when the file is compiled.
result(data)
The claim "this is the exact p-value and decision for these counts".
calculate
Computes the answer in exact arithmetic. Fast, and not a proof.
verify
Has Lean recompute the p-value from its own definition and compare.
calculated [calculation]: result(data)
  p-value = 1255807221238/58971773773923; decision = reject_null; no formal certificate issued.
verified [verification]: result(data)
  Exact p-value equals the Lean Fisher definition for these counts.
  Reported decision equals membership in the formal rejection event.
  The specified fixed-sample rule has Type I error at most 1/20 under the null model.
  Assumptions:
    ...
    The supplied counts describe the declared sampling procedure.

The p-value is an exact fraction, about 0.021. Results keep fractions; decimals are for display. Note the new assumption: Lean can check the arithmetic, but only you know whether these are the counts your study produced.

Calculate or verify? Use calculate while exploring. Use verify for anything you will report. The same split applies to every claim in the rest of this tutorial.

What you learned

  • observe attaches data; result is a claim about it.
  • calculate gives numbers, verify gives checked numbers.
  • Verifying a result adds the assumption that the counts are the real ones.

Try it

Change the treatment count to 18. The decision becomes do_not_reject_null, and it still verifies: a checked result is not the same as a significant one.

Lesson 5

Several endpoints

In this lesson

The study measures three outcomes. We split the 5% error budget between them so that the chance of any false positive stays at most 5%.

Testing each of three outcomes at 5% does not give a 5% study-wide error rate. The Bonferroni method gives each test a share of the budget.

examples/tutorial/05_several_endpoints.stat
# Lesson 5: three endpoints, one overall error rate.
use models.two_arm_binomial
use sampling
use tests.fisher
use multiplicity.bonferroni

let study = two_arm_binomial(n_control=50, n_treatment=50)
let design = fixed(model=study)
let null = equal_proportions(model=study)

let response = fisher(design=design, null=null, alpha=1/40)
let remission = fisher(design=design, null=null, alpha=1/80)
let relapse = fisher(design=design, null=null, alpha=1/80)

let endpoints = bonferroni(
    analyses=[response, remission, relapse],
    alpha=1/20,
    joint_law="binomial_marginals",
)
let verification = verify(familywise(endpoints))
Three analyses
Each endpoint is a Fisher analysis with its own level. The primary endpoint gets half the budget; the shares add up to exactly 1/20.
bonferroni
Groups the analyses into a family with an overall level. The list is written in square brackets.
joint_law
States what is assumed about how the outcomes relate. "binomial_marginals" assumes only that each outcome follows its own two-group model. The outcomes may be correlated in any way.
familywise
The claim: the probability of rejecting any true null is at most the overall level.
verified [verification]: familywise(endpoints)
  Strong familywise error is at most 1/20 under the declared marginal-law contracts,
  for every configuration of true and false endpoint nulls.
  The sum of the allocated endpoint levels does not exceed the familywise bound.

What you learned

  • A family groups analyses under one overall error level.
  • The shares must add up to no more than that level.
  • The guarantee holds however the endpoints are correlated.

Try it

Set all three levels to 1/20. You get an allocation obligation: the shares now add up to 3/20.

Lesson 6

Why it passed, and what a change affects

In this lesson

So far a valid file has been silent: no message means the pieces fit. We now ask StatClaim to show its reasoning, produce a report for the study file, and tell us what an edit affects.

When you write fisher(design=..., null=..., alpha=...), StatClaim checks that the pieces fit together. Lesson 3 showed what happens when they do not. When they do, the reasoning is kept and shown only if you ask. No new file is needed; we use the one from lesson 5.

statclaim explain examples/tutorial/05_several_endpoints.stat --name response
Conclusion: response: the design, the null and the level fit this analysis.

Why it passed
1. same-model: the null and the design describe the same study model.
2. supported-null: the declared null (p_treatment = p_control) is supported by this analysis.
3. level-range: the level 1/40 is a probability.
4. analysis-contract (from steps 1, 2, 3): the design, the null and the level fit this analysis.
5. fixed-sampling: sampling is fixed, as the fixed-sample error theorem requires.

Assumptions you must meet in the real study
- The two samples are independent, each with one common success probability.
- The arm sizes are fixed before outcomes are observed.
- The analysis and its level are chosen before outcomes are observed.

Unresolved obligations: None.
Not established here: No statistical guarantee is established here.
Independent check of this derivation: passed.

This is called a derivation. Read its parts separately:

PartMeaning
StepsEstablished from your declarations by a stated rule.
AssumptionsFacts about the real study. StatClaim cannot check them; you must.
Unresolved obligationsSomething a later guarantee needs that is not shown yet.
Not established hereA reminder: this is about fit, not about error rates.

A derivation says the declarations fit together. It is not the 5% guarantee; that is still the job of verify. The last line means a second, separate program re-read the declarations and confirmed every step.

In VS Code. Put the cursor on a declaration and run StatClaim: Explain Contract. Leave out --name on the command line to explain every declaration, including the family endpoints.

A report for the whole file

statclaim report examples/tutorial/05_several_endpoints.stat --output report.md

The report collects every derivation, the assumptions to meet, the open obligations and the claims the file requests. It is meant for a protocol appendix or a reviewer.

What does an edit affect?

A colleague suggests giving the two secondary endpoints more of the budget. The edited file changes two levels from 1/80 to 1/40:

examples/tutorial/06_changed_levels.stat
let response = fisher(design=design, null=null, alpha=1/40)
let remission = fisher(design=design, null=null, alpha=1/40)
let relapse = fisher(design=design, null=null, alpha=1/40)
statclaim impact examples/tutorial/05_several_endpoints.stat examples/tutorial/06_changed_levels.stat
Declarations
- remission: changed directly
- relapse: changed directly
- endpoints: affected through a dependency

Contracts affected
- remission: satisfied -> satisfied (re-derived for the new declaration)
- relapse: satisfied -> satisfied (re-derived for the new declaration)
- endpoints: satisfied -> satisfied, 1 unresolved

Claims affected
- verify familywise(endpoints): must be re-run: its subject changed

New diagnostics
- obligation [allocation] (line 17): endpoints: allocated alpha 3/40 exceeds the
  requested family bound 1/20.

Each analysis is still fine on its own. The family is where the edit bites: the shares now add up to 3/40, so the familywise claim has an open obligation, and the certificate from lesson 5 no longer describes this file. In VS Code, StatClaim: Show Change Impact does the same for your unsaved edits.

What you learned

  • A passing declaration keeps a derivation; you see it only when you ask.
  • Steps are established, assumptions are yours to meet, obligations are still open.
  • report documents a study file; impact shows what an edit affects.

Try it

Run statclaim explain on 03_optional_stopping.stat. The declaration passes its contract, with one unresolved obligation: the missing justification from lesson 3.

Lesson 7

Choosing a sample size

In this lesson

Before the study, we ask how many participants are needed to have an 80% chance of detecting the effect we expect.

Power depends on what you expect to happen. Those expectations are inputs you must supply. Here we expect a 10% success rate under control and 40% under treatment.

examples/tutorial/07_sample_size.stat
# Lesson 7: how many participants?
use models.two_arm_binomial
use sampling
use tests.fisher
use planning

let study = two_arm_binomial(n_control=25, n_treatment=25)
let analysis = fisher(design=fixed(model=study), null=equal_proportions(model=study), alpha=1/20)

# Planning inputs: the rates we expect, and the power we need there.
let expected = binomial_rates(p_control=1/10, p_treatment=2/5)
let target = power_target(at=expected, minimum=4/5, maximum_typeI=1/20)

# Is 25 per arm enough?
let check = calculate(meets(analysis=analysis, target=target))
let power = check.calculation.power

# What is the smallest equal-arm size between 20 and 60 that is enough?
let candidates = equal_arm_sizes(analysis=analysis, min_per_arm=20, max_per_arm=60)
let sizing = smallest_sample_size(candidates=candidates, target=target)
let recommendation = calculate(sizing)
let per_arm = recommendation.calculation.n_control
let verification = verify(sizing)
binomial_rates
The planning point: one expected rate per group. It is a guess for planning and does not replace the null.
power_target
What the design must achieve: power of at least 4/5 at the planning point, with a false-positive rate of at most 1/20.
meets
The claim "this analysis meets this target".
equal_arm_sizes
A range of designs to search, here 20 to 60 per group.
smallest_sample_size
The claim "some design in the range meets the target, and no smaller one does".
calculated [check]: meets(analysis)
  arm sizes = (25, 25); total = 50
  power ~ 0.5905; power target met = false; Type I target met = true
calculated [recommendation]: sample_size(candidates)
  arm sizes = (36, 36); total = 72
  power ~ 0.8004; power target met = true; Type I target met = true
verified [verification]: sample_size(candidates)
  Its power is at least 4/5 at p_control = 1/10, p_treatment = 2/5.
  No equal-arm candidate with 20 up to 35 controls reaches that power, so (36, 36)
  is the smallest sufficient candidate in the range 20 to 60.

Twenty-five per group gives only 59% power. The answer is 36 per group. Lean recomputes the power of that design and of every smaller one in the range.

What the result covers. Power is checked at your planning point only. If the true rates differ, the power differs. The "smallest" claim is about the range you declared, not about all possible designs.

For unequal groups, use allocated_arm_sizes with treatment_per_control=2 for two treated participants per control (examples/unequal_allocation.stat).

What you learned

  • Planning needs expected rates and a power target, both stated explicitly.
  • meets checks one design; smallest_sample_size searches a range.
  • Verified power is power at the planning point.

Try it

Raise the required power to 9/10. The recommendation grows; if it exceeds your range you get no_feasible_candidate, so widen the range.

Lesson 8

Better, or at least not worse

In this lesson

Most trials ask a directional question. We test whether a treatment is better than the control, estimate by how much, and then test whether a cheaper treatment is at least not much worse.

The Fisher test of lessons 1 to 7 asks whether two rates differ. Two more analyses ask directional questions. Both use a null you met in lesson 3, proportion_difference_at_most, and both reuse the claims and planning vocabulary you already know.

Is the treatment better?

examples/tutorial/08_better_or_not_worse.stat
# Lesson 8: is the treatment better, or at least not worse?
use models.two_arm_binomial
use sampling
use tests.fisher
use tests.difference
use estimation
use planning

# Part 1: is the treatment better?
let study = two_arm_binomial(n_control=36, n_treatment=36)
let design = fixed(model=study)
let no_better = proportion_difference_at_most(model=study, value=0)
let superiority = fisher_one_sided(design=design, null=no_better, alpha=1/40)

let target = power_target(
    at=binomial_rates(p_control=1/10, p_treatment=2/5),
    minimum=4/5,
    maximum_typeI=1/40,
)
let planned = verify(meets(analysis=superiority, target=target))

# 4 of 36 controls and 14 of 36 treated participants responded.
let data = observe(analysis=superiority, control_successes=4, treatment_successes=14)
let outcome = verify(result(data))
no_better
The null "treatment rate minus control rate is at most 0": the treatment is no better. Rejecting it supports the treatment.
fisher_one_sided
The one-sided Fisher test. It accepts this null and no other. The level 1/40 is the usual one-sided 2.5%.

meets, observe and result are unchanged from lessons 4 and 7.

verified [planned]: meets(superiority)
  The one-sided Fisher analysis with arm sizes (36, 36) and alpha 1/40 has Type I error
  at most 1/40 whenever the treatment success probability is at most the control's.
  Its power is at least 4/5 at p_control = 1/10, p_treatment = 2/5.
verified [outcome]: result(data)
  Exact one-sided p-value equals the Lean definition for these counts.
  Reported decision follows from comparing that p-value with the level.

The one-sided p-value is 0.0065, so the null is rejected. Read the error claim closely: it holds whenever the treatment is no better than the control, including when it is worse. A guarantee only for exactly equal rates would be weaker.

By how much?

examples/tutorial/08_better_or_not_worse.stat
# How large is the difference?
let interval = calculate(
    difference_interval(model=study, control_successes=4, treatment_successes=14, level=19/20)
)
calculated [interval]: interval(study)
  control 4 of 36, treatment 14 of 36; estimate ~ 0.2778;
  interval = [-0.0691, 0.5627] at level 19/20

The estimated difference is 28 percentage points. The interval is built from an exact interval for each group, which makes it valid for every pair of true rates and also wide. Here it includes zero although the test rejected. That is not a contradiction: the interval is cautious, and the two answer slightly different questions. Report both.

Is it at least not much worse?

A cheaper treatment does not need to be better. It may be enough to show it is at most 10 percentage points worse. This is a non-inferiority question.

examples/tutorial/08_better_or_not_worse.stat
# Part 2: is a cheaper treatment at most 10 points worse?
let trial = two_arm_binomial(n_control=60, n_treatment=60)
let too_much_worse = proportion_difference_at_most(model=trial, value=-1/10)
let non_inferiority = difference_test(design=fixed(model=trial), null=too_much_worse, alpha=1/40)

# 50 of 60 controls and 52 of 60 treated participants responded.
let trial_data = observe(analysis=non_inferiority, control_successes=50, treatment_successes=52)
let trial_outcome = verify(result(trial_data))

# How likely was this trial to succeed if both rates are truly 85%?
let hoped = power_target(
    at=binomial_rates(p_control=17/20, p_treatment=17/20),
    minimum=4/5,
    maximum_typeI=1/40,
)
let chance = calculate(meets(analysis=non_inferiority, target=hoped))
too_much_worse
The null "treatment rate minus control rate is at most -1/10": the treatment falls short by more than the margin. Rejecting it shows non-inferiority.
difference_test
An exact test for a null with a margin. It needs use tests.difference.
verified [trial_outcome]: result(trial_data)
  The exact difference test with arm sizes (60, 60) and the listed rejection thresholds
  has Type I error at most 1/40 whenever p_treatment - p_control <= -1/10.
  For 50 of 60 control and 52 of 60 treatment successes, the test does not reject the
  null: with that many control successes it needs at least 53 treatment successes.
calculated [chance]: meets(non_inferiority)
  arm sizes = (60, 60); total = 120
  power ~ 0.3017; power target met = false

The treatment did slightly better in the sample, and non-inferiority was still not shown. The last lines say why: with 60 per group this trial had only a 30% chance of succeeding even if the two treatments are equally good. Non-inferiority trials need large samples, and the planning step would have said so in advance.

What this test is. For each number of control successes, the test lists how many treatment successes are needed to reject. The list is stored in the certificate. Results are a decision without a p-value, and the test currently supports up to 120 participants per group.

What you learned

  • fisher_one_sided tests whether the treatment is better; difference_test tests a margin.
  • Their error guarantees cover the whole null, not only its boundary.
  • difference_interval estimates the difference, conservatively.

Try it

Search for a non-inferiority sample size: add equal_arm_sizes(analysis=non_inferiority, min_per_arm=60, max_per_arm=120) and calculate(sample_size(...)) with a target of minimum=1/2.

Lesson 9

A single-arm study

In this lesson

Everyone receives the treatment and we ask whether the response rate beats a known benchmark of 20%. We plan the study, analyse it, and report an interval.

This lesson uses a new test module but the planning vocabulary from lesson 7.

examples/tutorial/09_single_arm.stat
# Lesson 9: one arm, from planning to estimate.
use tests.binomial
use planning

# Plan: is the response rate above 20%? We hope for 40%.
let pilot = one_arm_binomial(n=25)
let test = binomial_test(model=pilot, null_rate=1/5, alpha=1/20)
let target = power_target(at=response_rate(value=2/5), minimum=4/5, maximum_typeI=1/20)
let sizing = smallest_sample_size(
    candidates=sample_sizes(analysis=test, min_n=10, max_n=60),
    target=target,
)
let plan = verify(sizing)
binomial_test
A one-sided exact test. The null is "the response rate is at most null_rate".
response_rate
The planning point for one group: we hope for 40%.
sample_sizes
The range to search, written inside the call this time.
verified [plan]: sample_size(<expression>)
  The exact binomial test with 35 participants, rejecting at 12 or more responses,
  rejects with probability at most 1/20 for every response rate at or below 1/5.
  It rejects with probability at least 4/5 at the response rate 2/5.
  No sample size from 10 up to 34 meets both bounds with this test, so 35 is the
  smallest sufficient candidate in the range 10 to 60.

So we recruit 35 and will declare success with 12 or more responders.

After the study

examples/tutorial/09_single_arm.stat
# Analyse: the study ran with 35 participants and 14 responded.
let study = one_arm_binomial(n=35)
let analysis = binomial_test(model=study, null_rate=1/5, alpha=1/20)
let data = responses(analysis=analysis, count=14)
let result = verify(binomial_result(data))

# Estimate: an exact 95% confidence interval for the response rate.
let interval = confidence_interval(model=study, count=14, level=19/20)
let estimate = calculate(interval)
let lower = estimate.calculation.lower
let upper = estimate.calculation.upper
let coverage = verify(interval)
responses, binomial_result
The one-arm counterparts of observe and result from lesson 4.
confidence_interval
An exact interval for the response rate. level=19/20 is 95%.
verified [result]: result(data)
  The exact one-sided p-value for 14 responses out of 35 at the null rate 1/5 is
  approximately 0.005258.
  The test at level 1/20 rejects at 12 or more responses, so the decision is: reject the null.
calculated [estimate]: interval(study)
  14 responses out of 35; estimate ~ 0.4000; interval = [0.2387, 0.5789] at level 19/20
verified [coverage]: interval(study)
  For every true response rate, the exact confidence set for 35 participants contains
  that rate with probability at least 19/20.

The report writes itself: 14 of 35 responded (40%, 95% CI 24% to 58%), p = 0.005. The verified interval claim is about the method: whatever the true rate, intervals built this way contain it at least 95% of the time.

What you learned

  • tests.binomial covers testing and estimating one proportion.
  • Planning, testing and estimation share the same study declaration.
  • A confidence interval's guarantee is about the procedure, for every true rate.

Try it

Change the count to 10. The test no longer rejects, and the interval now includes 20%. The two results agree, as they should.

Lesson 10

Stopping early

In this lesson

We return to the problem from lesson 3 and solve it: a study with a planned interim look that stops early if the treatment is clearly not working.

Early stopping is fine when the rule is part of the design and the error rates are worked out for the whole procedure. A two-stage design does this: treat a first group, stop if too few respond, otherwise continue.

examples/tutorial/10_stopping_early.stat
# Lesson 10: a design with a planned interim look.
use designs.two_stage
use planning

let target = power_target(at=response_rate(value=2/5), minimum=4/5, maximum_typeI=1/20)

# Propose a design: 13 participants, then 30 more if more than 3 respond.
let stages = two_stage_binomial(n_stage1=13, n_stage2=30)
let rule = threshold_rule(continue_above=3, reject_above=12)
let proposed = two_stage_test(design=stages, rule=rule, null_rate=1/5)
let characteristics = calculate(meets(analysis=proposed, target=target))
let expected_size = characteristics.calculation.expected_sample_size_null
let verification = verify(meets(analysis=proposed, target=target))
two_stage_binomial
Thirteen participants first, thirty more if the study continues.
threshold_rule
Continue only with more than 3 responders in stage one. At the end, reject the null with more than 12 responders in total.
two_stage_test
The complete design: stages, rule, and the benchmark rate it is tested against.

The target and meets are the ones you know. The claim is now about the whole procedure, interim look included.

calculated [characteristics]: meets(proposed)
  stages = (13, 30); Type I at the null rate ~ 0.0496; expected sample size under the null ~ 20.58
  power ~ 0.8002; power target met = true; Type I target met = true
verified [verification]: meets(proposed)
  The complete two-stage design (stages 13 and 30, continuing above 3 responses and
  rejecting above 12 in total) rejects with probability at most 1/20 for every
  response rate at or below 1/5.
  It rejects with probability at least 4/5 at the response rate 2/5.

Compare with lesson 9. The fixed design needed 35 participants. This one needs up to 43, but if the treatment does not work it stops after 13 about three times in four, for an average of 21.

After the study

Enter the counts as they happened. Here 5 of 13 responded in stage one, so the study continued, and 9 of 30 responded in stage two:

let data = completed_stages(analysis=proposed, stage1_responses=5, stage2_responses=9)
let outcome = verify(two_stage_result(data))
verified [outcome]: result(data)
  With 5 responses in stage one the declared rule continues, and with 14 responses
  in total it rejects the null.
  The complete design rejects with probability at most 0.0496 for every response
  rate at or below 1/5.

If the study had stopped, you would write stopped_at_interim(analysis=proposed, stage1_responses=3). Counts that contradict the rule are rejected: you cannot report stage-two data for a study the rule would have stopped.

Finding a design

You do not have to guess the numbers. Describe the search and use sample_size:

examples/tutorial/10_stopping_early.stat
# Or let StatClaim find one.
let search = two_stage_designs(null_rate=1/5, max_total=45, criterion="minimax")
let found = calculate(sample_size(candidates=search, target=target))
calculated [found]: sample_size(search)
  continue above 4 responses in stage one; reject above 10 in total (minimax design)
  stages = (18, 15); expected sample size under the null ~ 22.25
  power ~ 0.8011; power target met = true; Type I target met = true

"minimax" finds the design with the smallest maximum size (33 here). "optimal" finds the one with the smallest average size when the treatment does not work, which is the design we proposed by hand. Verifying a search certifies the selected design. That it is the best one is a calculation, and the output says so.

What you learned

  • An early stop is safe when it is declared as part of the design.
  • The same target and meets claim apply to the whole procedure.
  • A search finds a design; verification checks the one it found.

Try it

Replace calculate with verify on the last line, then switch the criterion to "optimal".

Lesson 11

A Bayesian stopping rule

In this lesson

Many teams prefer to decide with posterior probabilities. We write such a rule and then check its false-positive rate and power, which the rule alone does not give us.

examples/tutorial/11_bayesian_rule.stat
# Lesson 11: decide with posterior probabilities, then check error rates.
use designs.two_stage
use planning

let stages = two_stage_binomial(n_stage1=10, n_stage2=20)
let prior = beta_prior(a=1, b=1)
let rule = posterior_rule(
    prior=prior,
    reference=1/5,
    continue_at_least=1/2,
    success_at_least=19/20,
)
let analysis = two_stage_test(design=stages, rule=rule, null_rate=1/5)

let target = power_target(at=response_rate(value=2/5), minimum=4/5, maximum_typeI=1/10)
let characteristics = calculate(meets(analysis=analysis, target=target))
let verification = verify(meets(analysis=analysis, target=target))
beta_prior
The prior belief about the response rate. a=1, b=1 is uniform. Parameters are positive whole numbers.
posterior_rule
Decisions are based on the posterior probability that the response rate exceeds reference. Continue after stage one if it is at least 1/2. Declare success at the end if it is at least 19/20.

Only the rule changed. The stages, the test and the target are declared as in lesson 10.

calculated [characteristics]: meets(analysis)
  stages = (10, 20); Type I at the null rate ~ 0.0581; expected sample size under the null ~ 22.48
  power ~ 0.8059; power target met = true; Type I target met = true
verified [verification]: meets(analysis)
  The complete two-stage design (stages 10 and 20, with its posterior interim and
  final rules) rejects with probability at most 1/10 for every response rate at or below 1/5.

Look at the false-positive rate: 5.8%. Requiring 95% posterior probability does not make it 5%. A posterior threshold and a false-positive rate are different quantities, and this is why we asked for maximum_typeI=1/10. If you need 5%, raise success_at_least and check again.

One stated limit. The posterior probability is computed with a standard closed formula. That the formula equals the Beta posterior is not proved in Lean, and the certificate lists this under its assumptions.

What you learned

  • Bayesian decision rules fit the same design and target vocabulary.
  • A posterior threshold does not set the false-positive rate; check it.
  • Certificates say what was assumed as well as what was proved.

Try it

Set maximum_typeI=1/20 and verify: you get typeI_target_not_met. Then raise success_at_least to 39/40 and see what happens to the power.

Lesson 12

A continuous outcome, and a cited guarantee

In this lesson

Not every guarantee is proved in Lean. For a t-test, StatClaim checks that your study fits the test, then tells you which published guarantee you are relying on and what it assumes.

examples/tutorial/12_continuous_outcome.stat
# Lesson 12: a continuous outcome, with a guarantee that is cited, not proved.
use models.two_arm_continuous
use sampling
use tests.t

let study = two_arm_continuous(n_control=60, n_treatment=60)
let plan = fixed(model=study)
let null = equal_means(model=study)

let analysis = t_test(design=plan, null=null, alpha=1/20)
let checked = verify(typeI(analysis))
let grade = checked.evidence.grade

let robust = welch_test(design=plan, null=null, alpha=1/20)
let approximate = verify(typeI(robust))
let scope = approximate.claim.scope
two_arm_continuous
Two arms with a measured outcome, such as blood pressure. The model fixes no distribution. Each test states the distribution it assumes.
equal_means
The null hypothesis: the two arm means are equal.
t_test, welch_test
The pooled-variance t-test and Welch's test. You declare them exactly like fisher in lesson 1.

This file needs no Lean. Check it and read the first result:

cited [checked]: typeI(analysis)
  Evidence: cited from the literature; not machine-checked; guarantee: finite-sample bound
  Method: Two-sided pooled-variance t-test (t_test, version 1)
  Null rejection probability equals 1/20 whenever mean_treatment = mean_control.
  Assumptions:
    [independent_observations] Observations are independent within and between the two arms. (assumed)
    [fixed_sample_sizes] Arm sizes are fixed before observing outcomes. (declared)
    [single_analysis] The test is run once, on the complete data. (declared)
    [normal_outcomes] Outcomes in each arm are normally distributed. (assumed)
    [equal_variances] The two arms have the same variance. (assumed)
  References:
    Student (1908). The probable error of a mean. Biometrika 6(1), 1-25.
    ...

The status is cited, not verified. StatClaim checked the fit: the null suits the test, the null and the design describe the same study, and the design is fixed. It did not check the guarantee. That comes from the references, and it holds only under the listed assumptions.

Each assumption has a name and a mark. Declared means your file states it: fixed says the sizes are set in advance and the test is run once. Assumed means nothing in the file can show it. Normal outcomes and equal variances are yours to defend.

Welch's test drops those two assumptions, at a price:

cited [approximate]: typeI(robust)
  Evidence: cited from the literature; not machine-checked; guarantee: large-sample approximation
  Method: Two-sided Welch t-test (welch_test, version 1)
  Null rejection probability approaches 1/20 in the limit as the sample sizes grow,
  whenever mean_treatment = mean_control. No bound is claimed at the declared sample sizes.

A finite-sample bound holds at your sample size. A large-sample approximation gets closer as the study grows, and promises nothing exact at 60 per arm. StatClaim never words the two alike. A file with any cited claim ends with Program status: cited.

Time to an event. The same pattern covers survival data: two_arm_survival, equal_survival and log_rank, from models.two_arm_survival and tests.survival. Its guarantee is a large-sample approximation in the number of events. See examples/log_rank.stat.
Asking a one-sided question. Use t_test_one_sided or welch_test_one_sided with mean_difference_at_most(model=study, value=...). Zero asks whether the treatment is better. A negative value is a non-inferiority margin, in the outcome's units.

What you learned

  • A cited guarantee is checked for fit, not proved.
  • Every result says how it was established and whether it is exact or approximate.
  • Assumptions are named, and marked as declared or assumed.

Try it

Change fixed to adaptive: the claim becomes unresolved, as in lesson 3. Then give t_test the null mean_difference_at_most(model=study, value=0) and read the guidance.

Lesson 13

Proved and cited tests under one error bound

In this lesson

A trial often has a yes-or-no endpoint and a measured one. We put a proved Fisher test and a cited t-test in one family, and see exactly which part of the familywise guarantee a machine checked.

examples/tutorial/13_mixed_endpoints.stat
# Lesson 13: one error bound over a proved test and a cited test.
use models.two_arm_binomial
use models.two_arm_continuous
use sampling
use tests.fisher
use tests.t
use multiplicity.bonferroni

let responders = two_arm_binomial(n_control=120, n_treatment=120)
let response = fisher(
    design=fixed(model=responders),
    null=equal_proportions(model=responders),
    alpha=1/40,
)

let scores = two_arm_continuous(n_control=120, n_treatment=120)
let symptoms = t_test(
    design=fixed(model=scores),
    null=equal_means(model=scores),
    alpha=1/40,
)

let endpoints = bonferroni(analyses=[response, symptoms], alpha=1/20)
let family = verify(familywise(endpoints))
let primary = verify(typeI(response))

Each endpoint has its own model, because the outcomes are different kinds of data. bonferroni is the same constructor as in lesson 5. With a cited member there is no joint_law to state: the combination holds for any dependence between the endpoints.

conditional [family]: familywise(endpoints)
  Evidence: combination proved in Lean; the members' own guarantees are assumed; guarantee: finite-sample bound
  The member levels sum to 1/20, which does not exceed the familywise bound 1/20.
  If each member rejects its own true null with probability at most its level, the
  probability of rejecting any true member null is at most 1/20, for every configuration
  of true and false nulls and any dependence between members.
  Not checked here: the members' own error bounds, listed as assumptions.
  Assumptions:
    The set of analyses and their levels are chosen before outcomes are observed.
    response: Null rejection probability is at most 1/40 whenever p_treatment = p_control. (provable in Lean; verify the member's own Type I claim)
    symptoms: Null rejection probability is at most 1/40 whenever mean_treatment = mean_control. (cited from the literature; not machine-checked)
verified [primary]: typeI(response)
  Evidence: proved in Lean; guarantee: finite-sample bound
Program status: conditional

There are now three statuses for a result that went through, and they are not interchangeable:

StatusWhat a machine checkedWhat you rely on
verifiedThe guarantee itself, in LeanThe model's assumptions
conditionalHow the parts combine, in LeanEach member's own guarantee
citedThat your study fits the methodThe published result and its assumptions

The family is conditional. Lean proved that the two levels fit the budget and that the union bound then gives 1/20. It took each member's own 1/40 as given. For response that is not a leap: the last line verifies it. For symptoms it rests on the t-test's cited guarantee and its assumptions, such as normal outcomes.

The file's status is the weakest one in it, so one cited or conditional claim is never hidden behind verified ones.

Large-sample members. Swap t_test for welch_test and the family's guarantee becomes a large-sample approximation too. A family is only as exact as its least exact member.

What you learned

  • Proved and cited tests can share one familywise bound.
  • Conditional means the combination was proved and the members were assumed.
  • A file reports its weakest status.

Try it

Raise one member's alpha to 1/20: the family is overallocated and stays unresolved. Then run statclaim explain on the file and find the guarantee the family's contract carries.

Lesson 14

An interim look

In this lesson

In lesson 3, looking at the data early left the claim unresolved. Here we plan the look: we split the error level between an interim analysis and the final one, and get a bound for the whole trial.

examples/tutorial/14_interim_look.stat
# Lesson 14: look at the data once before the end, without inflating the error.
use models.two_arm_continuous
use sampling
use tests.t
use designs.group_sequential

let halfway = two_arm_continuous(n_control=50, n_treatment=50)
let complete = two_arm_continuous(n_control=100, n_treatment=100)

let interim = t_test(design=fixed(model=halfway), null=equal_means(model=halfway), alpha=1/200)
let final = t_test(design=fixed(model=complete), null=equal_means(model=complete), alpha=9/200)

let trial = alpha_spending(looks=[interim, final], alpha=1/20)
let overall = verify(typeI(trial))
Two models
Each look is an ordinary analysis of the data collected so far. The model gives the cumulative arm sizes at that look: 50 per arm halfway, 100 at the end.
alpha per look
The level spent at that look. Here 0.005 at the interim look and 0.045 at the end.
alpha_spending
The whole design: test at each look in order, and stop at the first rejection. The levels may sum to at most the overall alpha.
conditional [overall]: typeI(trial)
  Evidence: combination proved in Lean; the members' own guarantees are assumed; guarantee: finite-sample bound
  The look levels sum to 1/20, which does not exceed the overall error bound 1/20.
  If the test at each look rejects the true null with probability at most its level, the
  probability of rejecting it at any look is at most 1/20, whatever the dependence between
  looks. This split is conservative: it does not use the correlation between looks.
  Assumptions:
    The looks happen at the declared cumulative sample sizes, fixed in advance, and the study stops at the first look that rejects.
    interim: Null rejection probability is at most 1/200 whenever mean_treatment = mean_control. (cited from the literature; not machine-checked)
    final: Null rejection probability is at most 9/200 whenever mean_treatment = mean_control. (cited from the literature; not machine-checked)

The claim is typeI, not familywise: every look tests the same null, so rejecting at any look is one kind of error. The status is conditional, as in lesson 13. Lean proved that the two levels fit the budget and that the chance of rejecting at either look is then at most 1/20. Each look's own level rests on its test.

Compare the assumptions with lesson 12. "The test is run once" is gone. That assumption is exactly what a sequential design replaces: it is now "the looks happen at the declared sample sizes, and the study stops at the first rejection".

Conservative on purpose. Splitting the level this way ignores that the looks share data. Boundaries such as O'Brien-Fleming use that correlation to spend more at each look; they are not supported yet. With this split you can never spend more than the total.

What you learned

  • A planned interim look is a design with its own error bound.
  • Each look is the same test at the cumulative sample size.
  • A design can replace an assumption, not only add one.

Try it

Set the final look's alpha to 1/20: the design overspends and stays unresolved. Then swap the order of the looks and read the diagnostic.

Reference

What to reach for

You want toModulesClaimLesson
Compare two proportionsmodels.two_arm_binomial, sampling, tests.fishertypeI, result1, 4
Ask whether a treatment is bettertests.fisherfisher_one_sided with typeI, result8
Show a treatment is not worse by a margintests.differencedifference_test with typeI, result8
Estimate a differenceestimationdifference_interval8
Compare two meansmodels.two_arm_continuous, sampling, tests.tt_test, welch_test with typeI (cited)12
Compare two survival curvesmodels.two_arm_survival, sampling, tests.survivallog_rank with typeI (cited)12
Control error over several endpointsmultiplicity.bonferronifamilywise5, 13
Choose a sample sizeplanningmeets, sample_size, smallest_sample_size7
Test or estimate one proportiontests.binomialbinomial_result, confidence_interval9
Look at the data before the enddesigns.group_sequentialalpha_spending with typeI14
Stop early for futilitydesigns.two_stagemeets, sample_size10, 11
See why a declaration passed, or what an edit affects(built in)explain, report, impact commands6

Every claim goes through calculate for numbers or verify for checked evidence. statclaim catalogue lists every constructor and field.

Habits worth keeping