Algorithm Search⌘K

Algorithmadvanced

O'Brien-Fleming boundary

Also called O'Brien-Fleming stopping rule.

The group sequential boundary c_k = C sqrt(K/k), very strict at early looks and near the fixed-sample value at the last. C comes from recursive integration and bisection.

Time
O(B K m^2) worst
Space
O(m) extra
Where
B = the number of bisection steps on C; K = the number of analyses; m = the number of quadrature points per analysis
Properties
deterministicexact up to quadratureofflineiterative
Origin
Peter C. O'Brien, Thomas R. Fleming, 1979

The O'Brien-Fleming boundary is the most used stopping rule for a two-sided group sequential design. With KK analyses at information levels I1<⋯<IKI_1 < \cdots < I_K, it rejects H0:θ=0H_0: \theta = 0 at the first analysis kk with ∣Zk∣≥ck|Z_k| \ge c_k, where

ck=CIK/Ik,c_k = C\sqrt{I_K/I_k},

which is CK/kC\sqrt{K/k} for equally spaced analyses. Early critical values are very large, and the last one is only a little above the fixed-sample value: for K=5K = 5 and α=0.05\alpha = 0.05 they are 4.56, 3.23, 2.63, 2.28 and 2.04. The constant CC is the solution of P0(some ∣Zk∣≥ck)=αP_0(\text{some } |Z_k| \ge c_k) = \alpha. The algorithm below computes this probability by recursive numerical integration over the canonical joint distribution of the ZkZ_k, and finds CC by bisection. O'Brien and Fleming proposed the boundary in 1979; Pocock's constant boundary, from 1977, is the main alternative and is described under Variants.

In plain words

A trial will look at its data five times. At each look, a score measures the evidence that the treatment works. If the score crosses a line, the trial stops. The O'Brien-Fleming rule sets the lines so that early looks need overwhelming evidence and the last look needs about the usual amount. So a trial stops early only when the result is striking, and a trial that runs to the end is judged almost as if there had been no early looks. The algorithm finds the height of the lines. It tries a height, computes the chance of a false stop at any look when the treatment does nothing, and adjusts the height up or down until that chance is exactly the planned 5%.

The problem

Input. The number of analyses KK, the information levels 0<I1<⋯<IK0 < I_1 < \cdots < I_K (or only their ratios), and the two-sided level α∈(0,1)\alpha \in (0, 1).

Model. Under H0H_0, the scores Sk=ZkIkS_k = Z_k\sqrt{I_k} satisfy S0=0S_0 = 0 and have independent increments Sk−Sk−1∼N(0,Ik−Ik−1)S_k - S_{k-1} \sim N(0, I_k - I_{k-1}), with I0=0I_0 = 0. This is the canonical joint distribution of the group sequential design page; it is exact for normal data with known variance and holds approximately for most large-sample statistics.

Output. The constant CC such that

P0(∣Zk∣≥CIK/Ik for some k≤K)=α,P_0\bigl(|Z_k| \ge C\sqrt{I_K/I_k} \text{ for some } k \le K\bigr) = \alpha,

and the critical values ck=CIK/Ikc_k = C\sqrt{I_K/I_k}. On the score scale the boundary is flat: ∣Zk∣≥ck|Z_k| \ge c_k means ∣Sk∣≥CIK|S_k| \ge C\sqrt{I_K}.

The algorithm

  1. OBRIEN-FLEMING(K, α, I_1, ..., I_K)
  2. 1lo ← z_{1-α/2}, hi ← z_{1-α/(2K)} ▷ the root lies in [lo, hi]
  3. 2while hi - lo > tol do
  4. 3C ← (lo + hi)/2
  5. 4if CROSS(C, I) > α then lo ← C else hi ← C
  6. 5return C and c_k = C·sqrt(I_K / I_k) for k = 1..K
  7. CROSS(C, I_1, ..., I_K) ▷ P_0(|S_k| ≥ C·sqrt(I_K) for some k)
  8. 6b ← C·sqrt(I_K)
  9. 7p ← 2Φ̄(b / sqrt(I_1)); g ← density of N(0, I_1) on [-b, b]
  10. 8for k ← 2 to K do
  11. 9σ ← sqrt(I_k - I_{k-1})
  12. 10p ← p + ∫_{-b}^{b} g(u)[Φ((-b - u)/σ) + Φ̄((b - u)/σ)] du
  13. 11g(s) ← ∫_{-b}^{b} g(u) φ((s - u)/σ)/σ du for |s| < b
  14. 12return p

Lines L6 to L12. The function gg is the sub-density of SkS_k on the event that no earlier analysis crossed; its total mass is the probability of reaching analysis k+1k + 1. Line L7 handles the first analysis: it crosses with probability 2Φˉ(b/I1)2\bar\Phi(b/\sqrt{I_1}), and the rest of the N(0,I1)N(0, I_1) density, restricted to [−b,b][-b, b], carries on. Line L10 adds the probability of crossing first at analysis kk: from a position uu inside the boundary, the next score is uu plus an independent N(0,σ2)N(0, \sigma^2) step. Line L11 moves the sub-density one step forward by convolution with that step and drops the part outside [−b,b][-b, b]. This is the recursion of Armitage, McPherson and Rowe (1969).

