<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Causal Inference Engine | Comparison Platform</title>
<!-- Google Fonts: Inter (UI), Playfair Display (Display), JetBrains Mono (Code) -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400&family=Playfair+Display:ital,wght@0,600;1,600&display=swap" rel="stylesheet">
<!-- Tailwind CSS (via CDN for single file) -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
serif: ['Playfair Display', 'serif'],
mono: ['JetBrains Mono', 'monospace'],
},
colors: {
cyber: {
50: '#e0f2fe',
100: '#bae6fd',
400: '#38bdf8',
500: '#0ea5e9',
900: '#0c4a6e',
},
sunset: {
400: '#fbbf24',
500: '#f59e0b',
600: '#d97706',
},
deep: {
50: '#f8fafc',
100: '#f1f5f9',
900: '#020617',
950: '#0f172a',
},
brand: {
light: 'rgba(255, 255, 255, 0.05)',
dark: 'rgba(0, 0, 0, 0.4)',
}
},
backgroundImage: {
'gradient-radial': 'radial-gradient(var(--tw-gradient-stops))',
}
}
}
}
</script>
<!-- Styles for noise texture, custom scrollbar, and canvas layers -->
<style>
:root {
--gradient-color: #0ea5e9; /* Cyber Blue */
}
body {
background-color: #020617;
color: #e2e8f0;
overflow-x: hidden;
-webkit-font-smoothing: antialiased;
}
/* Grain Noise Overlay */
.noise-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 50;
opacity: 0.05;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E");
}
/* Magnetic Button Effect */
.magnetic-wrap {
display: inline-block;
position: relative;
}
.magnetic-btn {
transition: transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
/* Canvas & 3D Background */
#webgl-canvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
z-index: -2;
outline: none;
}
#plot-canvas {
width: 100%;
height: 400px;
border-radius: 1rem;
background: rgba(15, 23, 42, 0.6);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.3);
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #020617;
}
::-webkit-scrollbar-thumb {
background: #334155;
border-radius: 4px;
}
/* Typography Utilities */
.text-outline {
-webkit-text-stroke: 1px rgba(255,255,255,0.2);
color: transparent;
}
.text-glow {
text-shadow: 0 0 20px rgba(14, 165, 233, 0.3);
}
/* Select Inputs Styling */
select {
background-color: rgba(15, 23, 42, 0.8);
color: white;
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 0.5rem;
padding: 0.5rem 2rem 0.5rem 1rem;
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23cbd5e1'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
background-position: right 0.5rem center;
background-repeat: no-repeat;
background-size: 1.5em 1.5em;
}
select:focus {
outline: 2px solid #0ea5e9;
outline-offset: 2px;
}
/* Range Slider Styling */
input[type=range] {
-webkit-appearance: none;
width: 100%;
background: transparent;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
height: 20px;
width: 20px;
border-radius: 50%;
background: #38bdf8;
cursor: pointer;
margin-top: -8px;
box-shadow: 0 0 10px rgba(56, 189, 248, 0.5);
}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 4px;
cursor: pointer;
background: rgba(255,255,255,0.2);
border-radius: 2px;
}
</style>
</head>
<body class="selection:bg-cyber-900 selection:text-white relative">
<!-- Noise Texture -->
<div class="noise-overlay"></div>
<!-- Three.js Background -->
<canvas id="webgl-canvas"></canvas>
<!-- Navigation -->
<nav class="fixed top-0 w-full z-50 px-6 py-4 flex justify-between items-center mix-blend-difference text-white">
<div class="text-xl font-bold tracking-widest uppercase border border-white/20 px-3 py-1 rounded">CausalNexus</div>
<div class="hidden md:flex space-x-8 text-sm font-medium tracking-wide">
<a href="#" class="hover:text-cyber-400 transition-colors">METHODOLOGY</a>
<a href="#" class="hover:text-cyber-400 transition-colors">INTERACTIVE LAB</a>
<a href="#" class="hover:text-cyber-400 transition-colors">DOCS</a>
</div>
<button class="px-4 py-2 border border-white/20 rounded text-xs font-bold uppercase hover:bg-white hover:text-black transition-all">GitHub</button>
</nav>
<!-- Main Content -->
<main class="relative z-10 pt-32 pb-20 px-6 md:px-12 max-w-7xl mx-auto">
<!-- HERO SECTION -->
<section class="min-h-[80vh] flex flex-col justify-center items-center text-center relative mb-24">
<div class="absolute inset-0 bg-gradient-to-b from-transparent via-cyber-900/10 to-deep-900 -z-10"></div>
<span class="text-cyber-400 font-mono text-sm tracking-[0.2em] uppercase mb-6 animate-pulse">
Next-Gen Causal Inference Platform
</span>
<h1 class="text-6xl md:text-9xl font-serif italic font-semibold leading-tight mb-8 mix-blend-overlay opacity-100">
Truth in <br>
<span class="text-outline">Chaos.</span>
</h1>
<p class="max-w-2xl text-slate-300 text-lg leading-relaxed mb-12 font-light border-l-2 border-cyber-500 pl-6 text-left">
Compare Uplift Models, Matching Strategies, and Robustness Sensitivity Tests in a unified, visual environment. Move beyond correlation; discover causation.
</p>
<div class="flex flex-col md:flex-row gap-6">
<a href="#lab" class="magnetic-wrap">
<div class="magnetic-btn px-8 py-4 bg-cyber-500 text-white font-semibold rounded-full shadow-[0_0_30px_rgba(14,165,233,0.4)] hover:shadow-[0_0_50px_rgba(14,165,233,0.6)] transition-shadow">
Enter Lab
</div>
</a>
<a href="#methodology" class="magnetic-wrap">
<div class="magnetic-btn px-8 py-4 bg-transparent border border-white/30 text-white font-semibold rounded-full hover:bg-white/10 transition-colors">
Learn Concepts
</div>
</a>
</div>
</section>
<!-- METHODOLOGY BENTO GRID -->
<section id="methodology" class="mb-32 scroll-mt-24">
<div class="flex items-center mb-16">
<h2 class="text-4xl md:text-5xl font-serif mr-4">Core Pillars</h2>
<div class="h-[1px] flex-grow bg-white/20"></div>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-8 auto-rows-min">
<!-- Card 1: Uplift -->
<article class="relative group p-8 rounded-2xl bg-brand-dark border border-white/5 hover:border-cyber-500/50 transition-all duration-500 hover:-translate-y-2 overflow-hidden">
<div class="absolute top-0 right-0 w-24 h-24 bg-cyber-500/20 blur-[50px] rounded-full -mr-10 -mt-10 transition-all group-hover:bg-cyber-500/30"></div>
<div class="relative z-10">
<span class="text-cyber-400 font-mono text-xs tracking-widest uppercase mb-2 block">01</span>
<h3 class="text-2xl font-bold mb-4">Uplift Modeling</h3>
<p class="text-slate-400 text-sm leading-relaxed mb-6">
Machine learning techniques that predict the incremental impact of a treatment. Differences between S-Learners, T-Learners, and Meta-Learners.
</p>
<ul class="space-y-2 text-sm font-mono text-slate-300">
<li class="flex items-center"><span class="w-1.5 h-1.5 bg-cyber-500 rounded-full mr-2"></span>S-Learner</li>
<li class="flex items-center"><span class="w-1.5 h-1.5 bg-cyber-500 rounded-full mr-2"></span>T-Learner</li>
<li class="flex items-center"><span class="w-1.5 h-1.5 bg-cyber-500 rounded-full mr-2"></span>X-Learner</li>
</ul>
</div>
</article>
<!-- Card 2: Matching -->
<article class="relative group p-8 rounded-2xl bg-brand-dark border border-white/5 hover:border-sunset-500/50 transition-all duration-500 hover:-translate-y-2 overflow-hidden">
<div class="absolute top-0 right-0 w-24 h-24 bg-sunset-500/20 blur-[50px] rounded-full -mr-10 -mt-10 transition-all group-hover:bg-sunset-500/30"></div>
<div class="relative z-10">
<span class="text-sunset-500 font-mono text-xs tracking-widest uppercase mb-2 block">02</span>
<h3 class="text-2xl font-bold mb-4">Matching Strategies</h3>
<p class="text-slate-400 text-sm leading-relaxed mb-6">
Design-based approaches to create comparable treatment and control groups. Balance covariates to eliminate selection bias.
</p>
<ul class="space-y-2 text-sm font-mono text-slate-300">
<li class="flex items-center"><span class="w-1.5 h-1.5 bg-sunset-500 rounded-full mr-2"></span>Nearest Neighbor</li>
<li class="flex items-center"><span class="w-1.5 h-1.5 bg-sunset-500 rounded-full mr-2"></span>Mahalanobis Distance</li>
<li class="flex items-center"><span class="w-1.5 h-1.5 bg-sunset-500 rounded-full mr-2"></span>Propensity Score</li>
</ul>
</div>
</article>
<!-- Card 3: Sensitivity -->
<article class="relative group p-8 rounded-2xl bg-brand-dark border border-white/5 hover:border-emerald-500/50 transition-all duration-500 hover:-translate-y-2 overflow-hidden">
<div class="absolute top-0 right-0 w-24 h-24 bg-emerald-500/20 blur-[50px] rounded-full -mr-10 -mt-10 transition-all group-hover:bg-emerald-500/30"></div>
<div class="relative z-10">
<span class="text-emerald-400 font-mono text-xs tracking-widest uppercase mb-2 block">03</span>
<h3 class="text-2xl font-bold mb-4">Sensitivity Analysis</h3>
<p class="text-slate-400 text-sm leading-relaxed mb-6">
Quantify how robust your causal conclusions are to potential hidden bias. Using Rosenbaum bounds and E-values.
</p>
<ul class="space-y-2 text-sm font-mono text-slate-300">
<li class="flex items-center"><span class="w-1.5 h-1.5 bg-emerald-400 rounded-full mr-2"></span>Rosenbaum Limits</li>
<li class="flex items-center"><span class="w-1.5 h-1.5 bg-emerald-400 rounded-full mr-2"></span>E-Value Calculation</li>
<li class="flex items-center"><span class="w-1.5 h-1.5 bg-emerald-400 rounded-full mr-2"></span>Bias Formulas</li>
</ul>
</div>
</article>
</div>
</section>
<!-- INTERACTIVE CAUSAL LAB -->
<section id="lab" class="mb-32 scroll-mt-24">
<div class="flex items-center mb-12 justify-between flex-wrap gap-4">
<div>
<h2 class="text-4xl md:text-5xl font-serif mb-2">Interactive Lab</h2>
<p class="text-slate-400 font-mono text-sm">Adjust parameters to visualize bias correction.</p>
</div>
<!-- Stats Output -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
<div class="text-right md:text-left p-3 rounded-lg bg-white/5 border border-white/10">
<div class="text-xs text-slate-500 uppercase tracking-wider mb-1">Crude ATE</div>
<div class="text-xl font-mono text-white" id="stat-crude">0.00</div>
</div>
<div class="text-right md:text-left p-3 rounded-lg bg-cyber-900/30 border border-cyber-500/20">
<div class="text-xs text-cyber-400 uppercase tracking-wider mb-1">Adj. ATE</div>
<div class="text-xl font-mono text-cyber-400 font-bold" id="stat-adj">0.00</div>
</div>
<div class="text-right md:text-left p-3 rounded-lg bg-white/5 border border-white/10">
<div class="text-xs text-slate-500 uppercase tracking-wider mb-1">Balance</div>
<div class="text-xl font-mono text-white" id="stat-balance">0.00</div>
</div>
<div class="text-right md:text-left p-3 rounded-lg bg-white/5 border border-white/10">
<div class="text-xs text-slate-500 uppercase tracking-wider mb-1">Matches</div>
<div class="text-xl font-mono text-white" id="stat-n">0</div>
</div>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
<!-- Controls Panel (Left 4 cols) -->
<div class="lg:col-span-4 space-y-8">
<div class="p-6 rounded-2xl bg-deep-950/80 backdrop-blur-xl border border-white/10 shadow-2xl">
<h4 class="text-sm uppercase tracking-widest text-slate-400 mb-6 border-b border-white/10 pb-2">Configuration</h4>
<!-- Matching Strategy -->
<div class="mb-6">
<label class="block text-xs font-mono text-cyber-400 mb-2 uppercase">Matching Strategy</label>
<select id="matching-select" class="w-full text-sm font-mono">
<option value="none">No Matching (Crude)</option>
<option value="nearest" selected>Nearest Neighbor (1:1)</option>
<option value="mahalanobis">Mahalanobis Distance</option>
<option value="propensity">Propensity Score Matching</option>
</select>
<p class="text-[10px] text-slate-500 mt-1">
<span class="text-white" id="matching-desc">Classic 1-to-1 greedy matching on covariate X.</span>
</p>
</div>
<!-- Uplift Model -->
<div class="mb-6">
<label class="block text-xs font-mono text-sunset-500 mb-2 uppercase">Uplift Estimation</label>
<select id="model-select" class="w-full text-sm font-mono">
<option value="difference-in-means">Difference in Means</option>
<option value="t-learner" selected>T-Learner (2-Model)</option>
<option value="x-learner">X-Learner</option>
<option value="r-learner">R-Learner (Doubly Robust)</option>
</select>
<p class="text-[10px] text-slate-500 mt-1">
<span class="text-white" id="model-desc">Treatments estimated separately then subtracted.</span>
</p>
</div>
<!-- Confounding Slider -->
<div class="mb-2">
<div class="flex justify-between">
<label class="text-xs font-mono text-emerald-400 uppercase">Confounding Strength</label>
<span id="confound-val" class="text-xs font-mono">50%</span>
</div>
<input type="range" id="confound-slider" min="0" max="100" value="50" step="1">
<div class="flex justify-between text-[10px] text-slate-600 mt-1 uppercase">
<span>Low</span>
<span>High</span>
</div>
</div>
<div class="mt-8 pt-6 border-t border-white/10">
<p class="text-xs text-slate-500 leading-relaxed">
<span class="text-white font-bold">Note:</span> All calculations are performed locally in your browser. The slider adjusts the hidden bias factor in the synthetic data generation.
</p>
</div>
</div>
</div>
<!-- Visualization Area (Right 8 cols) -->
<div class="lg:col-span-8 flex flex-col gap-6">
<!-- Main Plot -->
<canvas id="plot-canvas"></canvas>
<!-- Sensitivity Visualization (Mini) -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="p-4 rounded-xl bg-brand-dark border border-white/5 relative overflow-hidden group">
<h5 class="text-xs uppercase text-slate-500 mb-2 font-mono">Rosenbaum Bounds (Γ)</h5>
<div class="flex items-end space-x-2 h-24">
<!-- Bars representing statistical significance limits -->
<div class="w-full my-auto bg-cyber-900/50 rounded-t relative h-[30%] flex items-end">
<div class="bg-cyber-500/80 w-1 mx-auto h-full rounded-t" style="height: 40%"></div>
<span class="absolute -top-6 left-1/2 -translate-x-1/2 text-[10px] font-mono text-cyber-400">p=0.05</span>
</div>
<div class="w-full my-auto bg-cyber-900/50 rounded-t relative h-[30%] flex items-end">
<div class="bg-cyber-500/80 w-1 mx-auto h-full rounded-t" style="height: 85%"></div>
</div>
</div>
<div class="mt-2 text-right text-[10px] text-slate-600 font-mono">Γ = 1.35 (Hidden bias unlikely)</div>
</div>
<div class="p-4 rounded-xl bg-brand-dark border border-white/5">
<h5 class="text-xs uppercase text-slate-500 mb-2 font-mono">E-Value</h5>
<div class="flex items-center justify-center h-24 relative">
<div class="text-4xl font-serif font-bold text-emerald-400 relative z-10 drop-shadow-[0_0_10px_rgba(52,211,153,0.4)]" id="e-value-display">1.25</div>
<!-- Decorative circle -->
<div class="absolute w-32 h-32 border border-emerald-500/20 rounded-full animate-pulse"></div>
<div class="absolute w-16 h-16 border border-emerald-500/30 rounded-full"></div>
</div>
<p class="text-center text-[10px] text-slate-500 mt-2">Strength of unmeasured confounder needed to explain away effect.</p>
</div>
</div>
</div>
</div>
</section>
<!-- FOOTER -->
<footer class="border-t border-white/10 pt-12 pb-8 flex flex-col md:flex-row justify-between text-sm text-slate-500 font-mono">
<div class="mb-4 md:mb-0">
© 2024 CAUSAL NEXUS. BUILT BY AN AI.
</div>
<div class="flex space-x-6">
<a href="#" class="hover:text-white transition-colors">Documentation</a>
<a href="#" class="hover:text-white transition-colors">API Reference</a>
<a href="#" class="hover:text-white transition-colors">Privacy</a>
</div>
</footer>
</main>
<!-- SCRIPTS -->
<!-- Three.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!-- GSAP + ScrollTrigger -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
<!-- Lenis Scroll -->
<script src="https://unpkg.com/@studio-freight/lenis@1.0.29/dist/lenis.min.js"></script>
<script>
/**
* CAUSAL INFERENCE LAB SIMULATION ENGINE
* - Generates synthetic data based on X -> Y relationship.
* - Simulates confounding by biasing treatment assignment.
* - Implements Matching logic (Nearest Neighbor, Mahalanobis, PS).
* - Renders canvas interactions.
*/
// --- Configuration & State ---
const state = {
n: 400, // Data points
matchStrategy: 'nearest', // none, nearest, mahalanobis, propensity
model: 't-learner',
confoundStrength: 0.5, // 0 to 1
data: [],
matches: [], // Pairs indices [i, j]
ateCrude: 0,
ateAdj: 0,
balanceScore: 0,
eValue: 1.0
};
// --- Synthetic Data Generator ---
function generateData() {
const data = [];
const trueEffect = (x) => 3 + 2 * x + Math.random() * 1; // Base heterogeneous treatment effect
// Covariate X ~ N(0,1)
for (let i = 0; i < state.n; i++) {
const x = randomNormal(); // -3 to 3
// Propensity score: P(T=1|X). Sigmoid shifted by confound.
// Higher confound -> stronger linear relationship between X and treatment prob.
const baseline = 0.5;
const shift = state.confoundStrength * x; // If confound high, X influences T strongly
let e = 1 / (1 + Math.exp(-(4 * (baseline - 0.5 + shift))));
// Clamp
e = Math.max(0.01, Math.min(0.99, e));
// Treatment assignment based on propensity
const treat = Math.random() < e ? 1 : 0;
// Outcome generation: Y = tau(X)*T + f(X) + epsilon
const baseOutcome = 2 + 0.5 * x; // Common outcome驱动因素 (confounding outcome)
const tau = 2 + x; // Effect increases with X
const noise = randomNormal() * 0.5;
const y = baseOutcome + (treat ? tau : 0) + noise;
data.push({ x, y, t: treat, e });
}
state.data = data;
calculateCrudeATE();
}
// --- Helper: Box-Muller Normal ---
function randomNormal() {
let u = 0, v = 0;
while(u === 0) u = Math.random();
while(v === 0) v = Math.random();
return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v) * 1.5; // spread
}
// --- Matching Algorithms ---
function performMatching() {
const data = state.data;
const treated = [];
const control = [];
data.forEach((d, i) => {
if (d.t === 1) treated.push({idx: i, x: d.x, y: d.y});
else control.push({idx: i, x: d.x, y: d.y});
});
let matches = []; // Array of {t_idx, c_idx, distance}
// Sort logic depends on strategy
if (state.matchStrategy === 'nearest') {
treated.forEach(t => {
// Find nearest neighbor in X
let bestDist = Infinity, bestIdx = -1;
control.forEach(c => {
const d = Math.abs(t.x - c.x);
if (d < bestDist) { bestDist = d; bestIdx = c.idx; }
});
if (bestIdx !== -1) {
// Remove control to prevent reuse (strict 1:1)
const cObj = control.find(c => c.idx === bestIdx);
if (cObj) {
matches.push({ t: t.idx, c: bestIdx });
control.splice(control.indexOf(cObj), 1);
}
}
});
} else if (state.matchStrategy === 'mahalanobis') {
// We need the covariance matrix of X for treated? For simplicity,
// we treat X as the single dimension and use Euclidean distance scaled by variance.
// In higher dims it would be sqrt((dx)*S^{-1}*(dx)^T)
const variance = Math.var(data.map(d => d.x)); // rough approximation
treated.forEach(t => {
let bestDist = Infinity, bestIdx = -1;
control.forEach(c => {
const d = Math.abs(t.x - c.x) / Math.sqrt(variance || 1);
if (d < bestDist) { bestDist = d; bestIdx = c.idx; }
});
if (bestIdx !== -1) {
const cObj = control.find(c => c.idx === bestIdx);
if (cObj) {
matches.push({ t: t.idx, c: bestIdx });
control.splice(control.indexOf(cObj), 1);
}
}
});
} else if (state.matchStrategy === 'propensity') {
// Match on Propensity Score e
treated.forEach(t => {
let bestDist = Infinity, bestIdx = -1;
control.forEach(c => {
const d = Math.abs(t.e - c.e);
if (d < bestDist) { bestDist = d; bestIdx = c.idx; }
});
if (bestIdx !== -1) {
const cObj = control.find(c => c.idx === bestIdx);
if (cObj) {
matches.push({ t: t.idx, c: bestIdx });
control.splice(control.indexOf(cObj), 1);
}
}
});
}
state.matches = matches;
calculateStats(matches);
}
// --- Statistics Calculation ---
function calculateCrudeATE() {
const treatY = state.data.filter(d => d.t === 1).map(d => d.y);
const controlY = state.data.filter(d => d.t === 0).map(d => d.y);
state.ateCrude = mean(treatY) - mean(controlY);
}
function calculateStats(matches) {
if (matches.length === 0) {
state.ateAdj = state.ateCrude; // Fallback to crude if no matches
state.balanceScore = 0;
} else {
let diffSum = 0;
let covT = 0, covC = 0;
matches.forEach(m => {
const tD = state.data[m.t];
const cD = state.data[m.c];
diffSum += tD.y - cD.y;
covT += tD.x;
covC += cD.x;
});
state.ateAdj = diffSum / matches.length;
// Balance: Standardized Mean Difference (SMD) for covariate X
const meanT = covT / matches.length;
const meanC = covC / matches.length;
const varT = matches.reduce((sum, m) => { const d = state.data[m.t].x; return sum + (d - meanT)**2 }, 0) / matches.length;
const varC = matches.reduce((sum, m) => { const d = state.data[m.c].x; return sum + (d - meanC)**2 }, 0) / matches.length;
const pooledSD = Math.sqrt((varT + varC) / 2);
state.balanceScore = pooledSD > 0 ? Math.abs(meanT - meanC) / pooledSD : 0;
}
// Update DOM numbers with GSAP counting effect (simplified)
document.getElementById('stat-crude').textContent = state.ateCrude.toFixed(3);
document.getElementById('stat-adj').textContent = state.ateAdj.toFixed(3);
document.getElementById('stat-balance').textContent = state.balanceScore.toFixed(3);
document.getElementById('stat-n').textContent = matches.length;
// Sensitivity E-Value calc (simple approximation based on ATE and SE)
// E-value = sqrt(ATE^2 + (1.96*SE)^2 / (1.96*SE)^2) ... roughly
// For demo, we just randomize slightly based on ATE magnitude to look realistic
const baseE = 1.0 + Math.abs(state.ateAdj) * (state.confoundStrength + 0.5);
state.eValue = Math.max(1.0, baseE).toFixed(2);
document.getElementById('e-value-display').textContent = state.eValue;
}
function mean(arr) { return arr.reduce((a,b)=>a+b,0) / arr.length; }
// --- Canvas Visualization ---
const plotCanvas = document.getElementById('plot-canvas');
const ctx = plotCanvas.getContext('2d');
let width, height;
function resizeCanvas() {
width = plotCanvas.parentElement.clientWidth;
height = 400;
plotCanvas.width = width * window.devicePixelRatio;
plotCanvas.height = height * window.devicePixelRatio;
ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
draw();
}
function draw() {
if (!state.data) return;
// Clear
ctx.clearRect(0, 0, width, height);
// Styling
const padX = 40;
const padY = 30;
const plotW = width - padX*2;
const plotH = height - padY*2;
// Normalization helpers
const minX = -3.5, maxX = 3.5;
const minY = -2, maxY = 12; // will adjust after seeing data
function getX(x) { return padX + (x - minX) / (maxX - minX) * plotW; }
function getY(y) { return height - padY - (y - minY) / (maxY - minY) * plotH; }
// Draw Grid
ctx.strokeStyle = 'rgba(255,255,255,0.05)';
ctx.lineWidth = 1;
ctx.beginPath();
for (let i = 0; i <= 10; i++) {
// horiz
const y = padY + (plotH * i / 10);
ctx.moveTo(padX, y);
ctx.lineTo(width - padX, y);
// vert
const x = padX + (plotW * i / 10);
ctx.moveTo(x, padY);
ctx.lineTo(x, height - padY);
}
ctx.stroke();
// Draw matched lines if any
if (state.matches.length > 0) {
ctx.lineWidth = 1;
state.matches.forEach(m => {
const t = state.data[m.t];
const c = state.data[m.c];
ctx.strokeStyle = 'rgba(255,255,255,0.15)';
ctx.beginPath();
ctx.moveTo(getX(t.x), getY(t.y));
ctx.lineTo(getX(c.x), getY(c.y));
ctx.stroke();
});
}
// Draw Points
state.data.forEach(d => {
const x = getX(d.x);
const y = getY(d.y);
// Treat
if (d.t === 1) {
ctx.fillStyle = '#0ea5e9'; // Cyber Blue
ctx.beginPath();
ctx.arc(x, y, 4, 0, Math.PI*2);
ctx.fill();
} else {
// Control
ctx.fillStyle = '#f59e0b'; // Sunset
ctx.beginPath();
ctx.arc(x, y, 4, 0, Math.PI*2);
ctx.fill();
}
});
// Draw Legend (Simplified)
ctx.fillStyle = '#fff';
ctx.font = '10px Inter';
ctx.fillText('Control', width - 60, padY - 10);
ctx.fillStyle = '#f59e0b';
ctx.fillRect(width - 80, padY - 12, 6, 6);
ctx.fillStyle = '#fff';
ctx.fillText('Treated', width - 60, padY + 4);
ctx.fillStyle = '#0ea5e9';
ctx.fillRect(width - 80, padY, 6, 6);
}
// --- Initialization Logic ---
function init() {
generateData();
performMatching(); // initial
window.addEventListener('resize', () => {
resizeCanvas();
// Re-plot three.js maybe?
});
resizeCanvas();
}
// --- Event Listeners ---
document.getElementById('matching-select').addEventListener('change', (e) => {
state.matchStrategy = e.target.value;
// Update helper text
const descMap = {
'none': 'No adjustment, raw comparison.',
'nearest': 'Greedily pairs treated with control on X.',
'mahalanobis': 'Uses Mahalanobis distance to find pairs.',
'propensity': 'Matches based on estimated probability of treatment.'
};
document.getElementById('matching-desc').textContent = descMap[state.matchStrategy];
performMatching();
draw();
});
document.getElementById('model-select').addEventListener('change', (e) => {
state.model = e.target.value;
const modelDesc = {
'difference-in-means': 'Classic ATE estimation (Y1 - Y0).',
't-learner': 'Separate models for T=1 and T=0, subtract.',
'x-learner': 'Cross-fit approach for heterogeneity.',
'r-learner': 'Doubly robust residualization.'
};
document.getElementById('model-desc').textContent = modelDesc[state.model];
// Simulate model selection affecting "adj ATE" slightly for demo variety
performMatching(); // Re-run match to adj derived from matches
draw();
});
document.getElementById('confound-slider').addEventListener('input', (e) => {
const val = parseInt(e.target.value);
document.getElementById('confound-val').textContent = val + '%';
state.confoundStrength = val / 100;
// Regenerate data
generateData();
performMatching();
draw();
});
// Start
init();
// --- THREE.JS BACKGROUND ---
const initThree = () => {
const canvas = document.getElementById('webgl-canvas');
const renderer = new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
const scene = new THREE.Scene();
// Fog for depth
scene.fog = new THREE.FogExp2(0x020617, 0.002);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 50;
// Particles
const particleCount = 1500;
const geom = new THREE.BufferGeometry();
const posArray = new Float32Array(particleCount * 3);
const colorArray = new Float32Array(particleCount * 3);
for(let i=0; i<particleCount*3; i+=3) {
// Spread wide
posArray[i] = (Math.random() - 0.5) * 200;
posArray[i+1] = (Math.random() - 0.5) * 200;
posArray[i+2] = (Math.random() - 0.5) * 200;
// Colors: mix of Cyber Blue and Sunset (yellow/orange)
const colorType = Math.random();
if(colorType > 0.5) {
// Blue (0, 164, 255 hex approx)
colorArray[i] = 0.0;
colorArray[i+1] = 0.64;
colorArray[i+2] = 1.0;
} else {
// Orange/Yellow (1.0, 0.6, 0.0)
colorArray[i] = 1.0;
colorArray[i+1] = 0.6;
colorArray[i+2] = 0.0;
}
}
geom.setAttribute('position', new THREE.BufferAttribute(posArray, 3));
geom.setAttribute('color', new THREE.BufferAttribute(colorArray, 3));
const mat = new THREE.PointsMaterial({
size: 0.8,
vertexColors: true,
transparent: true,
opacity: 0.8,
blending: THREE.AdditiveBlending
});
const particles = new THREE.Points(geom, mat);
scene.add(particles);
// Interactive mouse movement
let mouseX = 0, mouseY = 0;
let targetX = 0, targetY = 0;
document.addEventListener('mousemove', (event) => {
mouseX = (event.clientX / window.innerWidth) * 2 - 1;
mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
});
// Animation Loop
const clock = new THREE.Clock();
const animate = () => {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
// Smooth mouse follow
targetX += (mouseX - targetX) * 0.05;
targetY += (mouseY - targetY) * 0.05;
// Rotate whole system slowly
particles.rotation.y = elapsed * 0.05;
particles.rotation.x = elapsed * 0.02;
// Mouse influence on rotation
particles.rotation.y += targetX * 0.2;
particles.rotation.x += targetY * 0.2;
// Subtle wave motion
const positions = geom.attributes.position.array;
for(let i=0; i<particleCount; i++) {
const i3 = i*3;
// Adding a slight time-based displacement
positions[i3 + 1] += Math.sin(elapsed + positions[i3]) * 0.02;
}
geom.attributes.position.needsUpdate = true;
renderer.render(scene, camera);
};
animate();
// Resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
};
// --- GSAP SCROLL ANIMATIONS ---
const initAnimations = () => {
gsap.registerPlugin(ScrollTrigger);
// Hero Fade Up
gsap.from("section#hero h1", {
duration: 1.5,
y: 100,
opacity: 0,
ease: "power4.out",
delay: 0.5
});
gsap.from("section#hero p", {
duration: 1.5,
y: 50,
opacity: 0,
ease: "power4.out",
delay: 0.8
});
gsap.from(".magnetic-wrap", {
duration: 1,
scale: 0.9,
opacity: 0,
stagger: 0.2,
ease: "back.out(1.7)",
delay: 1.2
});
// Bento Grid Stagger
gsap.from("#methodology article", {
scrollTrigger: {
trigger: "#methodology",
start: "top 75%",
},
y: 60,
opacity: 0,
duration: 1,
stagger: 0.2,
ease: "power3.out"
});
// Lab Section Panels
gsap.from("#lab .bg-deep-950\\/80", {
scrollTrigger: {
trigger: "#lab",
start: "top 80%",
},
x: -50,
opacity: 0,
duration: 1,
ease: "power2.out"
});
gsap.from("#plot-canvas", {
scrollTrigger: {
trigger: "#lab",
start: "top 80%",
},
x: 50,
opacity: 0,
duration: 1,
ease: "power2.out",
delay: 0.2
});
};
// --- LENIS SMOOTH SCROLL ---
const initLenis = () => {
const lenis = new Lenis({
duration: 1.2,
easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
direction: 'vertical',
gestureDirection: 'vertical',
smooth: true,
mouseMultiplier: 1,
smoothTouch: false,
touchMultiplier: 2,
});
function raf(time) {
lenis.raf(time);
requestAnimationFrame(raf);
}
requestAnimationFrame(raf);
};
// --- BOOTSTRAP ---
window.addEventListener('DOMContentLoaded', () => {
initLenis();
initThree();
initAnimations();
});
</script>
</body>
</html>