Delivery Experiment Design: Sample Size and Error Control
Arrays & HashingAuto-graded · 2 test casesLast updated
Tests ability to calculate sample sizes for superiority and non-inferiority tests, apply multiple-testing corrections, adjust for clustering, and explain sequential monitoring.
You are designing a two-arm randomized experiment to evaluate a new delivery routing feature. The control arm uses the existing system, and the treatment arm uses the new feature. Calculate the required sample sizes and describe error-control strategies under the following conditions.
Part 1: Main Metric (Delivery Duration)
The current average delivery duration is 42 minutes with a standard deviation of 15 minutes. You want to detect a 5% relative reduction (2.1 minutes absolute improvement). Use a two-sided significance level of 0.05 and power of 0.80.
Calculate the required sample size per arm for a two-sample t-test comparing means.
Part 2: Safety Metric (Cancellation Rate)
The baseline cancellation rate is 6%. You need to ensure the new feature does not increase cancellations by more than 0.5 percentage points (non-inferiority margin). Use a one-sided significance level of 0.05 and power of 0.80.
Calculate the required sample size per arm for a one-sided non-inferiority test on proportions.
Part 3: Multiple Hypothesis Testing
Your experiment tracks:
- 1 primary metric (delivery duration)
- 2 guardrail metrics (cancellation rate, estimated time accuracy)
- 1 secondary metric (deliveries per courier-hour)
Describe an error-control strategy that accounts for testing multiple hypotheses. Specify the effective significance level for each metric family and explain how you would construct confidence intervals.
Part 4: Clustered Randomization
Randomization occurs at the zone-day level (all deliveries in a zone on a given day receive the same treatment). Each zone-day contains an average of 300 deliveries, and the intracluster correlation coefficient (ICC) is 0.03 for the primary metric.
Calculate the design effect, the adjusted sample size per arm, and the number of zone-days needed per arm.
Part 5: Sequential Testing
You plan to conduct 4 interim analyses at equally spaced intervals using the O'Brien-Fleming alpha spending function.
Explain how the critical values at early looks compare to the final analysis, describe the impact on experiment duration and minimum detectable effect, and outline how you would implement boundary checks in practice.
Output Format
Return a dictionary with five keys: "primary_mean", "cancellation_noninferiority", "error_control", "cluster_randomization", and "sequential_monitoring".
Each key should map to a nested dictionary containing the calculated values and explanations as shown in the sample output structure.
Constraints
- Use normal approximations for sample size calculations
- Round sample sizes up to the nearest integer
- Use z = 1.96 for two-sided alpha = 0.05
- Use z = 1.645 for one-sided alpha = 0.05
- Use z = 0.842 for power = 0.80
- Assume equal allocation between arms
- For the proportion test, use conservative variance under the null hypothesis
Examples
Example 1
Input: calculate_experiment_design()
Output: {'primary_mean': {'formula': 'n_per_arm = 2 * (z_(1-alpha/2) + z_(power))^2 * sigma^2 / delta^2', 'delta_minutes': 2.1, 'z_alpha': 1.959963984540054, 'z_power': 0.8416212335729143, 'sample_size_per_arm': 801, 'note': 'Normal-approximation sample size for a two-sample t-test; rounding up.'}, 'cancellation_noninferiority': {'formula': 'n_per_arm = 2 * (z_(1-alpha) + z_(power))^2 * p0*(1-p0) / margin^2', 'absolute_margin': 0.005, 'z_alpha': 1.6448536269514722, 'z_power': 0.8416212335729143, 'sample_size_per_arm': 27896, 'note': 'Conservative planning approximation using the null-boundary variance; test H0: p_biker - p_control >= 0.005 versus H1: difference < 0.005.'}, 'error_control': {'approach': 'Hierarchical gatekeeping with Holm control within the guardrail family', 'primary_family_alpha': 0.05, 'guardrails_family_alpha': 0.05, 'guardrail_holm_procedure': 'Sort the two guardrail p-values; compare the smaller with 0.025 and the larger with 0.05, stopping at the first non-rejection.', 'secondary_family_alpha': 0.05, 'gatekeeping': 'Test the secondary orders-per-courier-hour metric confirmatorily only after the primary succeeds and both guardrails pass; otherwise report it as exploratory.', 'confidence_intervals': 'Report two-sided 95% CI for the primary. For non-inferiority guardrails report one-sided 95% upper confidence bounds for Biker minus control against +0.5 percentage points; provide Holm-adjusted simultaneous intervals (equivalently, sequential Holm-compatible intervals) for the two guardrails. Label exploratory intervals unadjusted.'}, 'cluster_randomization': {'design_effect_formula': 'DE = 1 + (m - 1)*ICC', 'design_effect': 9.969999999999999, 'adjusted_orders_per_arm': 7986, 'zone_days_per_arm': 27, 'orders_provided_by_whole_clusters_per_arm': 8100, 'note': 'Multiply the individually randomized primary sample size by DE, then round cluster count up; this assumes equal cluster size and ignores small-cluster degrees-of-freedom corrections.'}, 'sequential_monitoring': {'looks': 4, 'spending': 'O\'Brien-Fleming alpha spending is very small at early information fractions, so early efficacy boundaries are much more extreme than the fixed-horizon boundary; the final boundary is close to the ordinary two-sided 0.05 boundary. This protects type-I error while allowing early stopping only for unusually strong evidence. The stricter early boundary generally increases expected runtime and can require more information to stop early; the planned maximum-horizon MDE is not inherently changed when the design is powered using the sequential critical value.', 'final_look_spending_approximation': 'At information fraction 1, cumulative two-sided alpha spent is 0.05 (approximately 0.025 per tail); with four discrete looks the actual final increment is less than 0.05 because some alpha was spent at prior looks. The final critical value is computed from the chosen O\'Brien-Fleming spending function and joint boundary calibration, not by assigning 0.05 anew.', 'implementation': 'Prespecify the four information fractions, spending function, test statistic, and boundary algorithm. At each scheduled look compute information fraction and standardized statistic, evaluate the corresponding calibrated efficacy/futility boundaries, and stop only according to those boundaries. Use a validated group-sequential package and retain the prespecified analysis population and missing-data rules.'}}
Hints
Hint 1
For the mean comparison, apply the standard two-sample formula with pooled variance and normal quantiles
Hint 2
Non-inferiority tests use a one-sided alternative; the margin shifts the null hypothesis boundary
Hint 3
Hierarchical testing preserves familywise error by testing secondary metrics only after primary success; guardrails can use intersection-union logic
Hint 4
The design effect multiplies the variance by 1 + (m-1)×ICC, which directly inflates the required sample size
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem applies fundamental statistical formulas for experiment design across five interconnected components. Each calculation builds on standard hypothesis testing theory adapted to practical constraints.
Part 1: Sample Size for Mean Comparison
We need to detect a 2.1-minute improvement (5% of 42 minutes) with 80% power at a two-sided 0.05 significance level. The two-sample t-test formula for equal group sizes is:
n = 2(z_{α/2} + z_β)² σ² / δ²
Where z_{α/2} = 1.96 (two-sided), z_β = 0.842 (power 0.80), σ = 15, and δ = 2.1.
Plugging in: n = 2(1.96 + 0.842)² × 225 / 4.41 ≈ 801 per arm.
This assumes independent observations, which Part 4 corrects for clustering.
Part 2: Non-Inferiority Test for Proportions
Non-inferiority tests whether the treatment rate stays within an acceptable margin above the control. The null hypothesis is H₀: p_treatment - p_control ≥ 0.005 (harm), and we reject it to conclude non-inferiority.
Using conservative null variance and a one-sided test:
n = 2(z_α + z_β)² p(1-p) / margin²
With z_α = 1.645, p = 0.06, and margin = 0.005: n = 2(1.645 + 0.842)² × 0.06 × 0.94 / 0.000025 ≈ 27,896 per arm.
This far exceeds the primary metric requirement, making cancellation the binding constraint.
Part 3: Multiple Testing Strategy
Use hierarchical gatekeeping to preserve power while controlling familywise error:
- Primary metric: Full α = 0.05 (two-sided). This is the gateway test.
- Guardrails: Each uses α = 0.05 (one-sided) in an intersection-union framework. Both must pass (logical AND), which inherently controls familywise error at 0.05 without adjustment. Apply Holm step-down within the guardrail family for tighter simultaneous intervals.
- Secondary metric: Test at α = 0.05 only if the primary succeeds and both guardrails pass (fixed-sequence testing).
Confidence intervals:
- Primary: standard 95% two-sided CI
- Guardrails: one-sided 95% upper bounds (equivalent to 90% two-sided)
- Secondary: 95% CI, labeled confirmatory only if the gate opened
This approach avoids the power loss of blanket Bonferroni correction while maintaining rigorous error control through logical structure.
Part 4: Cluster Randomization Adjustment
When randomizing at the zone-day level, deliveries within a cluster share common conditions and are correlated. The design effect inflates variance:
DE = 1 + (m - 1)ρ = 1 + 299 × 0.03 = 9.97
Multiply the individual-level sample size by DE: n_adjusted = 801 × 9.97 ≈ 7,986 per arm
Clusters needed: 7,986 / 300 = 27 zone-days per arm (54 total).
In practice, add a few extra clusters to account for unequal cluster sizes and finite-sample degrees-of-freedom corrections.
Part 5: Sequential Monitoring with O'Brien-Fleming
O'Brien-Fleming spending allocates minimal alpha to early looks, making early stopping boundaries extremely stringent (z ≈ 4.0 at the first look) while preserving most alpha for the final analysis (final critical value ≈ 2.02 vs. 1.96 fixed).
Key properties:
- Early boundaries scale as z_final × √(K/k), where K is total looks and k is current look
- Cumulative alpha spent follows α(t) = 2 - 2Φ(z_{0.975}/√t)
- Maximum sample size inflates only ~2% compared to fixed design
- Expected duration increases under the null but decreases under large true effects
Implementation:
- Pre-register the number of looks, spending function, and analysis plan
- Define information fractions by accumulated data, not calendar time
- At each look, compute the standardized test statistic
- Stop for efficacy only if |z| exceeds the calibrated boundary for that look
- Report bias-adjusted estimates after early stopping
This approach balances the opportunity for early stopping with strict type I error control.
Complexity
- Time: O(1) — all calculations are closed-form formulas
- Space: O(1) — fixed-size output dictionary
Solution Code
from math import ceil, sqrt
from typing import Dict
def calculate_experiment_design():
# Standard normal quantiles for power and significance calculations
z_two_sided = 1.959963984540054 # two-sided alpha = 0.05
z_one_sided = 1.6448536269514722 # one-sided alpha = 0.05
z_beta = 0.8416212335729143 # power = 0.80
# Part 1: Primary metric (delivery duration)
mu_baseline = 42.0
sigma = 15.0
effect_size = mu_baseline * 0.05 # 5% relative improvement = 2.1 minutes
# Two-sample t-test formula: n = 2(z_alpha + z_beta)^2 * sigma^2 / delta^2
n_primary = ceil(2 * (z_two_sided + z_beta) ** 2 * sigma ** 2 / effect_size ** 2)
# Part 2: Cancellation non-inferiority
p_baseline = 0.06
ni_margin = 0.005 # 0.5 percentage points
# One-sided test: n = 2(z_alpha + z_beta)^2 * p(1-p) / margin^2
# Using conservative null variance
n_cancel = ceil(2 * (z_one_sided + z_beta) ** 2 * p_baseline * (1 - p_baseline) / ni_margin ** 2)
# Part 4: Cluster adjustment
cluster_size = 300
rho = 0.03
design_effect = 1 + (cluster_size - 1) * rho
n_adjusted = ceil(n_primary * design_effect)
n_clusters = ceil(n_adjusted / cluster_size)
return {
"primary_mean": {
"formula": "n_per_arm = 2 * (z_(1-alpha/2) + z_(power))^2 * sigma^2 / delta^2",
"delta_minutes": effect_size,
"z_alpha": z_two_sided,
"z_power": z_beta,
"sample_size_per_arm": n_primary,
"note": "Normal-approximation sample size for a two-sample t-test; rounding up."
},
"cancellation_noninferiority": {
"formula": "n_per_arm = 2 * (z_(1-alpha) + z_(power))^2 * p0*(1-p0) / margin^2",
"absolute_margin": ni_margin,
"z_alpha": z_one_sided,
"z_power": z_beta,
"sample_size_per_arm": n_cancel,
"note": "Conservative planning approximation using the null-boundary variance; test H0: p_biker - p_control >= 0.005 versus H1: difference < 0.005."
},
"error_control": {
"approach": "Hierarchical gatekeeping with Holm control within the guardrail family",
"primary_family_alpha": 0.05,
"guardrails_family_alpha": 0.05,
"guardrail_holm_procedure": "Sort the two guardrail p-values; compare the smaller with 0.025 and the larger with 0.05, stopping at the first non-rejection.",
"secondary_family_alpha": 0.05,
"gatekeeping": "Test the secondary orders-per-courier-hour metric confirmatorily only after the primary succeeds and both guardrails pass; otherwise report it as exploratory.",
"confidence_intervals": "Report two-sided 95% CI for the primary. For non-inferiority guardrails report one-sided 95% upper confidence bounds for Biker minus control against +0.5 percentage points; provide Holm-adjusted simultaneous intervals (equivalently, sequential Holm-compatible intervals) for the two guardrails. Label exploratory intervals unadjusted."
},
"cluster_randomization": {
"design_effect_formula": "DE = 1 + (m - 1)*ICC",
"design_effect": design_effect,
"adjusted_orders_per_arm": n_adjusted,
"zone_days_per_arm": n_clusters,
"orders_provided_by_whole_clusters_per_arm": n_clusters * cluster_size,
"note": "Multiply the individually randomized primary sample size by DE, then round cluster count up; this assumes equal cluster size and ignores small-cluster degrees-of-freedom corrections."
},
"sequential_monitoring": {
"looks": 4,
"spending": "O'Brien-Fleming alpha spending is very small at early information fractions, so early efficacy boundaries are much more extreme than the fixed-horizon boundary; the final boundary is close to the ordinary two-sided 0.05 boundary. This protects type-I error while allowing early stopping only for unusually strong evidence. The stricter early boundary generally increases expected runtime and can require more information to stop early; the planned maximum-horizon MDE is not inherently changed when the design is powered using the sequential critical value.",
"final_look_spending_approximation": "At information fraction 1, cumulative two-sided alpha spent is 0.05 (approximately 0.025 per tail); with four discrete looks the actual final increment is less than 0.05 because some alpha was spent at prior looks. The final critical value is computed from the chosen O'Brien-Fleming spending function and joint boundary calibration, not by assigning 0.05 anew.",
"implementation": "Prespecify the four information fractions, spending function, test statistic, and boundary algorithm. At each scheduled look compute information fraction and standardized statistic, evaluate the corresponding calibrated efficacy/futility boundaries, and stop only according to those boundaries. Use a validated group-sequential package and retain the prespecified analysis population and missing-data rules."
}
}