Lines L1 to L5. The crossing probability decreases as CC grows. At C=z1−α/2C = z_{1-\alpha/2} the last analysis alone crosses with probability α\alpha, so the total is at least α\alpha. At C=z1−α/(2K)C = z_{1-\alpha/(2K)} every ck≥Cc_k \ge C, so each analysis crosses with probability at most α/K\alpha/K and the total is at most α\alpha. Bisection keeps the root inside [lo,hi][lo, hi] and halves the interval each step.

Quadrature. The implementation evaluates the integrals of lines L10 and L11 by Simpson's rule on a grid over [−b,b][-b, b] with spacing at most σ/16\sigma/16. Doubling the grid changes the crossing probability by less than 10−710^{-7} in the examples below.

Example

Take K=5K = 5 equally spaced analyses, Ik=kI_k = k, and α=0.05\alpha = 0.05. Then lo=1.95996lo = 1.95996 and hi=z0.995=2.57583hi = z_{0.995} = 2.57583. The first bisection steps are:

step CC CROSS(C)(C) new interval
1 2.2679 0.02755 [1.9600,2.2679][1.9600, 2.2679]
2 2.1139 0.04141 [1.9600,2.1139][1.9600, 2.1139]
3 2.0369 0.05040 [2.0369,2.1139][2.0369, 2.1139]
4 2.0754 0.04571 [2.0369,2.0754][2.0369, 2.0754]
5 2.0562 0.04800 [2.0369,2.0562][2.0369, 2.0562]
6 2.0466 0.04919 [2.0369,2.0466][2.0369, 2.0466]

It converges to C=2.0401C = 2.0401. The critical values and their parts of α\alpha are:

analysis kk 1 2 3 4 5
ck=2.04015/kc_k = 2.0401\sqrt{5/k} 4.5617 3.2256 2.6337 2.2809 2.0401
nominal two-sided p-value of ckc_k 0.000005 0.00126 0.00845 0.02256 0.04134
P0(first crossing at k)P_0(\text{first crossing at } k) 0.00001 0.00125 0.00764 0.01668 0.02442

The last critical value 2.040 corresponds to a nominal p-value of 0.041, so almost all of the 0.05 is still available at the end. With the plain value 1.96 at all five analyses, CROSS gives 0.061 for this shape, and 0.142 for a flat line at 1.96.

The constant for other numbers of analyses, equally spaced, α=0.05\alpha = 0.05 two-sided:

KK 1 2 3 4 5
O'Brien-Fleming CC 1.9600 1.9774 2.0040 2.0243 2.0401
Pocock constant 1.9600 2.1783 2.2895 2.3613 2.4132

For K=2K = 2 the boundary is (2.7965,1.9774)(2.7965, 1.9774): each tail of the first analysis has probability 0.00258 and each tail of the second has first-crossing probability 0.02242.

Sample size. With 90% power, the maximum information must be R=1.0265R = 1.0265 times the fixed-sample information (z0.975+z0.9)2/δ2=10.507/δ2(z_{0.975} + z_{0.9})^2/\delta^2 = 10.507/\delta^2 for K=5K = 5. The expected information at stopping is 0.750 of the fixed-sample information when θ=δ\theta = \delta, 0.961 when θ=δ/2\theta = \delta/2 and 1.019 when θ=0\theta = 0.

Correctness

The proof is in full below. In outline:

  1. The recursion is exact. By induction on kk, the function gg after line L11 at step kk is the sub-density of SkS_k on the event that no analysis j≤kj \le k crossed. The induction step is the Chapman-Kolmogorov identity for the independent normal increment. So the value returned by line L12 is ∑kP0(first crossing at k)=P0(some ∣Sk∣≥b)\sum_k P_0(\text{first crossing at } k) = P_0(\text{some } |S_k| \ge b), before quadrature.
  2. Monotone in CC. If C<C′C < C', the event "some ∣Sk∣≥C′IK|S_k| \ge C'\sqrt{I_K}" is contained in the event "some ∣Sk∣≥CIK|S_k| \ge C\sqrt{I_K}", and the difference contains the event CIK≤∣SK∣<C′IKC\sqrt{I_K} \le |S_K| < C'\sqrt{I_K} with no earlier crossing, which has positive probability. So CROSS is strictly decreasing. It is also continuous, because each ∣Sk∣|S_k| has a continuous distribution.
  3. The bracket. CROSS(z1−α/2)≥P0(∣ZK∣≥z1−α/2)=α(z_{1-\alpha/2}) \ge P_0(|Z_K| \ge z_{1-\alpha/2}) = \alpha and, by the union bound, CROSS(z1−α/(2K))≤∑kP0(∣Zk∣≥z1−α/(2K))=α(z_{1-\alpha/(2K)}) \le \sum_k P_0(|Z_k| \ge z_{1-\alpha/(2K)}) = \alpha, since ck≥Cc_k \ge C for all kk.
  4. Bisection. By 2 and 3 there is exactly one root in [lo,hi][lo, hi], and each step of lines L3 and L4 keeps it inside. After BB steps the interval has width (hi−lo)/2B(hi - lo)/2^B.

The only approximation is the quadrature in lines L10 and L11; its error is O(h4)O(h^4) in the grid spacing hh for the smooth parts of the integrands.

Proof: CROSS computes the crossing probability, and bisection finds the unique O'Brien-Fleming constantfull

