Prompt specification
Build or customize the Three.js 3D scene "Grouped and pooled association comparison" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Grouped and pooled association comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/grouped-and-pooled-association-comparison-x1782
Scene Description Prompt:
Reveal a hidden common-cause grouping in stylized synthetic observations and compare grouped versus pooled associations. Build standalone HTML with Three.js from cdnjs.
Working Three.js Starter (grouped-and-pooled-association-comparison-x1782):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hidden Structure — Grouped vs Pooled Associations</title>
<style>
:root {
color-scheme: dark;
--bg: #070b12;
--panel: #0d131e;
--panel-2: #111927;
--line: #202b3b;
--line-soft: #182231;
--text: #eef4ff;
--muted: #8f9db2;
--faint: #637187;
--cyan: #52e0c4;
--amber: #ffbd66;
--violet: #a78bfa;
--coral: #ff6b6b;
--blue: #70a5ff;
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
"Liberation Mono", monospace;
--sans: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family: var(--sans);
}
body {
min-height: 100vh;
overflow-x: hidden;
background:
radial-gradient(circle at 16% -8%, rgba(82, 224, 196, 0.10), transparent 31rem),
radial-gradient(circle at 90% 7%, rgba(167, 139, 250, 0.09), transparent 28rem),
linear-gradient(180deg, #080d15 0%, #070b12 65%, #060910 100%);
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app-shell {
width: min(1540px, calc(100% - 36px));
margin: 0 auto;
padding-bottom: 32px;
}
.topbar {
height: 74px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
border-bottom: 1px solid rgba(143, 157, 178, 0.13);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
width: 35px;
height: 35px;
display: grid;
place-items: center;
position: relative;
border: 1px solid rgba(82, 224, 196, 0.35);
border-radius: 11px;
background: rgba(82, 224, 196, 0.07);
box-shadow: inset 0 0 18px rgba(82, 224, 196, 0.06);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 10px rgba(82, 224, 196, 0.7);
}
.brand-mark::before {
left: 8px;
top: 9px;
}
.brand-mark::after {
right: 8px;
bottom: 9px;
background: var(--violet);
box-shadow: 0 0 10px rgba(167, 139, 250, 0.7);
}
.brand-title {
font-size: 14px;
font-weight: 700;
letter-spacing: 0.01em;
}
.brand-subtitle {
margin-top: 2px;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.top-actions {
display: flex;
align-items: center;
gap: 10px;
}
.sample-chip,
.status-chip {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 34px;
padding: 0 11px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(15, 22, 33, 0.75);
color: var(--muted);
font-size: 12px;
}
.sample-chip {
font-family: var(--mono);
}
.status-chip {
color: #b9c5d6;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 9px rgba(82, 224, 196, 0.8);
}
.button {
min-height: 35px;
padding: 0 13px;
border: 1px solid var(--line);
border-radius: 9px;
background: #121b29;
cursor: pointer;
transition:
border-color 150ms ease,
background 150ms ease,
transform 150ms ease;
}
.button:hover {
border-color: #3a4a61;
background: #172233;
}
.button:active {
transform: translateY(1px);
}
.button.primary {
border-color: rgba(82, 224, 196, 0.34);
background: rgba(82, 224, 196, 0.10);
color: #caffef;
}
.button.primary:hover {
border-color: rgba(82, 224, 196, 0.62);
background: rgba(82, 224, 196, 0.16);
}
.intro {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 32px;
padding: 42px 0 28px;
}
.eyebrow {
margin: 0 0 10px;
color: var(--cyan);
font-family: var(--mono);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.13em;
text-transform: uppercase;
}
h1 {
margin: 0;
max-width: 860px;
font-size: clamp(34px, 4.4vw, 60px);
font-weight: 650;
line-height: 1.03;
letter-spacing: -0.045em;
}
.intro-copy {
max-width: 440px;
margin: 0 0 3px;
color: var(--muted);
font-size: 15px;
line-height: 1.65;
}
.intro-copy strong {
color: #dbe6f5;
font-weight: 600;
}
.dashboard {
display: grid;
grid-template-columns: minmax(0, 1fr) 360px;
gap: 18px;
align-items: start;
}
.card {
border: 1px solid var(--line);
border-radius: 16px;
background:
linear-gradient(180deg, rgba(18, 27, 41, 0.96), rgba(11, 17, 27, 0.96));
box-shadow:
0 24px 70px rgba(0, 0, 0, 0.24),
inset 0 1px 0 rgba(255, 255, 255, 0.025);
}
.visual-card {
min-width: 0;
overflow: hidden;
}
.visual-toolbar {
min-height: 66px;
padding: 13px 16px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
border-bottom: 1px solid var(--line-soft);
}
.visual-heading {
min-width: 190px;
}
.visual-title {
font-size: 13px;
font-weight: 700;
}
.visual-meta {
margin-top: 4px;
color: var(--faint);
font-family: var(--mono);
font-size: 10px;
letter-spacing: 0.04em;
}
.toolbar-controls {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
justify-content: flex-end;
}
.segmented {
display: inline-flex;
padding: 3px;
border: 1px solid var(--line);
border-radius: 10px;
background: #090e17;
}
.segment {
min-height: 31px;
padding: 0 12px;
border: 0;
border-radius: 7px;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 11px;
font-weight: 650;
transition: 150ms ease;
}
.segment:hover {
color: #d9e5f3;
}
.segment.active {
color: #eafff9;
background: rgba(82, 224, 196, 0.13);
box-shadow: inset 0 0 0 1px rgba(82, 224, 196, 0.18);
}
.check-control {
display: inline-flex;
align-items: center;
gap: 7px;
color: var(--muted);
cursor: pointer;
font-size: 11px;
user-select: none;
}
.check-control input {
width: 14px;
height: 14px;
accent-color: var(--cyan);
}
.chart-stage {
position: relative;
height: 568px;
overflow: hidden;
isolation: isolate;
background:
radial-gradient(circle at 28% 35%, rgba(112, 165, 255, 0.045), transparent 27%),
radial-gradient(circle at 76% 72%, rgba(167, 139, 250, 0.045), transparent 30%),
linear-gradient(180deg, #0b111b, #090f18);
}
.chart-stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
z-index: 1;
outline: none;
cursor: crosshair;
touch-action: none;
}
.chart-stage canvas.dragging {
cursor: grabbing;
}
.chart-panel-label {
position: absolute;
z-index: 3;
pointer-events: none;
padding: 10px 12px;
border: 1px solid rgba(143, 157, 178, 0.13);
border-radius: 10px;
background: rgba(9, 14, 23, 0.79);
backdrop-filter: blur(10px);
}
.panel-kicker {
color: var(--faint);
font-family: var(--mono);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.panel-name {
margin-top: 4px;
font-size: 13px;
font-weight: 700;
}
.panel-description {
margin-top: 4px;
color: var(--muted);
font-size: 10px;
}
.pooled-label .panel-kicker {
color: #ff9a9a;
}
.grouped-label .panel-kicker {
color: var(--cyan);
}
.source-badge {
position: absolute;
z-index: 3;
pointer-events: none;
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 9px;
border: 1px solid rgba(82, 224, 196, 0.24);
border-radius: 999px;
background: rgba(11, 20, 29, 0.88);
color: #b9f7e7;
font-family: var(--mono);
font-size: 9px;
letter-spacing: 0.04em;
transition: opacity 180ms ease;
}
.source-badge::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 8px rgba(82, 224, 196, 0.75);
}
.source-badge.concealed {
border-color: rgba(143, 157, 178, 0.2);
color: var(--muted);
}
.source-badge.concealed::before {
background: var(--faint);
box-shadow: none;
}
.compare-divider {
position: absolute;
z-index: 2;
pointer-events: none;
background: rgba(143, 157, 178, 0.12);
}
.chart-tooltip {
position: absolute;
z-index: 8;
min-width: 174px;
pointer-events: none;
opacity: 0;
transform: translateY(4px);
padding: 10px 11px;
border: 1px solid #334258;
border-radius: 9px;
background: rgba(10, 16, 25, 0.96);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.35);
transition:
opacity 100ms ease,
transform 100ms ease;
}
.chart-tooltip.visible {
opacity: 1;
transform: translateY(0);
}
.tooltip-title {
margin-bottom: 6px;
color: #f4f8ff;
font-size: 11px;
font-weight: 700;
}
.tooltip-row {
display: flex;
justify-content: space-between;
gap: 16px;
margin-top: 3px;
color: var(--muted);
font-family: var(--mono);
font-size: 9px;
}
.tooltip-row strong {
color: #dbe6f5;
font-weight: 600;
}
.chart-footer {
min-height: 55px;
padding: 11px 16px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
border-top: 1px solid var(--line-soft);
color: var(--faint);
font-size: 10px;
}
.legend {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 7px;
white-space: nowrap;
}
.legend-mark {
width: 15px;
height: 3px;
border-radius: 2px;
background: currentColor;
}
.legend-mark.point {
width: 7px;
height: 7px;
border-radius: 50%;
}
.legend-pooled {
color: var(--coral);
}
.legend-a {
color: var(--cyan);
}
.legend-b {
color: var(--amber);
}
.legend-c {
color: var(--violet);
}
.interaction-hint {
font-family: var(--mono);
white-space: nowrap;
}
.selection-readout {
color: #a8b5c8;
font-family: var(--mono);
font-size: 10px;
min-height: 16px;
}
.sidebar {
display: grid;
gap: 14px;
}
.side-card {
padding: 17px;
}
.side-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 14px;
}
.side-title {
font-size: 12px;
font-weight: 750;
letter-spacing: 0.01em;
}
.side-kicker {
color: var(--faint);
font-family: var(--mono);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.reversal-chip {
padding: 5px 8px;
border: 1px solid rgba(255, 107, 107, 0.25);
border-radius: 999px;
background: rgba(255, 107, 107, 0.08);
color: #ffb1b1;
font-family: var(--mono);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.metric-box {
min-width: 0;
padding: 13px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(7, 12, 20, 0.45);
}
.metric-label {
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.metric-value {
margin-top: 8px;
font-family: var(--mono);
font-size: 28px;
font-weight: 700;
letter-spacing: -0.05em;
}
.metric-value.positive {
color: var(--coral);
}
.metric-value.negative {
color: var(--cyan);
}
.metric-detail {
margin-top: 4px;
color: var(--faint);
font-family: var(--mono);
font-size: 9px;
}
.slope-comparison {
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--line-soft);
}
.slope-row {
display: grid;
grid-template-columns: 54px 1fr;
align-items: center;
gap: 10px;
margin-top: 9px;
color: var(--muted);
font-size: 9px;
}
.slope-track {
position: relative;
height: 5px;
border-radius: 4px;
background:
linear-gradient(90deg, rgba(255, 255, 255, 0.025), rgba(255, 255, 255, 0.025))
center / 1px 100% no-repeat,
#151e2b;
}
.slope-track::after {
content: "";
position: absolute;
left: 50%;
top: -3px;
width: 1px;
height: 11px;
background: #64738a;
}
.slope-bar {
position: absolute;
top: 0;
height: 5px;
border-radius: 4px;
transition:
width 350ms ease,
left 350ms ease;
}
#pooledBar {
background: var(--coral);
box-shadow: 0 0 8px rgba(255, 107, 107, 0.35);
}
#withinBar {
background: var(--cyan);
box-shadow: 0 0 8px rgba(82, 224, 196, 0.35);
}
.narrative {
margin: 13px 0 0;
color: #aebacc;
font-size: 11px;
line-height: 1.6;
}
.narrative strong {
color: #e8f0fa;
font-weight: 650;
}
.reveal-button {
width: 100%;
margin-top: 14px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
text-align: left;
}
.reveal-button span:first-child {
font-size: 11px;
font-weight: 700;
}
.reveal-button span:last-child {
color: var(--cyan);
font-family: var(--mono);
font-size: 16px;
}
.dag {
position: relative;
margin: 4px 0 12px;
padding: 0 4px;
}
.dag-source {
width: 130px;
margin: 0 auto;
padding: 9px 10px;
border: 1px solid rgba(167, 139, 250, 0.35);
border-radius: 9px;
background: rgba(167, 139, 250, 0.08);
color: #d7ccff;
text-align: center;
font-size: 10px;
font-weight: 700;
}
.dag-stem {
width: 1px;
height: 22px;
margin: 0 auto;
background: rgba(167, 139, 250, 0.42);
}
.dag-branches {
position: relative;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 32px;
padding-top: 18px;
}
.dag-branches::before {
content: "";
position: absolute;
left: 25%;
right: 25%;
top: 0;
height: 1px;
background: rgba(167, 139, 250, 0.42);
}
.dag-node {
position: relative;
padding: 10px;
border: 1px solid var(--line);
border-radius: 9px;
background: #0b121d;
text-align: center;
font-family: var(--mono);
font-size: 9px;
color: #bdc9da;
}
.dag-node::before {
content: "";
position: absolute;
left: 50%;
top: -19px;
width: 1px;
height: 18px;
background: rgba(167, 139, 250, 0.42);
}
.dag-node span {
display: block;
margin-top: 3px;
color: var(--faint);
font-size: 8px;
}
.group-table {
width: 100%;
border-collapse: collapse;
font-family: var(--mono);
font-size: 9px;
}
.group-table th {
padding: 0 0 8px;
color: var(--faint);
font-family: var(--sans);
font-size: 8px;
font-weight: 600;
text-align: right;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.group-table th:first-child,
.group-table td:first-child {
text-align: left;
}
.group-table td {
padding: 9px 0;
border-top: 1px solid var(--line-soft);
color: #aebacc;
text-align: right;
}
.group-table td:first-child {
color: #e2eaf5;
}
.source-name {
display: inline-flex;
align-items: center;
gap: 7px;
}
.source-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--source-color);
box-shadow: 0 0 8px color-mix(in srgb, var(--source-color) 45%, transparent);
}
.caveat {
padding: 0 2px;
color: var(--faint);
font-size: 10px;
line-height: 1.55;
}
.caveat strong {
color: #9ca9bb;
}
.page-footer {
display: flex;
justify-content: space-between;
gap: 20px;
margin-top: 18px;
color: #536176;
font-family: var(--mono);
font-size: 9px;
}
@media (max-width: 1150px) {
.dashboard {
grid-template-columns: 1fr;
}
.sidebar {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.sidebar .wide-card {
grid-column: 1 / -1;
}
}
@media (max-width: 760px) {
.app-shell {
width: min(100% - 20px, 1540px);
}
.topbar {
height: 66px;
}
.status-chip,
.sample-chip {
display: none;
}
.intro {
display: block;
padding-top: 30px;
}
.intro-copy {
margin-top: 18px;
}
.visual-toolbar {
align-items: flex-start;
flex-direction: column;
}
.toolbar-controls {
width: 100%;
justify-content: space-between;
}
.segmented {
flex: 1;
}
.segment {
flex: 1;
padding: 0 8px;
}
.chart-stage {
height: 720px;
}
.chart-footer {
align-items: flex-start;
flex-direction: column;
}
.interaction-hint {
display: none;
}
.sidebar {
grid-template-columns: 1fr;
}
.sidebar .wide-card {
grid-column: auto;
}
.page-footer {
flex-direction: column;
gap: 6px;
}
}
</style>
</head>
<body>
<div class="app-shell">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<div class="brand-title">Hidden Structure Lab</div>
<div class="brand-subtitle">Synthetic association explorer</div>
</div>
</div>
<div class="top-actions">
<div class="sample-chip">
SAMPLE <span id="seedLabel">0137</span>
</div>
<div class="status-chip">
<span class="status-dot"></span>
3-source mixture
</div>
<button class="button" id="newSampleButton" type="button">New sample</button>
</div>
</header>
<main>
<section class="intro">
<div>
<p class="eyebrow">Grouping changes the conclusion</p>
<h1>A pooled line says one thing.<br />The groups say another.</h1>
</div>
<p class="intro-copy">
These synthetic observations were generated with a hidden source variable
that shifts <strong>both exposure and response</strong>. Pooling creates a
positive trend even though every within-source trend is negative.
</p>
</section>
<section class="dashboard">
<article class="card visual-card">
<div class="visual-toolbar">
<div class="visual-heading">
<div class="visual-title">Association landscape</div>
<div class="visual-meta" id="visualMeta">84 OBSERVATIONS · 3 LATENT SOURCES</div>
</div>
<div class="toolbar-controls">
<div class="segmented" aria-label="Chart view">
<button class="segment" data-mode="pooled" type="button">Pooled</button>
<button class="segment active" data-mode="compare" type="button">Compare</button>
<button class="segment" data-mode="grouped" type="button">Grouped</button>
</div>
<label class="check-control">
<input id="linesToggle" type="checkbox" checked />
Fit lines
</label>
<button class="button" id="resetButton" type="button">Reset view</button>
</div>
</div>
<div class="chart-stage" id="chartStage">
<div
class="chart-panel-label pooled-label"
id="pooledLabel"
>
<div class="panel-kicker">Pooled observation</div>
<div class="panel-name">One cloud, one fit</div>
<div class="panel-description" id="pooledDescription">
Source identity removed
</div>
</div>
<div
class="chart-panel-label grouped-label"
id="groupedLabel"
>
<div class="panel-kicker">Grouped observation</div>
<div class="panel-name">Source structure exposed</div>
<div class="panel-description" id="groupedDescription">
Three within-source fits
</div>
</div>
<div class="source-badge" id="sourceBadge">
3 latent sources exposed
</div>
<div class="compare-divider" id="compareDivider"></div>
<div class="chart-tooltip" id="chartTooltip">
<div class="tooltip-title" id="tooltipTitle"></div>
<div class="tooltip-row">
<span>Exposure</span>
<strong id="tooltipX"></strong>
</div>
<div class="tooltip-row">
<span>Response</span>
<strong id="tooltipY"></strong>
</div>
<div class="tooltip-row">
<span>Source</span>
<strong id="tooltipGroup"></strong>
</div>
</div>
</div>
<div class="chart-footer">
<div class="legend">
<div class="legend-item legend-pooled">
<span class="legend-mark"></span>
Pooled OLS
</div>
<div class="legend-item legend-a" id="sourceLegendA">
<span class="legend-mark"></span>
Source α
</div>
<div class="legend-item legend-b" id="sourceLegendB">
<span class="legend-mark"></span>
Source β
</div>
<div class="legend-item legend-c" id="sourceLegendC">
<span class="legend-mark"></span>
Source γ
</div>
</div>
<div class="selection-readout" id="selectionReadout">
Hover a point to inspect an observation.
</div>
<div class="interaction-hint">Drag to pan · Wheel to zoom · Double-click to reset</div>
</div>
</article>
<aside class="sidebar">
<article class="card side-card wide-card">
<div class="side-heading">
<div>
<div class="side-title">Association estimate</div>
<div class="side-kicker" style="margin-top: 4px">OLS slope · exposure → response</div>
</div>
<div class="reversal-chip">Sign reversed</div>
</div>
<div class="metric-grid">
<div class="metric-box">
<div class="metric-label">Pooled association</div>
<div class="metric-value positive" id="pooledSlope">+0.00</div>
<div class="metric-detail" id="pooledR2">R² = 0.00</div>
</div>
<div class="metric-box">
<div class="metric-label">Within-source association</div>
<div class="metric-value negative" id="withinSlope">−0.00</div>
<div class="metric-detail" id="withinR2">Mean R² = 0.00</div>
</div>
</div>
<div class="slope-comparison">
<div class="slope-row">
<span>Pooled</span>
<div class="slope-track">
<div class="slope-bar" id="pooledBar"></div>
</div>
</div>
<div class="slope-row">
<span>Within</span>
<div class="slope-track">
<div class="slope-bar" id="withinBar"></div>
</div>
</div>
</div>
<p class="narrative" id="narrative">
The pooled line points upward because it compares observations from
different source regimes. Within each regime, the relationship is downward.
</p>
<button class="button primary reveal-button" id="revealButton" type="button">
<span id="revealButtonText">Conceal source grouping</span>
<span aria-hidden="true">◉</span>
</button>
</article>
<article class="card side-card">
<div class="side-heading">
<div class="side-title">Hidden common cause</div>
<div class="side-kicker">DAG</div>
</div>
<div class="dag" aria-label="Latent source shifts both exposure and response">
<div class="dag-source">Latent source mix</div>
<div class="dag-stem"></div>
<div class="dag-branches">
<div class="dag-node">
EXPOSURE
<span>source-dependent shift</span>
</div>
<div class="dag-node">
RESPONSE
<span>source-dependent shift</span>
</div>
</div>
</div>
<p class="narrative">
Source composition affects both axes. Pooling therefore mixes a
<strong>between-source effect</strong> with the
<strong>within-source association</strong>.
</p>
</article>
<article class="card side-card wide-card">
<div class="side-heading">
<div class="side-title">Latent source diagnostics</div>
<div class="side-kicker" id="sourceCount">3 sources · 84 rows</div>
</div>
<table class="group-table">
<thead>
<tr>
<th>Source</th>
<th>n</th>
<th>x̄</th>
<th>ȳ</th>
<th>β</th>
</tr>
</thead>
<tbody id="groupTableBody"></tbody>
</table>
</article>
<div class="caveat wide-card">
<strong>Interpretation note:</strong> this is a synthetic demonstration of
composition bias, not evidence that grouping itself causes the reversal.
Observational source adjustment does not automatically identify causality.
</div>
</aside>
</section>
<footer class="page-footer">
<span>THREE.JS CORE · DIRECT CAMERA CONTROLS · DETERMINISTIC SYNTHETIC DATA</span>
<span>Keyboard: 1 pooled · 2 compare · 3 grouped · R reset</span>
</footer>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and synthetic data
// -------------------------------------------------------------------------
const COLORS = {
neutral: new THREE.Color("#aeb9c9"),
sourceA: new THREE.Color("#52e0c4"),
sourceB: new THREE.Color("#ffbd66"),
sourceC: new THREE.Color("#a78bfa"),
pooled: new THREE.Color("#ff6b6b")
};
const SOURCE_COLORS = [COLORS.sourceA, COLORS.sourceB, COLORS.sourceC];
const SOURCE_HEX = ["#52e0c4", "#ffbd66", "#a78bfa"];
const SOURCE_NAMES = ["Source α", "Source β", "Source γ"];
const SOURCE_GREEK = ["α", "β", "γ"];
const GROUP_SPECS = [
{
name: "Source α",
n: 32,
meanX: 2.8,
sdX: 0.84,
intercept: 4.9,
slope: -0.95,
noise: 0.82
},
{
name: "Source β",
n: 28,
meanX: 5.8,
sdX: 0.9,
intercept: 10.2,
slope: -0.78,
noise: 0.88
},
{
name: "Source γ",
n: 24,
meanX: 8.9,
sdX: 0.86,
intercept: 16.3,
slope: -0.88,
noise: 0.84
}
];
const PLOT = {
width: 10,
height: 9.5,
xMax: 12,
yMax: 9
};
const state = {
mode: "compare",
reveal: 1,
revealTarget: 1,
showLines: true,
seed: 137,
records: [],
groups: [],
stats: null,
width: 1,
height: 1,
rects: {
pooled: null,
grouped: null
},
drag: null
};
function mulberry32(seed) {
let a = seed >>> 0;
return function () {
a |= 0;
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function normalRandom(rng) {
let u = 0;
let v = 0;
while (u === 0) u = rng();
while (v === 0) v = rng();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function generateData(seed) {
const rng = mulberry32(seed);
const records = [];
const groups = [];
GROUP_SPECS.forEach((spec, groupIndex) => {
const groupRecords = [];
for (let i = 0; i < spec.n; i++) {
const x = clamp(
spec.meanX + normalRandom(rng) * spec.sdX,
0.45,
11.55
);
const y = clamp(
spec.intercept + spec.slope * x + normalRandom(rng) * spec.noise,
0.12,
8.92
);
const record = {
id: records.length + 1,
x,
y,
groupIndex
};
records.push(record);
groupRecords.push(record);
}
const fit = regression(
groupRecords.map((record) => record.x),
groupRecords.map((record) => record.y)
);
groups.push({
...spec,
records: groupRecords,
fit,
meanX: mean(groupRecords.map((record) => record.x)),
meanY: mean(groupRecords.map((record) => record.y))
});
});
const pooledFit = regression(
records.map((record) => record.x),
records.map((record) => record.y)
);
let withinCov = 0;
let withinVar = 0;
let weightedR2 = 0;
groups.forEach((group) => {
const xs = group.records.map((record) => record.x);
const ys = group.records.map((record) => record.y);
const mx = mean(xs);
const my = mean(ys);
let covariance = 0;
let variance = 0;
group.records.forEach((record) => {
covariance += (record.x - mx) * (record.y - my);
variance += (record.x - mx) ** 2;
});
withinCov += covariance;
withinVar += variance;
weightedR2 += group.fit.r2 * group.records.length;
});
const withinSlope = withinVar > 0 ? withinCov / withinVar : 0;
const withinMeanR2 = weightedR2 / records.length;
return {
records,
groups,
stats: {
pooledFit,
withinSlope,
withinMeanR2
}
};
}
function mean(values) {
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function regression(xs, ys) {
const mx = mean(xs);
const my = mean(ys);
let covariance = 0;
let varianceX = 0;
let varianceY = 0;
for (let i = 0; i < xs.length; i++) {
const dx = xs[i] - mx;
const dy = ys[i] - my;
covariance += dx * dy;
varianceX += dx * dx;
varianceY += dy * dy;
}
const slope = varianceX === 0 ? 0 : covariance / varianceX;
const intercept = my - slope * mx;
let residual = 0;
for (let i = 0; i < xs.length; i++) {
const predicted = intercept + slope * xs[i];
residual += (ys[i] - predicted) ** 2;
}
const total = varianceY;
const r2 = total === 0 ? 0 : 1 - residual / total;
const correlation =
varianceX === 0 || varianceY === 0
? 0
: covariance / Math.sqrt(varianceX * varianceY);
return { slope, intercept, r2, correlation };
}
function mapX(value) {
return (value / PLOT.xMax) * PLOT.width;
}
function mapY(value) {
return (value / PLOT.yMax) * PLOT.height;
}
function signed(value, digits = 2) {
const sign = value >= 0 ? "+" : "−";
return `${sign}${Math.abs(value).toFixed(digits)}`;
}
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const stage = document.getElementById("chartStage");
const tooltip = document.getElementById("chartTooltip");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.autoClear = false;
renderer.domElement.className = "chart-canvas";
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Interactive scatter plots comparing pooled and grouped associations"
);
stage.prepend(renderer.domElement);
function createPointTexture() {
const canvas = document.createElement("canvas");
canvas.width = 64;
canvas.height = 64;
const context = canvas.getContext("2d");
const gradient = context.createRadialGradient(
32,
32,
2,
32,
32,
30
);
gradient.addColorStop(0, "rgba(255,255,255,1)");
gradient.addColorStop(0.58, "rgba(255,255,255,0.96)");
gradient.addColorStop(0.78, "rgba(255,255,255,0.62)");
gradient.addColorStop(1, "rgba(255,255,255,0)");
context.fillStyle = gradient;
context.fillRect(0, 0, 64, 64);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
return texture;
}
const pointTexture = createPointTexture();
function createTextSprite(
text,
{
color = "#8492a6",
worldHeight = 0.28,
weight = 600,
fontSize = 38,
opacity = 1
} = {}
) {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
const font = `${weight} ${fontSize}px ui-sans-serif, system-ui, sans-serif`;
context.font = font;
const width = Math.ceil(context.measureText(text).width + 24);
const height = 64;
canvas.width = width;
canvas.height = height;
context.clearRect(0, 0, width, height);
context.font = font;
context.fillStyle = color;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, width / 2, height / 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
opacity,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(
worldHeight * (canvas.width / canvas.height),
worldHeight,
1
);
sprite.renderOrder = 30;
return sprite;
}
function createLine(points, color, opacity = 1, kind = "group") {
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity,
depthTest: false,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.renderOrder = 8;
line.userData.kind = kind;
return line;
}
function createChartView(kind) {
const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(-6, 6, 6, -6, 0.1, 100);
const target = new THREE.Vector3(5, 4.75, 0);
camera.position.set(target.x, target.y, 20);
camera.lookAt(target);
const view = {
kind,
scene,
camera,
target,
points: null,
fitLines: []
};
addAxes(scene);
return view;
}
function addAxes(scene) {
const gridMaterial = new THREE.LineBasicMaterial({
color: 0x334155,
transparent: true,
opacity: 0.26,
depthTest: false,
depthWrite: false
});
const axisMaterial = new THREE.LineBasicMaterial({
color: 0x526176,
transparent: true,
opacity: 0.62,
depthTest: false,
depthWrite: false
});
const xTicks = [0, 3, 6, 9, 12];
const yTicks = [0, 2, 4, 6, 8];
xTicks.forEach((tick) => {
const x = mapX(tick);
const line = createLine(
[
new THREE.Vector3(x, 0, -0.35),
new THREE.Vector3(x, PLOT.height, -0.35)
],
0x334155,
0.26,
"grid"
);
line.material = gridMaterial;
scene.add(line);
const label = createTextSprite(String(tick), {
color: "#69778b",
worldHeight: 0.23,
fontSize: 34
});
label.position.set(x, -0.28, 0.2);
scene.add(label);
});
yTicks.forEach((tick) => {
const y = mapY(tick);
const line = createLine(
[
new THREE.Vector3(0, y, -0.35),
new THREE.Vector3(PLOT.width, y, -0.35)
],
0x334155,
0.26,
"grid"
);
line.material = gridMaterial;
scene.add(line);
const label = createTextSprite(String(tick), {
color: "#69778b",
worldHeight: 0.23,
fontSize: 34
});
label.position.set(-0.25, y, 0.2);
scene.add(label);
});
const xAxis = createLine(
[
new THREE.Vector3(0, 0, -0.2),
new THREE.Vector3(PLOT.width, 0, -0.2)
],
0x526176,
0.62,
"axis"
);
xAxis.material = axisMaterial;
scene.add(xAxis);
const yAxis = createLine(
[
new THREE.Vector3(0, 0, -0.2),
new THREE.Vector3(0, PLOT.height, -0.2)
],
0x526176,
0.62,
"axis"
);
yAxis.material = axisMaterial;
scene.add(yAxis);
const topFrame = createLine(
[
new THREE.Vector3(0, PLOT.height, -0.3),
new THREE.Vector3(PLOT.width, PLOT.height, -0.3)
],
0x273447,
0.34,
"frame"
);
scene.add(topFrame);
const rightFrame = createLine(
[
new THREE.Vector3(PLOT.width, 0, -0.3),
new THREE.Vector3(PLOT.width, PLOT.height, -0.3)
],
0x273447,
0.34,
"frame"
);
scene.add(rightFrame);
const xTitle = createTextSprite("EXPOSURE INDEX", {
color: "#8290a4",
worldHeight: 0.28,
fontSize: 34
});
xTitle.position.set(5, -0.78, 0.2);
scene.add(xTitle);
const yTitle = createTextSprite("RESPONSE INDEX", {
color: "#8290a4",
worldHeight: 0.28,
fontSize: 34
});
yTitle.position.set(-0.84, PLOT.height / 2, 0.2);
yTitle.material.rotation = Math.PI / 2;
scene.add(yTitle);
}
const pooledView = createChartView("pooled");
const groupedView = createChartView("grouped");
function disposePoints(view) {
if (!view.points) return;
view.scene.remove(view.points);
view.points.geometry.dispose();
view.points.material.dispose();
view.points = null;
}
function replacePoints(view, records, grouped) {
disposePoints(view);
const positions = [];
const colors = [];
records.forEach((record, index) => {
positions.push(
mapX(record.x),
mapY(record.y),
0.18 + ((index % 7) - 3) * 0.008
);
const color = grouped ? SOURCE_COLORS[record.groupIndex] : COLORS.neutral;
colors.push(color.r, color.g, color.b);
});
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
const material = new THREE.PointsMaterial({
size: 8.7,
sizeAttenuation: false,
map: pointTexture,
alphaTest: 0.12,
transparent: true,
opacity: 0.96,
vertexColors: true,
depthTest: false,
depthWrite: false
});
const points = new THREE.Points(geometry, material);
points.renderOrder = 12;
points.userData.records = records;
points.userData.grouped = grouped;
view.points = points;
view.scene.add(points);
}
function clearFitLines(view) {
view.fitLines.forEach((line) => {
view.scene.remove(line);
line.geometry.dispose();
line.material.dispose();
});
view.fitLines = [];
}
function addRegressionLine(view, fit, xMin, xMax, color, kind) {
const startX = clamp(xMin, 0, PLOT.xMax);
const endX = clamp(xMax, 0, PLOT.xMax);
const points = [
new THREE.Vector3(
mapX(startX),
mapY(fit.intercept + fit.slope * startX),
0.42
),
new THREE.Vector3(
mapX(endX),
mapY(fit.intercept + fit.slope * endX),
0.42
)
];
const line = createLine(points, color, 1, kind);
view.fitLines.push(line);
view.scene.add(line);
}
function rebuildChartData() {
const { records, groups, stats } = state;
replacePoints(pooledView, records, false);
replacePoints(groupedView, records, true);
clearFitLines(pooledView);
clearFitLines(groupedView);
addRegressionLine(
pooledView,
stats.pooledFit,
0.35,
11.65,
COLORS.pooled,
"pooled"
);
groups.forEach((group) => {
const xs = group.records.map((record) => record.x);
addRegressionLine(
groupedView,
group.fit,
Math.min(...xs) - 0.12,
Math.max(...xs) + 0.12,
SOURCE_COLORS[group.records[0].groupIndex],
"group"
);
});
updateLineVisibility();
updateGroupedColors();
}
function updateGroupedColors() {
if (!groupedView.points) return;
const attribute = groupedView.points.geometry.getAttribute("color");
const records = groupedView.points.userData.records;
const mixed = new THREE.Color();
records.forEach((record, index) => {
mixed
.copy(COLORS.neutral)
.lerp(SOURCE_COLORS[record.groupIndex], state.reveal);
attribute.setXYZ(index, mixed.r, mixed.g, mixed.b);
});
attribute.needsUpdate = true;
}
function updateLineVisibility() {
pooledView.fitLines.forEach((line) => {
line.visible = state.showLines;
});
groupedView.fitLines.forEach((line) => {
line.visible = state.showLines && state.reveal > 0.005;
line.material.opacity = state.reveal;
});
}
// -------------------------------------------------------------------------
// Layout and camera controls
// -------------------------------------------------------------------------
const pooledLabel = document.getElementById("pooledLabel");
const groupedLabel = document.getElementById("groupedLabel");
const sourceBadge = document.getElementById("sourceBadge");
const compareDivider = document.getElementById("compareDivider");
function computeRects() {
const width = state.width;
const height = state.height;
if (state.mode === "pooled") {
state.rects.pooled = { x: 0, y: 0, width, height };
state.rects.grouped = null;
return;
}
if (state.mode === "grouped") {
state.rects.pooled = null;
state.rects.grouped = { x: 0, y: 0, width, height };
return;
}
if (width < 680) {
const half = Math.floor(height / 2);
state.rects.pooled = { x: 0, y: 0, width, height: half };
state.rects.grouped = {
x: 0,
y: half,
width,
height: height - half
};
} else {
const half = Math.floor(width / 2);
state.rects.pooled = { x: 0, y: 0, width: half, height };
state.rects.grouped = {
x: half,
y: 0,
width: width - half,
height
};
}
}
function fitCamera(view, aspect) {
const safeAspect = Math.max(0.2, aspect);
const baseHeight = Math.max(11.8, 11.8 / safeAspect);
view.camera.left = (-baseHeight * safeAspect) / 2;
view.camera.right = (baseHeight * safeAspect) / 2;
view.camera.top = baseHeight / 2;
view.camera.bottom = -baseHeight / 2;
view.camera.position.set(
view.target.x,
view.target.y,
20
);
view.camera.lookAt(view.target.x, view.target.y, 0);
view.camera.updateProjectionMatrix();
}
function updateCameraFits() {
if (state.rects.pooled) {
fitCamera(
pooledView,
state.rects.pooled.width / state.rects.pooled.height
);
}
if (state.rects.grouped) {
fitCamera(
groupedView,
state.rects.grouped.width / state.rects.grouped.height
);
}
}
function placeOverlays() {
const pooledRect = state.rects.pooled;
const groupedRect = state.rects.grouped;
pooledLabel.style.display = pooledRect ? "block" : "none";
groupedLabel.style.display = groupedRect ? "block" : "none";
sourceBadge.style.display = groupedRect ? "inline-flex" : "none";
if (pooledRect) {
pooledLabel.style.left = `${pooledRect.x + 16}px`;
pooledLabel.style.top = `${pooledRect.y + 14}px`;
}
if (groupedRect) {
groupedLabel.style.left = `${groupedRect.x + 16}px`;
groupedLabel.style.top = `${groupedRect.y + 14}px`;
sourceBadge.style.left = `${groupedRect.x + 17}px`;
sourceBadge.style.top = `${groupedRect.y + 84}px`;
}
const isCompare = state.mode === "compare";
compareDivider.style.display = isCompare ? "block" : "none";
if (isCompare) {
const vertical = state.width < 680;
Object.assign(compareDivider.style, {
left: vertical ? "14px" : `${Math.floor(state.width / 2)}px`,
top: vertical ? `${Math.floor(state.height / 2)}px` : "12px",
width: vertical ? `${state.width - 28}px` : "1px",
height: vertical ? "1px" : `${state.height - 24}px`
});
}
}
function resize() {
state.width = Math.max(1, stage.clientWidth);
state.height = Math.max(1, stage.clientHeight);
renderer.setSize(state.width, state.height, false);
computeRects();
updateCameraFits();
placeOverlays();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
function resetView(view = null) {
const views = view ? [view] : [pooledView, groupedView];
views.forEach((item) => {
item.target.set(5, 4.75, 0);
item.camera.zoom = 1;
item.camera.updateProjectionMatrix();
});
updateCameraFits();
}
function viewAt(clientX, clientY) {
const stageRect = stage.getBoundingClientRect();
const x = clientX - stageRect.left;
const y = clientY - stageRect.top;
if (
state.rects.pooled &&
x >= state.rects.pooled.x &&
x <= state.rects.pooled.x + state.rects.pooled.width &&
y >= state.rects.pooled.y &&
y <= state.rects.pooled.y + state.rects.pooled.height
) {
return { view: pooledView, rect: state.rects.pooled };
}
if (
state.rects.grouped &&
x >= state.rects.grouped.x &&
x <= state.rects.grouped.x + state.rects.grouped.width &&
y >= state.rects.grouped.y &&
y <= state.rects.grouped.y + state.rects.grouped.height
) {
return { view: groupedView, rect: state.rects.grouped };
}
return null;
}
renderer.domElement.addEventListener(
"wheel",
(event) => {
const hit = viewAt(event.clientX, event.clientY);
if (!hit) return;
event.preventDefault();
const camera = hit.view.camera;
camera.zoom = clamp(
camera.zoom * Math.exp(-event.deltaY * 0.0012),
0.75,
4.5
);
camera.updateProjectionMatrix();
},
{ passive: false }
);
renderer.domElement.addEventListener("pointerdown", (event) => {
const hit = viewAt(event.clientX, event.clientY);
if (!hit) return;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
state.drag = {
view: hit.view,
rect: hit.rect,
startX: event.clientX,
startY: event.clientY,
targetX: hit.view.target.x,
targetY: hit.view.target.y,
moved: false
};
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (state.drag) {
const dx = event.clientX - state.drag.startX;
const dy = event.clientY - state.drag.startY;
if (Math.abs(dx) + Math.abs(dy) > 3) {
state.drag.moved = true;
}
const camera = state.drag.view.camera;
const worldHeight =
(camera.top - camera.bottom) / camera.zoom;
const worldPerPixel =
worldHeight / state.drag.rect.height;
state.drag.view.target.x = clamp(
state.drag.targetX - dx * worldPerPixel,
1,
9
);
state.drag.view.target.y = clamp(
state.drag.targetY + dy * worldPerPixel,
0.5,
9
);
camera.position.set(
state.drag.view.target.x,
state.drag.view.target.y,
20
);
camera.lookAt(
state.drag.view.target.x,
state.drag.view.target.y,
0
);
hideTooltip();
return;
}
updateHover(event);
});
function endPointer(event) {
if (state.drag && !state.drag.moved) {
updateHover(event);
}
state.drag = null;
renderer.domElement.classList.remove("dragging");
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("dblclick", (event) => {
const hit = viewAt(event.clientX, event.clientY);
if (hit) resetView(hit.view);
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!state.drag) hideTooltip();
});
// -------------------------------------------------------------------------
// Hover inspection
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
raycaster.params.Points.threshold = 0.18;
function updateHover(event) {
const hit = viewAt(event.clientX, event.clientY);
if (!hit || !hit.view.points) {
hideTooltip();
return;
}
const rect = hit.rect;
const ndc = new THREE.Vector2(
((event.clientX - stage.getBoundingClientRect().left - rect.x) /
rect.width) *
2 -
1,
-(
((event.clientY - stage.getBoundingClientRect().top - rect.y) /
rect.height) *
2 -
1
)
);
raycaster.setFromCamera(ndc, hit.view.camera);
const intersections = raycaster.intersectObject(hit.view.points);
if (!intersections.length) {
hideTooltip();
return;
}
const index = intersections[0].index;
const record = hit.view.points.userData.records[index];
const grouped = hit.view.points.userData.grouped;
const sourceVisible = grouped && state.reveal > 0.5;
document.getElementById("tooltipTitle").textContent =
`Observation ${String(record.id).padStart(2, "0")}`;
document.getElementById("tooltipX").textContent = record.x.toFixed(2);
document.getElementById("tooltipY").textContent = record.y.toFixed(2);
document.getElementById("tooltipGroup").textContent = sourceVisible
? SOURCE_GREEK[record.groupIndex]
: "concealed";
document.getElementById("selectionReadout").textContent =
`Observation ${String(record.id).padStart(2, "0")} · ` +
`x ${record.x.toFixed(2)} · y ${record.y.toFixed(2)} · ` +
`source ${sourceVisible ? SOURCE_GREEK[record.groupIndex] : "hidden"}`;
const stageRect = stage.getBoundingClientRect();
let tooltipX = event.clientX - stageRect.left + 14;
let tooltipY = event.clientY - stageRect.top + 14;
const maxX = state.width - 195;
const maxY = state.height - 120;
tooltipX = clamp(tooltipX, 8, Math.max(8, maxX));
tooltipY = clamp(tooltipY, 8, Math.max(8, maxY));
tooltip.style.left = `${tooltipX}px`;
tooltip.style.top = `${tooltipY}px`;
tooltip.classList.add("visible");
}
function hideTooltip() {
tooltip.classList.remove("visible");
}
// -------------------------------------------------------------------------
// Statistics and UI
// -------------------------------------------------------------------------
function updateStatistics() {
const { pooledFit, withinSlope, withinMeanR2 } = state.stats;
const pooledSlope = document.getElementById("pooledSlope");
const withinSlopeElement = document.getElementById("withinSlope");
pooledSlope.textContent = signed(pooledFit.slope);
pooledSlope.className =
"metric-value " + (pooledFit.slope >= 0 ? "positive" : "negative");
withinSlopeElement.textContent = signed(withinSlope);
withinSlopeElement.className =
"metric-value " + (withinSlope >= 0 ? "positive" : "negative");
document.getElementById("pooledR2").textContent =
`R² = ${pooledFit.r2.toFixed(2)} · r = ${pooledFit.correlation.toFixed(2)}`;
document.getElementById("withinR2").textContent =
`Mean R² = ${withinMeanR2.toFixed(2)}`;
const maxMagnitude = Math.max(
1,
Math.abs(pooledFit.slope),
Math.abs(withinSlope)
);
const pooledWidth =
(Math.abs(pooledFit.slope) / maxMagnitude) * 48;
const withinWidth =
(Math.abs(withinSlope) / maxMagnitude) * 48;
const pooledBar = document.getElementById("pooledBar");
const withinBar = document.getElementById("withinBar");
pooledBar.style.width = `${pooledWidth}%`;
pooledBar.style.left =
pooledFit.slope >= 0 ? "50%" : `${50 - pooledWidth}%`;
withinBar.style.width = `${withinWidth}%`;
withinBar.style.left =
withinSlope >= 0 ? "50%" : `${50 - withinWidth}%`;
document.getElementById("pooledDescription").textContent =
`OLS β = ${signed(pooledFit.slope)} · source identity removed`;
document.getElementById("groupedDescription").textContent =
`Within-source β = ${signed(withinSlope)}`;
document.getElementById("seedLabel").textContent =
String(state.seed).padStart(4, "0");
document.getElementById("visualMeta").textContent =
`${state.records.length} OBSERVATIONS · 3 LATENT SOURCES`;
document.getElementById("sourceCount").textContent =
`3 sources · ${state.records.length} rows`;
const table = document.getElementById("groupTableBody");
table.innerHTML = state.groups
.map(
(group, index) => `
<tr>
<td>
<span class="source-name">
<span class="source-dot" style="--source-color:${SOURCE_HEX[index]}"></span>
${SOURCE_NAMES[index]}
</span>
</td>
<td>${group.records.length}</td>
<td>${group.meanX.toFixed(2)}</td>
<td>${group.meanY.toFixed(2)}</td>
<td>${signed(group.fit.slope)}</td>
</tr>
`
)
.join("");
}
function updateRevealUI() {
const isExposed = state.revealTarget > 0.5;
document.getElementById("revealButtonText").textContent = isExposed
? "Conceal source grouping"
: "Reveal source grouping";
sourceBadge.textContent = isExposed
? "3 latent sources exposed"
: "3 latent sources concealed";
sourceBadge.classList.toggle("concealed", !isExposed);
const legendOpacity = isExposed ? "1" : "0.35";
document.getElementById("sourceLegendA").style.opacity = legendOpacity;
document.getElementById("sourceLegendB").style.opacity = legendOpacity;
document.getElementById("sourceLegendC").style.opacity = legendOpacity;
document.getElementById("narrative").innerHTML = isExposed
? "The pooled line points upward because it compares observations from " +
"different source regimes. Within each regime, the relationship is downward."
: "Source colors and source-specific fits are concealed. The pooled cloud " +
"still carries the signature of a common source that shifts both variables.";
}
function setMode(mode) {
state.mode = mode;
document.querySelectorAll(".segment").forEach((button) => {
button.classList.toggle("active", button.dataset.mode === mode);
});
computeRects();
updateCameraFits();
placeOverlays();
hideTooltip();
}
function regenerate(seed) {
state.seed = seed >>> 0;
const generated = generateData(state.seed);
state.records = generated.records;
state.groups = generated.groups;
state.stats = generated.stats;
rebuildChartData();
updateStatistics();
}
document.querySelectorAll(".segment").forEach((button) => {
button.addEventListener("click", () => {
setMode(button.dataset.mode);
});
});
document.getElementById("revealButton").addEventListener("click", () => {
state.revealTarget = state.revealTarget > 0.5 ? 0 : 1;
if (state.revealTarget > 0.5 && state.mode === "pooled") {
setMode("compare");
}
updateRevealUI();
});
document.getElementById("linesToggle").addEventListener("change", (event) => {
state.showLines = event.target.checked;
updateLineVisibility();
});
document.getElementById("resetButton").addEventListener("click", () => {
resetView();
});
document.getElementById("newSampleButton").addEventListener("click", () => {
regenerate((state.seed + 101) >>> 0);
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.key === "1") setMode("pooled");
if (event.key === "2") setMode("compare");
if (event.key === "3") setMode("grouped");
if (event.key.toLowerCase() === "r") resetView();
});
// -------------------------------------------------------------------------
// Rendering
// -------------------------------------------------------------------------
function renderView(view, rect) {
if (!rect) return;
const bottom = state.height - rect.y - rect.height;
renderer.setViewport(rect.x, bottom, rect.width, rect.height);
renderer.setScissor(rect.x, bottom, rect.width, rect.height);
renderer.render(view.scene, view.camera);
}
function render() {
renderer.setScissorTest(false);
renderer.setViewport(0, 0, state.width, state.height);
renderer.setClearColor(0x000000, 0);
renderer.clear(true, true, true);
renderer.setScissorTest(true);
if (state.mode === "pooled") {
renderView(pooledView, state.rects.pooled);
} else if (state.mode === "grouped") {
renderView(groupedView, state.rects.grouped);
} else {
renderView(pooledView, state.rects.pooled);
renderView(groupedView, state.rects.grouped);
}
}
function animate() {
requestAnimationFrame(animate);
const difference = state.revealTarget - state.reveal;
if (Math.abs(difference) > 0.0005) {
state.reveal += difference * 0.09;
state.reveal = clamp(state.reveal, 0, 1);
updateGroupedColors();
updateLineVisibility();
}
render();
}
regenerate(state.seed);
updateRevealUI();
resize();
animate();
</script>
</body>
</html>
```