-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
581 lines (517 loc) · 21.2 KB
/
Copy pathindex.html
File metadata and controls
581 lines (517 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<title>Missing Data / Selection Bias Visualizer</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
body {
font-family: 'Inter', sans-serif;
-webkit-tap-highlight-color: transparent;
}
.range-slider {
position: relative;
height: 6px;
background: #374151;
border-radius: 3px;
margin: 20px 0;
touch-action: none;
}
.range-track {
position: absolute;
height: 100%;
background: #6366f1;
border-radius: 3px;
pointer-events: none;
}
.range-handle {
position: absolute;
width: 18px;
height: 18px;
background: #4f46e5;
border: 2px solid #fff;
border-radius: 50%;
top: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
z-index: 2;
touch-action: none;
}
.range-handle:hover { background: #6366f1; transform: translate(-50%, -50%) scale(1.1);}
.range-handle.dragging { background: #6366f1; transform: translate(-50%, -50%) scale(1.2);}
#plot { width: 100%; height: 400px; }
.threshold-line { stroke-dasharray: 3,3; }
/* Mobile-specific styles */
@media (max-width: 768px) {
.range-handle {
width: 24px;
height: 24px;
}
.range-slider {
height: 8px;
margin: 24px 0;
}
#plot { height: 300px; }
}
</style>
</head>
<body class="bg-gray-900 text-gray-200 min-h-screen flex flex-col items-center p-3 md:p-6">
<div class="max-w-4xl w-full bg-gray-800 rounded-xl shadow-2xl p-4 md:p-6">
<h1 class="text-2xl md:text-3xl font-bold text-white mb-2 md:mb-3 text-center">Missing Data / Selection Bias Visualizer</h1>
<p class="text-gray-400 mb-4 md:mb-6 text-center text-sm md:text-base">Explore how regression estimates can be biased by missing data / selection.</p>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 md:gap-6">
<!-- Controls -->
<div class="bg-gray-900/50 rounded-xl border border-gray-700 p-4 flex flex-col gap-5">
<div>
<label class="font-medium text-sm md:text-base">Percent Missing</label>
<input id="missSlider" type="range" min="0" max="100" value="100" class="w-full mt-1">
<div class="text-center text-indigo-400 font-mono text-lg" id="missValue">100%</div>
</div>
<div>
<label class="font-medium text-sm md:text-base">Missingness Mechanism</label>
<select id="mechSelect" class="w-full bg-gray-800 border border-gray-600 rounded-lg px-2 py-2 text-white mt-1 text-sm md:text-base">
<option value="random">Completely Random</option>
<option value="byX">X</option>
<option value="byY" selected>Y</option>
<option value="byXorY">X + Y</option>
<option value="flatten">Flatter β</option>
<option value="steepen">Steeper β</option>
</select>
</div>
<div id="xThreshDiv" class="hidden">
<label class="font-medium text-sm md:text-base">X range: <span id="xRangeVal" class="text-indigo-400 font-mono ml-1">[20, 80]</span></label>
<div class="range-slider" id="xRangeSlider">
<div class="range-track" id="xRangeTrack"></div>
<div class="range-handle" id="xMinHandle" data-value="20"></div>
<div class="range-handle" id="xMaxHandle" data-value="80"></div>
</div>
<div class="text-xs text-gray-500 text-center">Missing if X < <span id="xMinText">20</span> or X > <span id="xMaxText">80</span></div>
</div>
<div id="yThreshDiv" class="hidden">
<label class="font-medium text-sm md:text-base">Y range: <span id="yRangeVal" class="text-indigo-400 font-mono ml-1">[30, 60]</span></label>
<div class="range-slider" id="yRangeSlider">
<div class="range-track" id="yRangeTrack"></div>
<div class="range-handle" id="yMinHandle" data-value="30"></div>
<div class="range-handle" id="yMaxHandle" data-value="60"></div>
</div>
<div class="text-xs text-gray-500 text-center">Missing if Y < <span id="yMinText">30</span> or Y > <span id="yMaxText">60</span></div>
</div>
<div id="actualMissing" class="text-sm text-gray-400">
<span>% missing: </span><span id="actualMissingCount" class="text-indigo-400 font-mono">0%</span>
</div>
<button id="resample" class="mt-2 w-full bg-gray-700 hover:bg-gray-600 active:bg-gray-500 text-gray-300 font-medium py-1.5 rounded-lg text-sm">New Sample</button>
<div class="mt-2 text-sm">
<span class="inline-block w-4 h-4 rounded-full bg-orange-500 mr-2"></span>Observed
<span class="inline-block w-4 h-4 rounded-full bg-gray-500 mx-2"></span>Missing
</div>
</div>
<!-- Plot and results -->
<div class="md:col-span-2 flex flex-col gap-2">
<div class="flex flex-row gap-2 md:gap-4 justify-center items-center bg-gray-900/80 border border-gray-700 rounded-xl px-3 md:px-6 py-2 mb-2">
<div>
<span class="text-gray-400 text-sm md:text-base">True β:</span>
<span id="coefTrue" class="text-green-400 text-xl md:text-2xl font-mono font-bold">1.00</span>
</div>
<div>
<span class="text-gray-400 text-sm md:text-base">Observed β:</span>
<span id="coefObs" class="text-yellow-300 text-xl md:text-2xl font-mono font-bold">1.00</span>
</div>
<div>
<span class="text-gray-400 text-sm md:text-base">Bias:</span>
<span id="bias" class="text-red-400 text-xl md:text-2xl font-mono font-bold">0.00</span>
</div>
<div>
<span class="text-gray-400 text-sm md:text-base">SE:</span>
<span id="se" class="text-blue-400 text-xl md:text-2xl font-mono font-bold">0.00</span>
</div>
</div>
<div class="bg-gray-900 rounded-lg border border-gray-700 overflow-hidden" style="position:relative;">
<canvas id="plot"></canvas>
</div>
<div id="explanation" class="text-gray-300 mt-2 p-3 text-center text-sm md:text-base"></div>
</div>
</div>
<div class="mt-4 text-center">
<a href="https://github.com/dbann/selection" target="_blank" class="text-gray-500 hover:text-gray-300 text-xs md:text-sm">
GitHub • Feedback
</a>
</div>
</div>
<script>
// ======== State & Data Generation =========
const N = 400;
let points = [];
const trueSlope = 1;
// Range values for X/Y threshold sliders
let xMin = 20, xMax = 80;
let yMin = 30, yMax = 60;
function generateData() {
points = [];
for (let i = 0; i < N; i++) {
const x = Math.random() * 100;
const y = trueSlope * x + (Math.random() - 0.5) * 25;
points.push({ x, y, missing: false });
}
}
// ========= Range Slider Implementation ==============
function setupRangeSlider(sliderId, minHandleId, maxHandleId, trackId, min, max, onUpdate) {
const slider = document.getElementById(sliderId);
const minHandle = document.getElementById(minHandleId);
const maxHandle = document.getElementById(maxHandleId);
const track = document.getElementById(trackId);
let activeHandle = null;
function updateTrack() {
const minVal = parseFloat(minHandle.dataset.value);
const maxVal = parseFloat(maxHandle.dataset.value);
const minPercent = ((minVal - min) / (max - min)) * 100;
const maxPercent = ((maxVal - min) / (max - min)) * 100;
track.style.left = minPercent + '%';
track.style.width = (maxPercent - minPercent) + '%';
minHandle.style.left = minPercent + '%';
maxHandle.style.left = maxPercent + '%';
}
function handleStart(e, handle) {
e.preventDefault();
activeHandle = handle;
handle.classList.add('dragging');
if (e.type === 'touchstart') {
document.addEventListener('touchmove', handleMove, { passive: false });
document.addEventListener('touchend', handleEnd);
} else {
document.addEventListener('mousemove', handleMove);
document.addEventListener('mouseup', handleEnd);
}
}
function handleMove(e) {
if (!activeHandle) return;
e.preventDefault();
const rect = slider.getBoundingClientRect();
const clientX = e.type === 'touchmove' ? e.touches[0].clientX : e.clientX;
const percent = Math.max(0, Math.min(100, ((clientX - rect.left) / rect.width) * 100));
const value = Math.round(min + (percent / 100) * (max - min));
if (activeHandle === minHandle) {
const maxVal = parseFloat(maxHandle.dataset.value);
if (value < maxVal - 5) {
activeHandle.dataset.value = value;
onUpdate(value, maxVal);
}
} else {
const minVal = parseFloat(minHandle.dataset.value);
if (value > minVal + 5) {
activeHandle.dataset.value = value;
onUpdate(minVal, value);
}
}
updateTrack();
applyMissing();
draw();
}
function handleEnd() {
if (activeHandle) {
activeHandle.classList.remove('dragging');
activeHandle = null;
}
document.removeEventListener('mousemove', handleMove);
document.removeEventListener('mouseup', handleEnd);
document.removeEventListener('touchmove', handleMove);
document.removeEventListener('touchend', handleEnd);
applyMissing();
draw();
}
// Add both mouse and touch listeners
minHandle.addEventListener('mousedown', (e) => handleStart(e, minHandle));
minHandle.addEventListener('touchstart', (e) => handleStart(e, minHandle));
maxHandle.addEventListener('mousedown', (e) => handleStart(e, maxHandle));
maxHandle.addEventListener('touchstart', (e) => handleStart(e, maxHandle));
updateTrack();
}
// ========= Missingness Logic ==============
function applyMissing() {
points.forEach(p => p.missing = false);
const percent = +missSlider.value;
const mech = mechSelect.value;
let candidates = [];
if (mech === "random") {
const nMiss = Math.floor((percent / 100) * points.length);
const shuffled = [...points];
shuffle(shuffled);
for (let i = 0; i < nMiss; i++) shuffled[i].missing = true;
} else if (mech === "byX") {
candidates = points.filter(p => p.x < xMin || p.x > xMax);
} else if (mech === "byY") {
candidates = points.filter(p => p.y < yMin || p.y > yMax);
} else if (mech === "byXorY") {
candidates = points.filter(
p => (p.x < xMin || p.x > xMax) || (p.y < yMin || p.y > yMax)
);
} else if (mech === "flatten" || mech === "steepen") {
// Diagonal quadrants logic:
const pivot = 50;
const diagFlatten = p =>
(p.x < pivot && p.y < trueSlope * p.x) || // lower left
(p.x > pivot && p.y > trueSlope * p.x); // upper right
const diagSteepen = p =>
(p.x < pivot && p.y > trueSlope * p.x) || // upper left
(p.x > pivot && p.y < trueSlope * p.x); // lower right
const rule = mech === "flatten" ? diagFlatten : diagSteepen;
candidates = points.filter(rule);
}
// Mark selected candidates as missing
if (mech !== "random") {
const nCandidates = candidates.length;
const nMiss = Math.floor((percent / 100) * nCandidates);
if (nCandidates > 0 && nMiss > 0) {
const shuffled = [...candidates];
shuffle(shuffled);
for (let i = 0; i < nMiss; i++) shuffled[i].missing = true;
}
}
updateActualMissing();
}
function updateActualMissing() {
const actualMissing = points.filter(p => p.missing).length;
const actualPercent = (actualMissing / points.length * 100).toFixed(1);
document.getElementById('actualMissingCount').textContent = `${actualPercent}%`;
}
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
// ======== Regression ===========
function regression(arr) {
if (arr.length < 2) return { slope: 0, intercept: 0, se: 0 };
const n = arr.length;
let sx = 0, sy = 0, sxy = 0, sx2 = 0;
arr.forEach(p => {
sx += p.x;
sy += p.y;
sxy += p.x * p.y;
sx2 += p.x * p.x;
});
const denom = n * sx2 - sx * sx;
if (denom === 0) return { slope: 0, intercept: 0, se: 0 };
const slope = (n * sxy - sx * sy) / denom;
const intercept = (sy - slope * sx) / n;
// Calculate standard error of the slope
let ssr = 0; // sum of squared residuals
arr.forEach(p => {
const yPred = slope * p.x + intercept;
ssr += Math.pow(p.y - yPred, 2);
});
const mse = ssr / (n - 2); // mean squared error
const se = Math.sqrt(mse * n / denom);
return { slope, intercept, se };
}
// ======= Drawing ==============
function draw() {
const canvas = document.getElementById('plot');
const container = canvas.parentElement;
const width = container.offsetWidth;
const height = window.innerWidth < 768 ? 300 : 400;
// Set canvas size with device pixel ratio for sharp rendering
const dpr = window.devicePixelRatio || 1;
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
ctx.clearRect(0, 0, width, height);
// Axes range
const minX = 0, maxX = 100, minY = -20, maxY = 120;
function mapX(x) { return (x - minX) / (maxX - minX) * width; }
function mapY(y) { return height - (y - minY) / (maxY - minY) * height; }
// Adjust sizes based on screen width
const isMobile = window.innerWidth < 768;
const pointRadius = isMobile ? 3 : 4;
const lineWidth = isMobile ? 2 : 3;
const fontSize = isMobile ? '10px' : '12px';
// Draw threshold lines if applicable
const mech = mechSelect.value;
ctx.strokeStyle = '#6366f1';
ctx.lineWidth = 1;
ctx.setLineDash([3,3]);
if (["byX","byXorY"].includes(mech)) {
ctx.beginPath();
ctx.moveTo(mapX(xMin), mapY(minY));
ctx.lineTo(mapX(xMin), mapY(maxY));
ctx.stroke();
ctx.beginPath();
ctx.moveTo(mapX(xMax), mapY(minY));
ctx.lineTo(mapX(xMax), mapY(maxY));
ctx.stroke();
ctx.fillStyle = '#6366f1';
ctx.font = fontSize + ' Inter';
ctx.textAlign = 'center';
ctx.fillText(`X=${xMin}`, mapX(xMin), 15);
ctx.fillText(`X=${xMax}`, mapX(xMax), 15);
}
if (["byY","byXorY"].includes(mech)) {
ctx.beginPath();
ctx.moveTo(mapX(minX), mapY(yMin));
ctx.lineTo(mapX(maxX), mapY(yMin));
ctx.stroke();
ctx.beginPath();
ctx.moveTo(mapX(minX), mapY(yMax));
ctx.lineTo(mapX(maxX), mapY(yMax));
ctx.stroke();
ctx.save();
ctx.translate(15, mapY(yMin));
ctx.rotate(-Math.PI/2);
ctx.textAlign = 'center';
ctx.fillText(`Y=${yMin}`, 0, 0);
ctx.restore();
ctx.save();
ctx.translate(15, mapY(yMax));
ctx.rotate(-Math.PI/2);
ctx.textAlign = 'center';
ctx.fillText(`Y=${yMax}`, 0, 0);
ctx.restore();
}
ctx.setLineDash([]);
// Draw missing points (gray)
ctx.fillStyle = "#6b7280";
points.forEach(p => {
if (p.missing) {
ctx.beginPath();
ctx.arc(mapX(p.x), mapY(p.y), pointRadius, 0, 2 * Math.PI);
ctx.fill();
}
});
// Draw observed points (orange)
ctx.fillStyle = "#f97316";
points.filter(p => !p.missing).forEach(p => {
ctx.beginPath();
ctx.arc(mapX(p.x), mapY(p.y), pointRadius, 0, 2 * Math.PI);
ctx.fill();
});
// Draw true regression line (green, dashed)
ctx.strokeStyle = "#22c55e";
ctx.lineWidth = lineWidth;
ctx.setLineDash([8, 4]);
ctx.beginPath();
ctx.moveTo(mapX(minX), mapY(trueSlope * minX));
ctx.lineTo(mapX(maxX), mapY(trueSlope * maxX));
ctx.stroke();
ctx.setLineDash([]);
// Draw observed regression line (yellow)
const observed = points.filter(p => !p.missing);
let obsSlope = 0, obsInt = 0, obsSE = 0;
if (observed.length > 1) {
const { slope, intercept, se } = regression(observed);
obsSlope = slope;
obsInt = intercept;
obsSE = se;
ctx.strokeStyle = "#facc15";
ctx.lineWidth = lineWidth;
ctx.beginPath();
ctx.moveTo(mapX(minX), mapY(obsSlope * minX + obsInt));
ctx.lineTo(mapX(maxX), mapY(obsSlope * maxX + obsInt));
ctx.stroke();
}
// Update coefficients
coefTrue.textContent = trueSlope.toFixed(2);
coefObs.textContent = obsSlope.toFixed(2);
const biasValue = obsSlope - trueSlope;
bias.textContent = (biasValue >= 0 ? '+' : '') + biasValue.toFixed(2);
// Display SE with appropriate precision based on its magnitude
if (observed.length > 2) {
se.textContent = obsSE < 0.01 ? obsSE.toExponential(2) : obsSE.toFixed(3);
} else {
se.textContent = "N/A";
}
// Color bias based on magnitude
const biasClasses = "text-xl md:text-2xl font-mono font-bold";
if (Math.abs(biasValue) < 0.05) bias.className = "text-green-400 " + biasClasses;
else if (Math.abs(biasValue) < 0.15) bias.className = "text-yellow-400 " + biasClasses;
else bias.className = "text-red-400 " + biasClasses;
// Axis labels
ctx.fillStyle = '#9ca3af';
ctx.font = '14px Inter';
ctx.textAlign = 'center';
ctx.fillText('X', width / 2, height - 10);
ctx.save();
ctx.translate(18, height / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText('Y', 0, 0);
ctx.restore();
// Explanation
if (mech === "flatten") {
explanation.textContent = "Missing opposite-diagonal quadrants. Typically ⇒ β̂ ↓";
} else if (mech === "steepen") {
explanation.textContent = "Missing near-diagonal quadrants. Typically ⇒ β̂ ↑";
} else if (mech === "byX") {
explanation.textContent = "Missing X. Typically unbiased β";
} else if (mech === "byY") {
explanation.textContent = "Missing Y. Typically ⇒ β̂ ↓";
} else if (mech === "byXorY") {
explanation.textContent = "Missing X or Y. Typically ⇒ β̂ ↓";
} else {
explanation.textContent = "";
}
}
// ============ UI Elements ===============
const missSlider = document.getElementById('missSlider');
const missValue = document.getElementById('missValue');
const mechSelect = document.getElementById('mechSelect');
const xThreshDiv = document.getElementById('xThreshDiv');
const yThreshDiv = document.getElementById('yThreshDiv');
const coefTrue = document.getElementById('coefTrue');
const coefObs = document.getElementById('coefObs');
const bias = document.getElementById('bias');
const se = document.getElementById('se');
const explanation = document.getElementById('explanation');
const resample = document.getElementById('resample');
// =========== Events ============
missSlider.addEventListener('input', () => {
missValue.textContent = missSlider.value + "%";
applyMissing(); draw();
});
mechSelect.addEventListener('change', () => {
updateThresholds();
applyMissing(); draw();
});
resample.addEventListener('click', () => {
generateData(); applyMissing(); draw();
});
// Debounced resize handler
let resizeTimeout;
window.addEventListener('resize', () => {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(draw, 100);
});
function updateThresholds() {
let mech = mechSelect.value;
xThreshDiv.classList.toggle('hidden', !["byX","byXorY"].includes(mech));
yThreshDiv.classList.toggle('hidden', !["byY","byXorY"].includes(mech));
}
// Setup range sliders
setupRangeSlider('xRangeSlider', 'xMinHandle', 'xMaxHandle', 'xRangeTrack', 0, 100,
(min, max) => {
xMin = min;
xMax = max;
document.getElementById('xRangeVal').textContent = `[${min}, ${max}]`;
document.getElementById('xMinText').textContent = min;
document.getElementById('xMaxText').textContent = max;
}
);
setupRangeSlider('yRangeSlider', 'yMinHandle', 'yMaxHandle', 'yRangeTrack', 0, 100,
(min, max) => {
yMin = min;
yMax = max;
document.getElementById('yRangeVal').textContent = `[${min}, ${max}]`;
document.getElementById('yMinText').textContent = min;
document.getElementById('yMaxText').textContent = max;
}
);
// ========== Initialize ==========
generateData();
updateThresholds();
applyMissing();
draw();
</script>
</body>
</html>