Notation is that of the page. Under H0H_0, S0=0S_0 = 0 and the increments Sk−Sk−1S_k - S_{k-1}, k=1,…,Kk = 1, \ldots, K, are independent with distribution N(0,Δk)N(0, \Delta_k), where Δk=Ik−Ik−1>0\Delta_k = I_k - I_{k-1} > 0 and I0=0I_0 = 0. For C>0C > 0 let b=CIKb = C\sqrt{I_K}. The O'Brien-Fleming test with constant CC rejects at the first kk with ∣Sk∣≥b|S_k| \ge b, which is the same as ∣Zk∣≥CIK/Ik|Z_k| \ge C\sqrt{I_K/I_k} since Zk=Sk/IkZ_k = S_k/\sqrt{I_k}. Let

Q(C)=P0(∣Sk∣≥b for some k≤K).Q(C) = P_0\bigl(|S_k| \ge b \text{ for some } k \le K\bigr).

We prove that CROSS(C)(C) equals Q(C)Q(C) when the integrals are exact, and that lines L1 to L5 converge to the unique solution of Q(C)=αQ(C) = \alpha. Write φv\varphi_v for the N(0,v)N(0, v) density and Ek={∣Sj∣<b for all j≤k}E_k = \{|S_j| < b \text{ for all } j \le k\}, with E0E_0 the sure event.

Lemma 1 (the sub-densities). For k=1,…,Kk = 1, \ldots, K and every Borel set A⊆(−b,b)A \subseteq (-b, b),

P0(Ek−1∩{Sk∈A})=∫Ahk(s) ds,P_0(E_{k-1} \cap \{S_k \in A\}) = \int_A h_k(s)\,ds,

where h1=φI1h_1 = \varphi_{I_1} and, for k≥2k \ge 2, hk(s)=∫−bbhk−1(u)1{∣u∣<b}φΔk(s−u) duh_k(s) = \int_{-b}^{b} h_{k-1}(u)\mathbf 1\{|u| < b\}\varphi_{\Delta_k}(s - u)\,du. The same formula holds for every Borel A⊆RA \subseteq \mathbb R.

Proof. By induction on kk. For k=1k = 1, E0E_0 is sure and S1∼N(0,I1)=N(0,Δ1)S_1 \sim N(0, I_1) = N(0, \Delta_1). For k≥2k \ge 2, Ek−1=Ek−2∩{∣Sk−1∣<b}E_{k-1} = E_{k-2} \cap \{|S_{k-1}| < b\}, and the increment D=Sk−Sk−1D = S_k - S_{k-1} is independent of (S1,…,Sk−1)(S_1, \ldots, S_{k-1}). By the induction hypothesis the restriction of the law of Sk−1S_{k-1} to Ek−2E_{k-2} has density hk−1h_{k-1}. Conditioning on Sk−1S_{k-1} and using the independence of DD,

P0(Ek−1∩{Sk∈A})=∫−bbhk−1(u) P(u+D∈A) du=∫−bbhk−1(u)∫AφΔk(s−u) ds du.P_0(E_{k-1} \cap \{S_k \in A\}) = \int_{-b}^{b} h_{k-1}(u)\,P(u + D \in A)\,du = \int_{-b}^{b} h_{k-1}(u)\int_A \varphi_{\Delta_k}(s - u)\,ds\,du.

Tonelli's theorem exchanges the integrals, which gives ∫Ahk(s) ds\int_A h_k(s)\,ds. □\square

Lemma 2 (CROSS is the crossing probability). If the integrals of lines L10 and L11 are evaluated exactly, then after the iteration of line L8 for kk, p=P0(Ekc)p = P_0(E_k^c) and g=hk+1g = h_{k+1} restricted to (−b,b)(-b, b). In particular line L12 returns Q(C)=P0(EKc)Q(C) = P_0(E_K^c).

Proof. The first crossing happens at exactly one kk, so P0(Ekc)=∑j≤kP0(Ej−1∩{∣Sj∣≥b})P_0(E_k^c) = \sum_{j \le k} P_0(E_{j-1} \cap \{|S_j| \ge b\}). Line L7 sets p=P0(∣S1∣≥b)=2Φˉ(b/I1)p = P_0(|S_1| \ge b) = 2\bar\Phi(b/\sqrt{I_1}) and g=h1g = h_1 on [−b,b][-b, b]. At step k≥2k \ge 2, Lemma 1 with A={∣s∣≥b}A = \{|s| \ge b\} gives

P0(Ek−1∩{∣Sk∣≥b})=∫−bbg(u) P(∣u+D∣≥b) du=∫−bbg(u)[Φ(−b−uσ)+Φˉ(b−uσ)]du,P_0(E_{k-1} \cap \{|S_k| \ge b\}) = \int_{-b}^{b} g(u)\,P(|u + D| \ge b)\,du = \int_{-b}^{b} g(u)\left[\Phi\left(\frac{-b - u}{\sigma}\right) + \bar\Phi\left(\frac{b - u}{\sigma}\right)\right]du,

with σ=Δk\sigma = \sqrt{\Delta_k}, which is the term that line L10 adds. Line L11 computes hk+1h_{k+1} from g=hkg = h_k by the formula of Lemma 1. Induction on kk completes the proof. □\square

Lemma 3 (monotone and continuous). QQ is continuous and strictly decreasing on (0,∞)(0, \infty).

