Design a clinical trial adaptive design simulation: rules, power, and bias.
- User
Design a clinical trial adaptive design simulation: rules, power, and bias.
Assistant
Design a clinical trial adaptive design simulation: rules, power, and bias.
1. Understand the User's Request: * Goal: Design a clinical trial adaptive design simulation. * Key Components: Rules (decision-making), Power (probability of success), and Bias (estimation errors). * Target Audience: Likely a statistician, clinical researcher, or data scientist working in biostatistics. The tone should be professional, technical yet accessible, and structured.
Deconstruct the Problem:
Step-by-Step Design:
Step 1: Define the Clinical Scenario (The "Truth"):
Step 2: Define the Adaptive Design Structure:
Step 3: The Simulation Logic (The Core):
Step 4: Address the "Rules" (Adaptation Logic):
Step 5: Address "Power":
Step 6: Address "Bias":
Drafting the Content (Iterative Refinement):
Refining the "Bias" Explanation:
Structuring the Output:
Self-Correction/Review during drafting:
Final Polish: Check variable names, ensure the distinction between "Naive" and "True" bias is clear, and format the code for readability. (The resulting output matches the detailed response provided previously.)
(Self-Correction during coding the Python script): I need to make sure the conditional_power function is correct.
... wait, that's getting complicated for a quick demo.
Use a simpler approximation or Fisher's combination? No, Inverse Normal is standard.
I will calculate Conditional Power using the standard formula based on the current trend () and projected remaining information. ... actually, let's stick to the most robust implementation:
. Using the observed effect as the predictor (conditional power for trend).
Let's stick to the plan:
This seems solid. Proceeding to generate response. This guide outlines the design of a simulation for a Two-Stage Adaptive Clinical Trial with Sample Size Re-estimation (SSR). This is the most common adaptive design where the sample size is modified based on interim results.
We will break this down into the Statistical Framework, Adaptation Rules, Simulation Code (Python), and Analysis of Power & Bias.
Objective: Compare an Experimental Drug () vs. Control (). Endpoint: Continuous (e.g., reduction in blood pressure). Assumptions:
The Adaptive Procedure:
We define "The Promising Zone" approach.
Conditional Power (): The probability of success at the end of the trial given the current data.
This script simulates the trial 10,000 times to estimate Power and Bias.
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
class AdaptiveTrialSimulation:
def __init__(self,
mu_control=0,
mu_experimental=0.4,
sigma=1.0,
n_stage1=50,
n_stage2_orig=50,
alpha=0.025,
n_sim=10000):
self.mu_c = mu_control
self.mu_e = mu_experimental
self.sigma = sigma
self.n1 = n_stage1
self.n2_orig = n_stage2_orig
self.alpha = alpha
self.n_sim = n_sim
# Pre-calculate weights for Inverse Normal Combination (based on initial planned N)
total_n_planned = n_stage1 + n_stage2_orig
self.w1 = np.sqrt(n_stage1 / total_n_planned)
self.w2 = np.sqrt(n_stage2_orig / total_n_planned)
# Critical values for Interim decisions
self.z_futility = 0.0 # Stop if Z < 0
self.z_efficacy_interim = 2.9 # Binding boundary to stop early
def generate_data(self, n, delta):
# Generate outcomes for Control and Experimental
# Under H0, delta = 0. Under H1, delta = mu_e - mu_c
y_c = np.random.normal(self.mu_c, self.sigma, n)
y_e = np.random.normal(self.mu_c + delta, self.sigma, n)
return y_c, y_e
def calculate_z(self, y_c, y_e):
diff = np.mean(y_e) - np.mean(y_c)
se = self.sigma * np.sqrt(1/len(y_c) + 1/len(y_e))
return diff / se
def run_single_sim(self, true_delta):
# --- STAGE 1 ---
yc1, ye1 = self.generate_data(self.n1, true_delta)
z1 = self.calculate_z(yc1, ye1)
effect_stage1 = np.mean(ye1) - np.mean(yc1)
# --- INTERIM DECISIONS ---
n2_final = self.n2_orig
decision = "continue"
# 1. Stop for Futility
if z1 < self.z_futility:
return {"reject_H0": False, "effect": effect_stage1, "n_total": self.n1, "stage": 1}
# 2. Stop for Efficacy (binding)
if z1 >= self.z_efficacy_interim:
return {"reject_H0": True, "effect": effect_stage1, "n_total": self.n1, "stage": 1}
# 3. Sample Size Re-estimation (SSR)
# If results are 'promising' (e.g., Z > 1.5), increase N to boost power
if z1 > 1.5:
# Calculate Conditional Power (CP)
# Simplified CP formula assuming trend continues
# We target 80% Conditional Power
cp_target = 0.8
# Approximation of required information level (simple increase logic)
# In a real trial, this uses exact formulae. Here we cap doubling the size.
n2_final = int(self.n2_orig * 1.5) # Increase by 50%
# --- STAGE 2 ---
yc2, ye2 = self.generate_data(n2_final, true_delta)
z2 = self.calculate_z(yc2, ye2)
# Effect sizes for bias calculation (Naive vs Weighted)
effect_stage2 = np.mean(ye2) - np.mean(yc2)
# --- FINAL ANALYSIS (Inverse Normal Combination) ---
# We combine the p-values (or Z-scores) to control Type I error
z_comb = self.w1 * z1 + self.w2 * z2
# Critical value for one-sided alpha 0.025 is 1.96
final_reject = z_comb > 1.96
# Naive effect size (simple average of all data pooled)
total_n = self.n1 + n2_final
naive_effect = (self.n1 * effect_stage1 + n2_final * effect_stage2) / total_n
return {
"reject_H0": final_reject,
"effect": naive_effect,
"n_total": total_n,
"stage": 2
}
def run_mass_sim(self):
results_h0 = []
results_h1 = []
print("Running Simulations under H0 (Null)...")
for _ in range(self.n_sim):
results_h0.append(self.run_single_sim(true_delta=0))
print("Running Simulations under H1 (Alternative)...")
for _ in range(self.n_sim):
results_h1.append(self.run_single_sim(true_delta=self.mu_e - self.mu_c))
self.analyze(results_h0, "Null Hypothesis (H0)")
self.analyze(results_h1, "Alternative Hypothesis (H1)")
def analyze(self, results, label):
rejections = np.mean([r['reject_H0'] for r in results])
avg_n = np.mean([r['n_total'] for r in results])
# Bias Calculation
# Only calculate effect size bias on trials that rejected H0 (Selection Bias)
# or simply the overall raw bias.
true_effect = 0.0 if "Null" in label else (self.mu_e - self.mu_c)
estimated_effects = [r['effect'] for r in results if r['reject_H0']]
if len(estimated_effects) > 0:
bias = np.mean(estimated_effects) - true_effect
else:
bias = 0
print(f"\n--- Results: {label} ---")
print(f"Probability of Rejection (Power/Type I Error): {rejections:.4f}")
print(f"Average Sample Size: {avg_n:.1f}")
if "Null" not in label:
print(f"Bias in Effect Estimate (Conditional on Success): {bias:.4f}")
# Run the simulation
if __name__ == "__main__":
sim = AdaptiveTrialSimulation()
sim.run_mass_sim()
In a standard fixed trial, you just check if . In an adaptive trial, if you see "promising" results and add more patients, you increase the chance of a False Positive just by sheer volume of data.
In the simulation output under :
reject_H0 was True.Adaptive designs introduce Operational Bias.
Effect Size Bias (Over-estimation):
Selection Bias:
If you run the code above, you will see:
numpy and scipy.