power-optimization-patterns
Direct and tradeoff-based optimization strategies for clinical trial design. Use when optimizing sample size, selecting design parameters, or performing sensitivity analysis.
What this skill does
# Power Optimization Patterns
## When to Use This Skill
- Optimizing sample size for target power
- Selecting design parameters (randomization ratio, event count)
- Trading off between competing objectives
- Performing sensitivity analysis
- Finding optimal regions across scenarios
## Clinical Trial Optimization Framework
### Problem Formulation
**Components:**
- Data Model D(θ): Parameterized by θ (treatment effects, rates, etc.)
- Analysis Model A(λ): Parameterized by λ (sample size, events, etc.)
- Criterion ψ(λ | θ): Power or other metric
**Objective:**
Find λ* that optimizes ψ(λ | θ) subject to constraints.
## Direct Optimization
### Sample Size Determination
**Objective:** Find minimum n such that Power(n) ≥ target
**Binary Search Algorithm:**
```r
find_sample_size <- function(target_power, effect_size, alpha = 0.025,
n_low = 50, n_high = 500, n_sims = 10000) {
while (n_high - n_low > 5) {
n_mid <- round((n_low + n_high) / 2)
# Run CSE with n_mid
data.model <- DataModel() +
OutcomeDist(outcome.dist = "NormalDist") +
SampleSize(n_mid) +
Sample(id = "Control", outcome.par = parameters(mean = 0, sd = 1)) +
Sample(id = "Treatment", outcome.par = parameters(mean = effect_size, sd = 1))
analysis.model <- AnalysisModel() +
Test(id = "Primary", samples = samples("Control", "Treatment"), method = "TTest")
evaluation.model <- EvaluationModel() +
Criterion(id = "Power", method = "MarginalPower",
tests = tests("Primary"), labels = "Power",
par = parameters(alpha = alpha))
results <- CSE(data.model, analysis.model, evaluation.model,
SimParameters(n.sims = n_sims, proc.load = "full", seed = 12345))
power <- results$simulation.results$Power
if (power >= target_power) {
n_high <- n_mid
} else {
n_low <- n_mid
}
}
return(n_high)
}
```
### Event Count Optimization (TTE)
```r
# Grid search over event counts
event_grid <- seq(200, 400, by = 25)
power_results <- numeric(length(event_grid))
for (i in seq_along(event_grid)) {
results <- sim_fixed_n(
n_sim = 10000,
sample_size = 500,
target_event = event_grid[i],
enroll_rate = enroll_rate,
fail_rate = fail_rate,
timing_type = 2
)
power_results[i] <- mean(results$z < qnorm(0.025))
}
# Find minimum events for 90% power
min_events <- event_grid[min(which(power_results >= 0.90))]
```
## Tradeoff-Based Optimization
### Additive Criterion
**Formula:**
```
ψ_combined(λ) = w₁ × ψ₁(λ) + w₂ × ψ₂(λ)
```
**Example: Power vs Sample Size**
```r
# Weights: 70% power importance, 30% sample size (negative for minimization)
w1 <- 0.7
w2 <- -0.3 # Negative because we want to minimize sample size
sample_sizes <- seq(60, 120, by = 10)
combined_scores <- numeric(length(sample_sizes))
for (i in seq_along(sample_sizes)) {
n <- sample_sizes[i]
# Simulate power
# ... CSE simulation ...
power <- results$simulation.results$Power
# Normalize sample size to [0,1] scale
n_normalized <- (n - min(sample_sizes)) / (max(sample_sizes) - min(sample_sizes))
combined_scores[i] <- w1 * power + w2 * n_normalized
}
optimal_n <- sample_sizes[which.max(combined_scores)]
```
### Constrained Optimization
**Problem:** Maximize ψ₁(λ) subject to ψ₂(λ) ≥ c
**Example: Maximize secondary power subject to primary power ≥ 90%**
```r
# Grid search with constraint
secondary_power <- numeric(length(weight_grid))
primary_power <- numeric(length(weight_grid))
for (i in seq_along(weight_grid)) {
w <- weight_grid[i]
# Configure multiplicity with weight w for primary
# ... run CSE ...
primary_power[i] <- results$simulation.results$Primary_Power
secondary_power[i] <- results$simulation.results$Secondary_Power
}
# Find optimal weight satisfying constraint
valid_idx <- which(primary_power >= 0.90)
optimal_w <- weight_grid[valid_idx[which.max(secondary_power[valid_idx])]]
```
## Sensitivity Analysis
### Qualitative Sensitivity (Pivoting)
Evaluate optimal λ across multiple θ scenarios.
```r
# Define scenarios
scenarios <- list(
conservative = parameters(mean = 0.3, sd = 1),
expected = parameters(mean = 0.5, sd = 1),
optimistic = parameters(mean = 0.7, sd = 1)
)
optimal_n <- list()
for (scenario_name in names(scenarios)) {
effect <- scenarios[[scenario_name]]
# Find optimal n for this scenario
optimal_n[[scenario_name]] <- find_sample_size(
target_power = 0.90,
effect_size = effect$mean
)
}
# Report range
cat("Sample size range:", min(unlist(optimal_n)), "-", max(unlist(optimal_n)))
```
### Quantitative Sensitivity (Bootstrap)
Perturb θ and evaluate robustness of optimal λ.
```r
# Bootstrap perturbation of effect size
n_bootstrap <- 1000
bootstrap_power <- numeric(n_bootstrap)
optimal_n <- 100 # Fixed design choice
for (b in 1:n_bootstrap) {
# Perturb effect size (e.g., from prior distribution)
effect_b <- rnorm(1, mean = 0.5, sd = 0.1)
# Simulate power at optimal_n
# ... CSE with effect_b ...
bootstrap_power[b] <- results$simulation.results$Power
}
# Robustness metrics
cat("Mean power:", mean(bootstrap_power), "\n")
cat("Power 95% CI:", quantile(bootstrap_power, c(0.025, 0.975)), "\n")
cat("P(power >= 80%):", mean(bootstrap_power >= 0.80), "\n")
```
## Optimal Intervals and Regions
### Optimal Interval
The η-optimal interval contains all λ values within η% of optimal power.
```r
# Define optimal interval
eta <- 0.95 # 95% of maximum power
sample_sizes <- seq(50, 150, by = 5)
power_curve <- numeric(length(sample_sizes))
for (i in seq_along(sample_sizes)) {
# ... simulate power ...
power_curve[i] <- power_at_n
}
max_power <- max(power_curve)
threshold <- eta * max_power
# Find interval boundaries
optimal_interval <- sample_sizes[power_curve >= threshold]
cat("95%-optimal interval: [", min(optimal_interval), ",", max(optimal_interval), "]")
```
### Joint Optimal Region
Intersection of optimal intervals across scenarios.
```r
# Find joint optimal region
intervals <- list()
for (scenario in scenarios) {
# Get optimal interval for this scenario
intervals[[scenario]] <- find_optimal_interval(scenario, eta = 0.95)
}
# Joint region = intersection
joint_region <- Reduce(intersect, intervals)
cat("Joint optimal sample sizes:", joint_region)
```
## Compound Criteria
### Minimum Power
**Use:** Ensure robustness across scenarios
```r
# Evaluate minimum power across scenarios
evaluate_min_power <- function(n, scenarios) {
powers <- numeric(length(scenarios))
for (i in seq_along(scenarios)) {
# ... simulate power for scenario i ...
powers[i] <- power_i
}
return(min(powers))
}
# Optimize for minimum power
min_powers <- sapply(sample_sizes, evaluate_min_power, scenarios = scenarios)
optimal_n <- sample_sizes[which.max(min_powers)]
```
### Average Power
**Use:** Balance across scenarios
```r
evaluate_avg_power <- function(n, scenarios, weights = NULL) {
if (is.null(weights)) weights <- rep(1/length(scenarios), length(scenarios))
powers <- numeric(length(scenarios))
for (i in seq_along(scenarios)) {
powers[i] <- simulate_power(n, scenarios[[i]])
}
return(sum(weights * powers))
}
```
## Multiplicity Optimization
### Gamma Parameter Optimization
```r
gamma_grid <- seq(0.5, 1.0, by = 0.05)
results_list <- list()
for (i in seq_along(gamma_grid)) {
g <- gamma_grid[i]
analysis.model <- AnalysisModel() +
# Tests ...
MultAdjProc(
proc = "ParallelGatekeepingAdj",
par = parameters(
family = families(family1 = c(1, 2), family2 = c(3, 4)),
proc = families(family1 = "HolmAdj", family2 = "HolmAdj"),
gamma = families(family1 = g, family2 = 1)
)
)
results_list[[i]] <- CSE(data.model, analysis.model, evaluation.model,
SimParameters(n.sims = 10000, proc.load = "full", seed = i))
}
# Extract powers and find optimal gamma
# ... (subject to FWER constraint)Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.