Proof. Let 0<C<C′0 < C < C', with b=CIKb = C\sqrt{I_K} and b′=C′IKb' = C'\sqrt{I_K}. Every path with some ∣Sk∣≥b′|S_k| \ge b' has ∣Sk∣≥b|S_k| \ge b, so Q(C′)≤Q(C)Q(C') \le Q(C). The difference Q(C)−Q(C′)Q(C) - Q(C') is at least the probability of the event {∣Sj∣<b for j<K}∩{b≤∣SK∣<b′}\{|S_j| < b \text{ for } j < K\} \cap \{b \le |S_K| < b'\}. By Lemma 1 with the bound bb, this probability is ∫b≤∣s∣<b′hK(s) ds\int_{b \le |s| < b'} h_K(s)\,ds, and hK>0h_K > 0 everywhere because it is a convolution of a positive function on (−b,b)(-b, b) with a normal density (for K=1K = 1, h1h_1 is a normal density). So the difference is positive. For continuity, the events {max⁡k∣Sk∣≥CIK}\{\max_k |S_k| \ge C\sqrt{I_K}\} change with CC only through the event {max⁡k∣Sk∣=CIK}\{\max_k |S_k| = C\sqrt{I_K}\}, which has probability at most ∑kP(∣Sk∣=CIK)=0\sum_k P(|S_k| = C\sqrt{I_K}) = 0. By continuity of probability along monotone sequences of events, QQ is continuous from both sides. □\square

Lemma 4 (the bracket). With lo=z1−α/2lo = z_{1-\alpha/2} and hi=z1−α/(2K)hi = z_{1-\alpha/(2K)}, Q(lo)≥α≥Q(hi)Q(lo) \ge \alpha \ge Q(hi).

Proof. The event of crossing contains {∣SK∣≥loIK}={∣ZK∣≥z1−α/2}\{|S_K| \ge lo\sqrt{I_K}\} = \{|Z_K| \ge z_{1-\alpha/2}\}, which has probability α\alpha. For hihi, the critical values hiIK/Ikhi\sqrt{I_K/I_k} are all at least hihi, so by the union bound Q(hi)≤∑k=1KP0(∣Zk∣≥hi)=K⋅α/K=αQ(hi) \le \sum_{k=1}^K P_0(|Z_k| \ge hi) = K \cdot \alpha/K = \alpha. □\square

Theorem. If CROSS is evaluated exactly, there is exactly one C∗∈[lo,hi]C^* \in [lo, hi] with Q(C∗)=αQ(C^*) = \alpha, and after every iteration of lines L2 to L4 it holds that lo≤C∗≤hilo \le C^* \le hi. The loop stops after ⌈log⁡2((hi−lo)/tol)⌉\lceil\log_2((hi - lo)/\mathrm{tol})\rceil iterations, and line L5 returns a value within tol\mathrm{tol} of C∗C^*, together with the boundary ck=CIK/Ikc_k = C\sqrt{I_K/I_k}.

Proof. Existence follows from Lemmas 3 and 4 and the intermediate value theorem; uniqueness from strict monotonicity. Line L1 establishes lo≤C∗≤hilo \le C^* \le hi by Lemma 4. At line L4, if Q(C)>α=Q(C∗)Q(C) > \alpha = Q(C^*) then C<C∗C < C^* by Lemma 3, so setting lo=Clo = C keeps C∗C^* in the interval; otherwise Q(C)≤Q(C∗)Q(C) \le Q(C^*) and C≥C∗C \ge C^*, so setting hi=Chi = C keeps it. Each iteration halves hi−lohi - lo. Line L5 returns a point of the final interval, of width at most tol, which contains C∗C^*. By Lemma 2, CROSS(C)=Q(C)(C) = Q(C). ■\blacksquare

Quadrature. In the implementation the integrals of lines L10 and L11 are computed by Simpson's rule on [−b,b][-b, b]. The integrands are smooth on this closed interval, so each step has error O(h4)O(h^4) in the grid spacing hh; the computed CROSS is then a close approximation of QQ, and the bisection finds the root of the approximation.

Complexity

One evaluation of CROSS on mm grid points per analysis costs O(m2)O(m^2) for the convolution of line L11 and O(m)O(m) for line L10, so O(Km2)O(Km^2) in all. With grid spacing σ/r\sigma/r and b=CIKb = C\sqrt{I_K}, m=O(r CIK/(Ik−Ik−1))m = O(r\,C\sqrt{I_K/(I_k - I_{k-1})}), which is O(rK)O(r\sqrt K) for equally spaced analyses. Bisection to width ε\varepsilon needs B=⌈log⁡2((hi−lo)/ε)⌉B = \lceil \log_2((hi - lo)/\varepsilon) \rceil evaluations, so the total time is O(BKm2)O(BKm^2) and the extra space is O(m)O(m) for two grids. For K=5K = 5, r=16r = 16 and ε=10−9\varepsilon = 10^{-9}, this is about 30 evaluations of a few thousand grid operations each.

Properties

  • Flat on the score scale. The rule is ∣Sk∣≥CIK|S_k| \ge C\sqrt{I_K}: the same bound on the sum at every analysis. This is why it spends so little error early, when the variance of SkS_k is small.
  • Last critical value near z1−α/2z_{1-\alpha/2}. CC grows slowly with KK, from 1.960 to 2.040 for K=5K = 5. So the final analysis loses little power against the fixed-sample test.
  • Small inflation. The maximum information is only 2.7% above the fixed-sample one for K=5K = 5 and 90% power.
  • Dependence on the information levels. CC depends on the ratios Ik/IKI_k/I_K. If the analyses do not occur at the planned levels, the boundary must be recomputed, or the alpha spending function approach used instead.
  • A trade-off, not an optimum. Pocock's shape gives a smaller expected sample size when the effect is as large as planned. The O'Brien-Fleming shape gives a smaller maximum, and a smaller expected sample size when there is no effect.

Variants and improvements

Pocock boundary. Pocock (1977) uses the same critical value ck=CPc_k = C_P at every analysis. For K=5K = 5 and α=0.05\alpha = 0.05, CP=2.4132C_P = 2.4132. Compared with the O'Brien-Fleming boundary:

K=5K = 5, α=0.05\alpha = 0.05, power 90% O'Brien-Fleming Pocock
critical values 4.562, 3.226, 2.634, 2.281, 2.040 2.413 at every analysis
P0P_0 of first crossing at analyses 1 to 5 0.00001, 0.00125, 0.00764, 0.01668, 0.02442 0.01581, 0.01171, 0.00902, 0.00731, 0.00615
inflation factor RR 1.0265 1.2065
expected information, θ=δ\theta = \delta 0.750 0.685
expected information, θ=δ/2\theta = \delta/2 0.961 1.052
expected information, θ=0\theta = 0 1.019 1.177

The Pocock design stops sooner when the effect is as planned, but its maximum sample size is 21% larger, and a trial that reaches the last analysis needs ∣Z5∣≥2.413|Z_5| \ge 2.413, a nominal p-value of 0.016. The same bisection computes it, with ck=Cc_k = C and the general crossing routine.

Other variants:

  • Wang-Tsiatis family. ck=C(Ik/IK)Δ−1/2c_k = C(I_k/I_K)^{\Delta - 1/2} with 0≤Δ≤1/20 \le \Delta \le 1/2. Δ=0\Delta = 0 is O'Brien-Fleming and Δ=1/2\Delta = 1/2 is Pocock. Wang and Tsiatis (1987) searched this family for boundaries with a small expected sample size.
  • Spending-function version. Lan and DeMets (1983) give the spending function 2−2Φ(z1−α/2/t)2 - 2\Phi(z_{1-\alpha/2}/\sqrt t), which produces boundaries close to O'Brien-Fleming for any times of analysis; see alpha spending function.
  • One-sided boundary and futility. For a one-sided test, line L7 and line L10 count only the upper crossing, and an inner futility boundary can be added; the recursion is the same with a different integration range.
  • Haybittle-Peto rule. A fixed critical value of 3 at the interim analyses and the fixed-sample value at the end. It resembles O'Brien-Fleming but does not keep the level exactly.

When to use it

Use the O'Brien-Fleming boundary for the efficacy analysis of a confirmatory trial with a few planned interim analyses, where early stopping should need overwhelming evidence and the final analysis should be almost unchanged. Use the Pocock boundary when early stopping for a large effect is the main goal and the larger maximum is acceptable. Use the alpha spending function when the times of the analyses are uncertain, and a fully sequential method such as the SPRT when the data are analysed after every observation.

Pitfalls

  • Using 1.96 at the end. The final critical value is CC, not z1−α/2z_{1-\alpha/2}. A result with 1.96≤∣ZK∣<2.0401.96 \le |Z_K| < 2.040 does not reject for K=5K = 5.
  • Analyses at unplanned times. The constant CC depends on the information ratios. Recompute it for the actual times, or use a spending function from the start.
  • Too coarse a quadrature. With few grid points the recursion error can exceed the target accuracy of CC, mostly at early analyses where the sub-density is narrow. Choose the spacing relative to Ik−Ik−1\sqrt{I_k - I_{k-1}}, as the implementation does.
  • Normal approximation at the first analysis. The first critical value 4.56 sits far in the tail, where large-sample approximations for binary or survival data are least accurate.
  • Bias after early stopping. The estimate at an early stop is biased away from 0; report a repeated confidence interval or an adjusted estimate.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

obrien_fleming_boundary.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/obrien-fleming-boundary/. The authors are listed in prov/C11SHN.jsonl.
"""O'Brien-Fleming and Pocock group sequential boundaries.

The statistics Z_1, ..., Z_K follow the canonical joint distribution: the score
S_k = Z_k sqrt(I_k) is a Brownian motion with drift theta observed at the
information levels I_1 < ... < I_K. A two-sided boundary c_1, ..., c_K rejects
H_0 at the first k with |Z_k| >= c_k.

The crossing probabilities are computed by recursive numerical integration
(Armitage, McPherson and Rowe 1969): the sub-density of S_k on the event that
no earlier boundary was crossed is carried from stage to stage on a Simpson
grid. The grid spacing is at most sqrt(I_k - I_(k-1)) / r, so the work of one
evaluation is O(K m^2) for m grid points per stage.
"""

import math
from collections.abc import Callable, Sequence

_SQRT2 = math.sqrt(2.0)
_INV_SQRT_2PI = 1.0 / math.sqrt(2.0 * math.pi)


def _norm_cdf(x: float) -> float:
    return 0.5 * math.erfc(-x / _SQRT2)


def _norm_sf(x: float) -> float:
    return 0.5 * math.erfc(x / _SQRT2)


def _norm_pdf(x: float) -> float:
    return _INV_SQRT_2PI * math.exp(-0.5 * x * x)


def norm_quantile(p: float) -> float:
    """The lower p-quantile of the standard normal, by bisection on erfc to 1e-15."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    lo, hi = -40.0, 40.0
    for _ in range(200):
        mid = 0.5 * (lo + hi)
        if _norm_cdf(mid) < p:
            lo = mid
        else:
            hi = mid
        if hi - lo < 1e-15:
            break
    return 0.5 * (lo + hi)


def _simpson_grid(b: float, step: float) -> tuple[list[float], list[float]]:
    """Points and Simpson weights on [-b, b] with an even number of intervals of length <= step."""
    n = max(2, 2 * math.ceil(b / step))
    h = 2.0 * b / n
    xs = [-b + i * h for i in range(n + 1)]
    ws = [(1.0 if i in (0, n) else (4.0 if i % 2 else 2.0)) * h / 3.0 for i in range(n + 1)]
    return xs, ws


def crossing_probabilities(c: Sequence[float], info: Sequence[float], theta: float = 0.0,
                           r: int = 16) -> list[tuple[float, float]]:
    """Per-stage crossing probabilities of the two-sided boundary c on the z scale.

    Returns a list of pairs (upper_k, lower_k): the probabilities of stopping at
    analysis k with Z_k >= c_k or with Z_k <= -c_k, with no earlier crossing,
    when the score has drift theta per unit of information. Precondition:
    0 < info[0] < info[1] < ..., c_k > 0. Cost O(K m^2) with m about
    2 b_k r / sqrt(I_k - I_(k-1)) grid points at stage k.
    """
    if len(c) != len(info) or not c:
        raise ValueError("c and info must have the same positive length")
    out = []
    b = c[0] * math.sqrt(info[0])
    sd = math.sqrt(info[0])
    mu = theta * info[0]
    out.append((_norm_sf((b - mu) / sd), _norm_cdf((-b - mu) / sd)))
    xs, ws = _simpson_grid(b, sd / r)
    g = [_norm_pdf((x - mu) / sd) / sd for x in xs]
    for k in range(1, len(c)):
        delta = info[k] - info[k - 1]
        if delta <= 0:
            raise ValueError("information levels must increase")
        sd = math.sqrt(delta)
        mu = theta * delta
        b = c[k] * math.sqrt(info[k])
        up = sum(w * gu * _norm_sf((b - u - mu) / sd) for u, w, gu in zip(xs, ws, g))
        lo = sum(w * gu * _norm_cdf((-b - u - mu) / sd) for u, w, gu in zip(xs, ws, g))
        out.append((up, lo))
        if k + 1 < len(c):
            nxs, nws = _simpson_grid(b, min(sd, math.sqrt(info[k + 1] - info[k])) / r)
            wg = [w * gu for w, gu in zip(ws, g)]
            g = [sum(a * _norm_pdf((s - u - mu) / sd) for u, a in zip(xs, wg)) / sd for s in nxs]
            xs, ws = nxs, nws
    return out


def total_crossing(c: Sequence[float], info: Sequence[float], theta: float = 0.0, r: int = 16) -> float:
    """P(|Z_k| >= c_k for some k) under drift theta (two-sided rejection probability)."""
    return sum(u + l for u, l in crossing_probabilities(c, info, theta, r))


def _shape(kind: str, info: Sequence[float]) -> list[float]:
    if kind == "obrien-fleming":
        return [math.sqrt(info[-1] / i) for i in info]
    if kind == "pocock":
        return [1.0 for _ in info]
    raise ValueError("kind must be 'obrien-fleming' or 'pocock'")


def boundary_constant(kind: str, k_looks: int, alpha: float = 0.05, info: Sequence[float] | None = None,
                      tol: float = 1e-9, r: int = 16,
                      cross: Callable[..., float] | None = None) -> tuple[float, list[float]]:
    """The constant C and the z-scale boundary c_k = C shape_k at two-sided level alpha.

    kind is "obrien-fleming" (c_k = C sqrt(I_K / I_k)) or "pocock" (c_k = C).
    info defaults to equal spacing 1, 2, ..., K. Bisection on C to width tol;
    each step costs one evaluation of total_crossing.
    """
    if info is None:
        info = [float(i) for i in range(1, k_looks + 1)]
    if len(info) != k_looks or k_looks < 1:
        raise ValueError("info must have k_looks entries")
    if not 0.0 < alpha < 1.0:
        raise ValueError("alpha must be in (0, 1)")
    cross = cross or total_crossing
    shape = _shape(kind, info)
    lo = norm_quantile(1.0 - alpha / 2.0)  # @line L1
    hi = norm_quantile(1.0 - alpha / (2.0 * k_looks))  # @line L1
    while hi - lo > tol:  # @line L2
        mid = 0.5 * (lo + hi)  # @line L3
        if cross([mid * s for s in shape], info, 0.0, r) > alpha:  # @line L4
            lo = mid
        else:
            hi = mid
    big_c = 0.5 * (lo + hi)
    return big_c, [big_c * s for s in shape]  # @line L5


def obrien_fleming_boundary(k_looks: int, alpha: float = 0.05, info: Sequence[float] | None = None,
                            tol: float = 1e-9, r: int = 16) -> tuple[float, list[float]]:
    """O'Brien-Fleming: c_k = C sqrt(I_K / I_k), two-sided level alpha.

    Returns (C, [c_1, ..., c_K]). For K = 5 equally spaced looks and
    alpha = 0.05, C is about 2.0401.
    """
    return boundary_constant("obrien-fleming", k_looks, alpha, info, tol, r)


def pocock_boundary(k_looks: int, alpha: float = 0.05, info: Sequence[float] | None = None,
                    tol: float = 1e-9, r: int = 16) -> tuple[float, list[float]]:
    """Pocock: c_k = C at every look, two-sided level alpha."""
    return boundary_constant("pocock", k_looks, alpha, info, tol, r)


def cross_on_score_scale(big_c: float, info: Sequence[float], r: int = 16) -> float:
    """CROSS(C, I) of the pseudocode: the O'Brien-Fleming boundary is |S_k| >= C sqrt(I_K)."""
    b = big_c * math.sqrt(info[-1])  # @line L6
    sd = math.sqrt(info[0])
    p = 2.0 * _norm_sf(b / sd)  # @line L7
    xs, ws = _simpson_grid(b, sd / r)
    g = [_norm_pdf(x / sd) / sd for x in xs]  # @line L7
    for k in range(1, len(info)):  # @line L8
        sd = math.sqrt(info[k] - info[k - 1])  # @line L9
        p += sum(w * gu * (_norm_cdf((-b - u) / sd) + _norm_sf((b - u) / sd))  # @line L10
                 for u, w, gu in zip(xs, ws, g))
        if k + 1 < len(info):
            nxs, nws = _simpson_grid(b, min(sd, math.sqrt(info[k + 1] - info[k])) / r)
            wg = [w * gu for w, gu in zip(ws, g)]
            g = [sum(a * _norm_pdf((s - u) / sd) for u, a in zip(xs, wg)) / sd for s in nxs]  # @line L11
            xs, ws = nxs, nws
    return p  # @line L12


def expected_information(c: Sequence[float], info: Sequence[float], theta: float = 0.0, r: int = 16) -> float:
    """E[I_T], the expected information at stopping, where T is the stage of stopping (K if no crossing)."""
    probs = crossing_probabilities(c, info, theta, r)
    stop = [u + l for u, l in probs]
    return sum(p * i for p, i in zip(stop[:-1], info[:-1])) + (1.0 - sum(stop[:-1])) * info[-1]
test_obrien_fleming_boundary.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/obrien-fleming-boundary/. The authors are listed in prov/C11SHN.jsonl.
import math
import random

import pytest

from obrien_fleming_boundary import (
    boundary_constant,
    cross_on_score_scale,
    crossing_probabilities,
    expected_information,
    norm_quantile,
    obrien_fleming_boundary,
    pocock_boundary,
    total_crossing,
)


def phi(x: float) -> float:
    return math.exp(-0.5 * x * x) / math.sqrt(2.0 * math.pi)


def upper(x: float) -> float:
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def two_look_quadrature(c1: float, c2: float, t1: float, n: int = 400) -> float:
    """P(|Z1| >= c1 or (|Z1| < c1 and |Z2| >= c2)) with Z2 | Z1 = z ~ N(sqrt(t1) z, 1 - t1).

    One-dimensional composite Simpson rule on the z scale: an oracle that does
    not share the score-scale recursion of the code under test.
    """
    s, v = math.sqrt(t1), math.sqrt(1.0 - t1)
    h = 2.0 * c1 / n
    acc = 0.0
    for i in range(n + 1):
        z = -c1 + i * h
        w = 1.0 if i in (0, n) else (4.0 if i % 2 else 2.0)
        acc += w * phi(z) * (upper((c2 - s * z) / v) + upper((c2 + s * z) / v))
    return 2.0 * upper(c1) + acc * h / 3.0


def test_one_look_is_the_fixed_sample_test():
    c, bounds = obrien_fleming_boundary(1)
    assert abs(c - 1.959964) < 1e-6
    assert bounds == [c]
    p, _ = pocock_boundary(1)
    assert abs(p - c) < 1e-9


def test_worked_example_five_looks():
    c, bounds = obrien_fleming_boundary(5)
    assert abs(c - 2.0401) < 1e-4
    expected = [4.5617, 3.2256, 2.6337, 2.2809, 2.0401]
    assert all(abs(a - b) < 1e-4 for a, b in zip(bounds, expected))
    p, pb = pocock_boundary(5)
    assert abs(p - 2.4132) < 1e-4
    assert all(abs(x - p) < 1e-12 for x in pb)


@pytest.mark.parametrize("k", [2, 3, 4, 5])
def test_total_level_is_alpha(k):
    for kind in ("obrien-fleming", "pocock"):
        _, bounds = boundary_constant(kind, k)
        assert abs(total_crossing(bounds, list(range(1, k + 1))) - 0.05) < 1e-6


def test_grid_doubling_converges():
    info = [1.0, 2.0, 3.0, 4.0, 5.0]
    p8, p16, p32 = (cross_on_score_scale(2.0401, info, r=r) for r in (8, 16, 32))
    assert abs(p16 - p32) < 1e-8
    assert abs(p8 - p32) < 1e-7


def test_score_scale_cross_matches_z_scale():
    info = [1.0, 2.0, 3.0, 4.0, 5.0]
    for c in (1.8, 2.04, 2.3):
        z_bounds = [c * math.sqrt(5.0 / i) for i in info]
        assert abs(cross_on_score_scale(c, info) - total_crossing(z_bounds, info)) < 1e-12


def test_crossing_decreases_in_c():
    info = [1.0, 2.0, 3.0]
    values = [cross_on_score_scale(c, info) for c in (1.5, 1.8, 2.0, 2.2, 2.5)]
    assert all(a > b for a, b in zip(values, values[1:]))


def test_two_looks_against_quadrature():
    for kind in ("obrien-fleming", "pocock"):
        _, (c1, c2) = boundary_constant(kind, 2)
        assert abs(two_look_quadrature(c1, c2, 0.5) - 0.05) < 1e-7


def test_random_two_look_boundaries_against_quadrature():
    rng = random.Random(20260314)
    for _ in range(500):
        t1 = rng.uniform(0.1, 0.9)
        c1 = rng.uniform(1.0, 4.0)
        c2 = rng.uniform(1.0, 4.0)
        got = total_crossing([c1, c2], [t1, 1.0])
        # Both sides use Simpson grids; their discretization errors stay below 5e-7.
        assert abs(got - two_look_quadrature(c1, c2, t1)) < 5e-7


def test_monte_carlo_level_and_stage_split():
    rng = random.Random(7)
    _, bounds = obrien_fleming_boundary(5)
    reps = 20000
    hits = 0
    for _ in range(reps):
        s = 0.0
        for k in range(1, 6):
            s += rng.gauss(0.0, 1.0)
            if abs(s / math.sqrt(k)) >= bounds[k - 1]:
                hits += 1
                break
    se = math.sqrt(0.05 * 0.95 / reps)
    assert abs(hits / reps - 0.05) < 4 * se


def test_unequal_information_and_drift():
    info = [0.3, 0.7, 1.0]
    c, bounds = obrien_fleming_boundary(3, info=info)
    assert abs(total_crossing(bounds, info) - 0.05) < 1e-6
    # Under drift the rejection probability rises, and early stops cut the expected information.
    assert total_crossing(bounds, [i * 10 for i in info], theta=1.0) > 0.5
    assert expected_information(bounds, [i * 10 for i in info], theta=1.0) < 10.0
    parts = crossing_probabilities(bounds, info)
    assert all(abs(u - l) < 1e-12 for u, l in parts)


def test_inflation_factor_five_looks():
    fixed = (norm_quantile(0.975) + norm_quantile(0.9)) ** 2
    for kind, want in (("obrien-fleming", 1.0265), ("pocock", 1.2065)):
        _, bounds = boundary_constant(kind, 5)

        def power(imax: float) -> float:
            return total_crossing(bounds, [k / 5 * imax for k in range(1, 6)], theta=1.0)

        lo, hi = fixed, 2 * fixed
        for _ in range(40):
            mid = 0.5 * (lo + hi)
            lo, hi = (mid, hi) if power(mid) < 0.9 else (lo, mid)
        assert abs(lo / fixed - want) < 1e-3


def test_bad_input():
    with pytest.raises(ValueError):
        obrien_fleming_boundary(3, info=[1.0, 2.0])
    with pytest.raises(ValueError):
        total_crossing([2.0, 2.0], [1.0, 1.0])
    with pytest.raises(ValueError):
        boundary_constant("haybittle", 3)

History

Armitage, McPherson and Rowe (1969) showed how much repeated significance tests inflate the type I error and computed the inflation by recursive numerical integration. Pocock (1977) turned this into practical group sequential designs with a constant critical value. O'Brien and Fleming (1979) proposed critical values proportional to K/k\sqrt{K/k}, so that early stopping needs very strong evidence; this shape became the standard for efficacy monitoring. Lan and DeMets (1983) gave the spending function that approximates it at analysis times not fixed in advance, and Wang and Tsiatis (1987) placed both boundaries in a one-parameter family.

References

  1. Peter C. O'Brien and Thomas R. Fleming, A multiple testing procedure for clinical trials, Biometrics 35(3) (1979), pages 549 to 556, the definition of the boundary, with critical values proportional to the square root of K/k
  2. Stuart J. Pocock, Group sequential methods in the design and analysis of clinical trials, Biometrika 64(2) (1977), pages 191 to 199, the constant boundary and its table of critical values for equally spaced analyses
  3. P. Armitage, C. K. McPherson and B. C. Rowe, Repeated significance tests on accumulating data, Journal of the Royal Statistical Society, Series A 132(2) (1969), the recursive numerical integration of the probability of crossing a boundary for sums of normal variables
  4. Samuel K. Wang and Anastasios A. Tsiatis, Approximately optimal one-parameter boundaries for group sequential trials, Biometrics 43(1) (1987), the family of boundaries proportional to (k/K) to the power Delta minus 1/2, which contains the O'Brien-Fleming and Pocock shapes
  5. Christopher Jennison and Bruce W. Turnbull, Group Sequential Methods with Applications to Clinical Trials, Chapman and Hall/CRC, 2000, Chapter 2 (the Pocock and O'Brien-Fleming tests, their constants and their inflation factors)
  6. K. K. Gordon Lan and David L. DeMets, Discrete sequential boundaries for clinical trials, Biometrika 70(3) (1983), pages 659 to 663, the spending function that approximates the O'Brien-Fleming boundary for analyses at times not fixed in advance

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example