Prompt specification
Build or customize the Three.js 3D scene "Aggregation-weight exploration tool" 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: Aggregation-weight exploration tool
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/aggregation-weight-exploration-tool-x1836
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: aggregation-weight exploration tool. Let users change group proportions while holding within-group rates fixed; display when the aggregate ordering reverses and distinguish arithmetic reversal from a causal explanation. Return one self-contained HTML file.
Working Three.js Starter (aggregation-weight-exploration-tool-x1836):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light" />
<title>Weight Lab — Aggregation and Causal Reasoning</title>
<style>
:root {
--ink: #172520;
--muted: #64736c;
--paper: #fbfaf5;
--panel: rgba(251, 250, 245, 0.96);
--line: #d7ded6;
--low: #20b89a;
--high: #ff7b55;
--treatment: #315efb;
--control: #8a52d8;
--danger: #d94b43;
--success: #168566;
--shadow: 0 18px 50px rgba(37, 54, 45, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e8eee4;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#app {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
}
.app-header {
z-index: 20;
display: flex;
align-items: center;
justify-content: space-between;
min-height: 76px;
padding: 14px 24px;
border-bottom: 1px solid rgba(65, 83, 72, 0.12);
background: rgba(248, 249, 242, 0.9);
backdrop-filter: blur(14px);
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
position: relative;
width: 42px;
height: 42px;
flex: 0 0 auto;
border: 2px solid var(--ink);
border-radius: 12px;
transform: rotate(-6deg);
}
.brand-mark::before,
.brand-mark::after {
position: absolute;
bottom: 8px;
width: 8px;
border-radius: 2px 2px 0 0;
content: "";
}
.brand-mark::before {
left: 8px;
height: 14px;
background: var(--low);
}
.brand-mark::after {
right: 8px;
height: 23px;
background: var(--high);
}
.eyebrow {
margin: 0 0 2px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(20px, 2.3vw, 28px);
line-height: 1;
letter-spacing: -0.04em;
}
.locked-badge {
display: flex;
align-items: center;
gap: 8px;
padding: 9px 12px;
border: 1px solid #bfd5c9;
border-radius: 999px;
background: #edf7f1;
color: #28664f;
font-size: 12px;
font-weight: 750;
white-space: nowrap;
}
.locked-badge::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--success);
box-shadow: 0 0 0 4px rgba(22, 133, 102, 0.12);
content: "";
}
main {
display: grid;
grid-template-columns: minmax(0, 1fr) 430px;
min-height: 0;
flex: 1;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #e8eee4;
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
#labels {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.scene-label {
position: absolute;
z-index: 5;
transform: translate(-50%, -100%);
white-space: nowrap;
user-select: none;
}
.scene-label.aggregate {
display: flex;
align-items: baseline;
gap: 7px;
padding: 7px 10px;
border: 1px solid rgba(23, 37, 32, 0.13);
border-radius: 10px;
background: rgba(255, 255, 252, 0.92);
box-shadow: 0 7px 18px rgba(42, 57, 49, 0.12);
font-size: 11px;
font-weight: 700;
backdrop-filter: blur(8px);
}
.scene-label.aggregate strong {
font-size: 17px;
letter-spacing: -0.04em;
}
.scene-label.aggregate.treatment {
border-bottom: 3px solid var(--treatment);
}
.scene-label.aggregate.control {
border-bottom: 3px solid var(--control);
}
.scene-label.pin {
padding: 4px 7px;
border: 1px solid rgba(23, 37, 32, 0.12);
border-radius: 999px;
background: rgba(255, 255, 252, 0.85);
color: #3b4c44;
font-size: 10px;
font-weight: 800;
box-shadow: 0 4px 12px rgba(42, 57, 49, 0.08);
}
.scene-label.arm {
padding: 5px 9px;
border-radius: 7px;
background: rgba(23, 37, 32, 0.84);
color: white;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.scene-label.gap {
padding: 7px 11px;
border: 1px solid rgba(23, 37, 32, 0.12);
border-radius: 999px;
background: rgba(255, 255, 252, 0.94);
color: var(--success);
font-size: 12px;
font-weight: 850;
box-shadow: var(--shadow);
}
.scene-label.gap.reverse {
border-color: #e7a29b;
background: #fff0ed;
color: var(--danger);
}
.scene-heading,
.scene-state,
.legend,
.orbit-hint {
position: absolute;
z-index: 8;
}
.scene-heading {
top: 20px;
left: 22px;
max-width: 270px;
pointer-events: none;
}
.scene-heading strong {
display: block;
font-size: 14px;
letter-spacing: -0.01em;
}
.scene-heading span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 11px;
line-height: 1.35;
}
.scene-state {
top: 20px;
right: 22px;
max-width: 280px;
padding: 11px 13px;
border: 1px solid #b9d9ca;
border-radius: 12px;
background: rgba(240, 250, 245, 0.92);
box-shadow: 0 8px 24px rgba(42, 57, 49, 0.08);
backdrop-filter: blur(10px);
}
.scene-state.reverse {
border-color: #e6aaa3;
background: rgba(255, 241, 237, 0.94);
}
.scene-state.tie {
border-color: #d8c68d;
background: rgba(255, 250, 230, 0.94);
}
.scene-state strong {
display: block;
font-size: 11px;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.scene-state span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 11px;
line-height: 1.35;
}
.legend {
bottom: 20px;
left: 22px;
display: flex;
flex-wrap: wrap;
gap: 8px 13px;
max-width: 500px;
padding: 10px 12px;
border: 1px solid rgba(65, 83, 72, 0.12);
border-radius: 11px;
background: rgba(251, 250, 245, 0.83);
color: #53635b;
font-size: 10px;
backdrop-filter: blur(9px);
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
display: inline-block;
width: 9px;
height: 9px;
border-radius: 2px;
}
.swatch.low {
background: var(--low);
}
.swatch.high {
background: var(--high);
}
.swatch.treatment {
border-radius: 50%;
background: var(--treatment);
}
.swatch.control {
border-radius: 50%;
background: var(--control);
}
.swatch.pin {
width: 3px;
height: 13px;
border-radius: 2px;
background: #7d8c84;
}
.orbit-hint {
right: 22px;
bottom: 20px;
padding: 8px 10px;
border-radius: 9px;
background: rgba(23, 37, 32, 0.76);
color: rgba(255, 255, 255, 0.88);
font-size: 10px;
pointer-events: none;
}
aside {
z-index: 15;
min-height: 0;
overflow: hidden;
border-left: 1px solid rgba(65, 83, 72, 0.13);
background: var(--panel);
box-shadow: -12px 0 35px rgba(44, 60, 51, 0.08);
}
.panel-scroll {
height: 100%;
overflow-y: auto;
padding: 22px 22px 30px;
scrollbar-color: #c4cec6 transparent;
scrollbar-width: thin;
}
.panel-title {
margin: 0;
font-size: 22px;
letter-spacing: -0.04em;
}
.panel-intro {
margin: 7px 0 17px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.presets {
display: flex;
gap: 7px;
margin-bottom: 18px;
}
.preset {
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 9px;
background: white;
cursor: pointer;
font-size: 11px;
font-weight: 750;
transition: 140ms ease;
}
.preset:hover,
.preset.active {
border-color: #94aaa0;
background: #edf3ed;
}
.control-block {
padding: 14px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 252, 0.72);
}
.control-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.control-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
font-weight: 800;
}
.control-dot {
width: 9px;
height: 9px;
border-radius: 50%;
}
.control-dot.treatment {
background: var(--treatment);
}
.control-dot.control {
background: var(--control);
}
.control-value {
color: var(--ink);
font-size: 17px;
font-weight: 850;
letter-spacing: -0.03em;
}
.control-subtitle {
margin-top: 4px;
color: var(--muted);
font-size: 10px;
}
input[type="range"] {
width: 100%;
height: 25px;
margin: 8px 0 0;
accent-color: var(--treatment);
cursor: pointer;
}
#qInput {
accent-color: var(--control);
}
input[type="range"]:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.range-shell {
position: relative;
}
.threshold-marker {
position: absolute;
top: 3px;
left: 50%;
z-index: 2;
width: 0;
height: 18px;
border-left: 2px dashed var(--danger);
pointer-events: none;
}
.mix-strip {
display: flex;
width: 100%;
height: 8px;
overflow: hidden;
border-radius: 999px;
background: var(--high);
}
.mix-strip .low {
height: 100%;
background: var(--low);
transition: width 100ms ease;
}
.mix-legend {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: var(--muted);
font-size: 9px;
}
.match-control {
display: flex;
align-items: center;
gap: 8px;
margin: 13px 0 0;
color: #4e5f56;
font-size: 11px;
cursor: pointer;
user-select: none;
}
.match-control input {
width: 15px;
height: 15px;
accent-color: var(--success);
}
.section {
margin-top: 20px;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
}
.section-heading h2 {
margin: 0;
font-size: 13px;
letter-spacing: -0.01em;
}
.section-heading span {
color: var(--muted);
font-size: 10px;
}
.rate-table {
width: 100%;
overflow: hidden;
border: 1px solid var(--line);
border-collapse: separate;
border-spacing: 0;
border-radius: 12px;
background: rgba(255, 255, 252, 0.72);
font-size: 11px;
}
.rate-table th,
.rate-table td {
padding: 9px 8px;
border-bottom: 1px solid #e4e8e2;
text-align: right;
}
.rate-table th:first-child,
.rate-table td:first-child {
text-align: left;
}
.rate-table thead th {
background: #f0f3ed;
color: #6c7972;
font-size: 9px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.rate-table tbody tr:last-child td {
border-bottom: 0;
}
.group-name {
display: flex;
align-items: center;
gap: 7px;
font-weight: 750;
}
.group-dot {
width: 8px;
height: 8px;
border-radius: 2px;
}
.gap-positive {
color: var(--success);
font-weight: 800;
}
.status-card {
margin-top: 12px;
padding: 14px;
border: 1px solid #b9d9ca;
border-radius: 14px;
background: #eef8f2;
}
.status-card.reverse {
border-color: #e7aaa3;
background: #fff0ed;
}
.status-card.tie {
border-color: #d8c68d;
background: #fff9e8;
}
.status-kicker {
margin-bottom: 7px;
color: var(--success);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.reverse .status-kicker {
color: var(--danger);
}
.tie .status-kicker {
color: #8b6a12;
}
.status-card h3 {
margin: 0;
font-size: 15px;
letter-spacing: -0.02em;
}
.status-card p {
margin: 6px 0 0;
color: #526159;
font-size: 11px;
line-height: 1.45;
}
.aggregate-pair {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: end;
gap: 10px;
margin-top: 12px;
}
.aggregate-number {
padding: 10px;
border: 1px solid rgba(23, 37, 32, 0.09);
border-radius: 10px;
background: rgba(255, 255, 255, 0.64);
}
.aggregate-number span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.aggregate-number strong {
display: block;
margin-top: 2px;
font-size: 24px;
letter-spacing: -0.05em;
}
.aggregate-number.treatment strong {
color: var(--treatment);
}
.aggregate-number.control strong {
color: var(--control);
}
.versus {
padding-bottom: 9px;
color: #89958e;
font-size: 9px;
font-weight: 850;
text-transform: uppercase;
}
.threshold-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 10px;
padding-top: 9px;
border-top: 1px solid rgba(23, 37, 32, 0.09);
color: var(--muted);
font-size: 10px;
}
.threshold-row strong {
color: var(--ink);
text-align: right;
}
.callout {
margin-top: 12px;
padding: 14px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 252, 0.76);
}
.callout.arithmetic {
border-left: 4px solid var(--low);
}
.callout.causal {
border-left: 4px solid #e4a32f;
background: #fffaf0;
}
.callout-tag {
display: inline-block;
margin-bottom: 7px;
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.causal .callout-tag {
color: #9b6811;
}
.callout h3 {
margin: 0;
font-size: 14px;
letter-spacing: -0.02em;
}
.callout p {
margin: 6px 0 0;
color: #536159;
font-size: 11px;
line-height: 1.5;
}
.equation {
margin-top: 11px;
padding: 10px;
border-radius: 9px;
background: #f0f3ed;
color: #2e4037;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
font-weight: 750;
text-align: center;
}
.decomposition {
display: grid;
grid-template-columns: 1fr auto;
gap: 6px 12px;
margin-top: 10px;
font-size: 10px;
}
.decomposition span {
color: var(--muted);
}
.decomposition strong {
text-align: right;
}
.positive {
color: var(--success);
}
.negative {
color: var(--danger);
}
.causal ul {
margin: 9px 0 0;
padding-left: 17px;
color: #5d594b;
font-size: 10px;
line-height: 1.5;
}
.causal li + li {
margin-top: 4px;
}
details {
margin-top: 12px;
padding: 11px 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 252, 0.65);
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
summary {
color: var(--ink);
cursor: pointer;
font-weight: 800;
}
.formula {
margin-top: 8px;
color: #34483e;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.footnote {
margin: 15px 0 0;
color: #89958e;
font-size: 9px;
line-height: 1.45;
text-align: center;
}
@media (max-width: 1050px) {
main {
grid-template-columns: minmax(0, 1fr) 390px;
}
.scene-state {
max-width: 225px;
}
.scene-heading {
max-width: 210px;
}
}
@media (max-width: 820px) {
html,
body {
height: auto;
overflow: auto;
}
#app {
min-height: 100%;
height: auto;
}
.app-header {
min-height: 70px;
padding: 12px 15px;
}
.locked-badge {
padding: 8px 9px;
font-size: 10px;
}
main {
display: flex;
flex-direction: column;
}
#viewport {
height: 58vh;
min-height: 430px;
}
aside {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.panel-scroll {
height: auto;
overflow: visible;
}
.scene-label.pin {
display: none !important;
}
.scene-state {
top: 17px;
right: 15px;
max-width: 190px;
}
.scene-heading {
top: 17px;
left: 15px;
max-width: 180px;
}
.legend {
right: 15px;
bottom: 15px;
left: 15px;
}
.orbit-hint {
display: none;
}
}
@media (max-width: 480px) {
.brand-mark {
display: none;
}
.locked-badge {
max-width: 150px;
white-space: normal;
}
.scene-heading {
display: none;
}
.scene-state {
right: 10px;
left: 10px;
max-width: none;
}
.panel-scroll {
padding: 18px 14px 25px;
}
}
</style>
</head>
<body>
<div id="app">
<header class="app-header">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<p class="eyebrow">Aggregation / weights / causality</p>
<h1>Weight Lab</h1>
</div>
</div>
<div class="locked-badge">Within-group rates locked</div>
</header>
<main>
<section id="viewport" aria-label="Interactive three-dimensional aggregate rate scene">
<canvas id="scene"></canvas>
<div id="labels" aria-hidden="true">
<div id="labelT" class="scene-label aggregate treatment">
<span>Treatment aggregate</span><strong id="labelTValue">57.5%</strong>
</div>
<div id="labelC" class="scene-label aggregate control">
<span>Control aggregate</span><strong id="labelCValue">64.0%</strong>
</div>
<div id="labelTLow" class="scene-label pin">80% fixed</div>
<div id="labelTHigh" class="scene-label pin">50% fixed</div>
<div id="labelCLow" class="scene-label pin">70% fixed</div>
<div id="labelCHigh" class="scene-label pin">30% fixed</div>
<div id="labelTBase" class="scene-label arm">Treatment</div>
<div id="labelCBase" class="scene-label arm">Control</div>
<div id="labelGap" class="scene-label gap reverse">
Treatment − Control: −6.5 pp
</div>
</div>
<div class="scene-heading">
<strong>Weighted aggregate rates</strong>
<span>Stack height shows each group's contribution to the arm average.</span>
</div>
<div id="sceneState" class="scene-state reverse" aria-live="polite">
<strong>Aggregate ordering reversed</strong>
<span id="sceneStateText">Control is 6.5 pp higher in the aggregate.</span>
</div>
<div class="legend">
<span class="legend-item"><i class="swatch low"></i>Low-risk contribution</span>
<span class="legend-item"><i class="swatch high"></i>High-risk contribution</span>
<span class="legend-item"><i class="swatch treatment"></i>Treatment aggregate</span>
<span class="legend-item"><i class="swatch control"></i>Control aggregate</span>
<span class="legend-item"><i class="swatch pin"></i>Locked within-group rate</span>
</div>
<div class="orbit-hint">Drag to orbit · Wheel to zoom · Double-click to reset</div>
</section>
<aside aria-label="Controls and interpretation">
<div class="panel-scroll">
<h2 class="panel-title">Change the mix, not the rates</h2>
<p class="panel-intro">
Move the low-risk share within each arm. The four within-group outcome
rates stay fixed, so every change in the aggregate comes from weighting.
</p>
<div class="presets" aria-label="Example scenarios">
<button class="preset active" data-p="0.25" data-q="0.85" type="button">
Simpson reversal
</button>
<button class="preset" data-p="0.55" data-q="0.55" type="button">
Same mix
</button>
</div>
<div class="control-block">
<div class="control-head">
<div>
<div class="control-name">
<i class="control-dot treatment"></i>
Low-risk share in Treatment
</div>
<div class="control-subtitle">The remaining share is high-risk.</div>
</div>
<output id="pOutput" class="control-value" for="pInput">25%</output>
</div>
<input id="pInput" type="range" min="0" max="100" step="1" value="25" />
<div class="mix-strip" aria-hidden="true">
<span id="pLowFill" class="low" style="width: 25%"></span>
</div>
<div class="mix-legend">
<span>Low-risk</span>
<span>High-risk</span>
</div>
</div>
<div class="control-block" style="margin-top: 10px">
<div class="control-head">
<div>
<div class="control-name">
<i class="control-dot control"></i>
Low-risk share in Control
</div>
<div class="control-subtitle">
The dashed marker is the aggregate reversal threshold.
</div>
</div>
<output id="qOutput" class="control-value" for="qInput">85%</output>
</div>
<div class="range-shell">
<input id="qInput" type="range" min="0" max="100" step="1" value="85" />
<span id="qThreshold" class="threshold-marker" title="Aggregate tie threshold"></span>
</div>
<div class="mix-strip" aria-hidden="true">
<span id="qLowFill" class="low" style="width: 85%"></span>
</div>
<div class="mix-legend">
<span>Low-risk</span>
<span>High-risk</span>
</div>
<label class="match-control">
<input id="matchToggle" type="checkbox" />
Force both arms to use the same group mix
</label>
</div>
<section class="section">
<div class="section-heading">
<h2>Locked within-group rates</h2>
<span>These values never move</span>
</div>
<table class="rate-table">
<thead>
<tr>
<th>Group</th>
<th>Treatment</th>
<th>Control</th>
<th>Gap</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="group-name">
<i class="group-dot" style="background: var(--low)"></i>
Low-risk
</span>
</td>
<td>80%</td>
<td>70%</td>
<td class="gap-positive">+10</td>
</tr>
<tr>
<td>
<span class="group-name">
<i class="group-dot" style="background: var(--high)"></i>
High-risk
</span>
</td>
<td>50%</td>
<td>30%</td>
<td class="gap-positive">+20</td>
</tr>
</tbody>
</table>
<div id="statusCard" class="status-card reverse" aria-live="polite">
<div class="status-kicker" id="statusKicker">Aggregate ordering reversed</div>
<h3 id="statusTitle">Control now ranks above Treatment</h3>
<p id="statusCopy">
Treatment is better inside both groups, but its aggregate rate is lower.
</p>
<div class="aggregate-pair">
<div class="aggregate-number treatment">
<span>Treatment</span>
<strong id="aggTValue">57.5%</strong>
</div>
<div class="versus">vs</div>
<div class="aggregate-number control">
<span>Control</span>
<strong id="aggCValue">64.0%</strong>
</div>
</div>
<div class="threshold-row">
<span>First reversal point</span>
<strong id="thresholdValue">Control share > 68.8%</strong>
</div>
</div>
</section>
<div class="callout arithmetic">
<span class="callout-tag">Arithmetic explanation</span>
<h3>How the weighted averages reverse</h3>
<p id="arithmeticText">
Control's aggregate is 6.5 pp higher. Its much larger low-risk share
contributes −21.0 pp, outweighing the positive weighted within-group gap.
</p>
<div id="equation" class="equation">
D = (+14.5) + (−21.0) = −6.5 pp
</div>
<div class="decomposition">
<span>Weighted within-group gap</span>
<strong id="withinValue" class="positive">+14.5 pp</strong>
<span>Differential composition term</span>
<strong id="compositionValue" class="negative">−21.0 pp</strong>
</div>
</div>
<div class="callout causal">
<span class="callout-tag">Causal explanation</span>
<h3>A causal effect is not identified here</h3>
<p>
The reversal is an arithmetic consequence of comparing differently
composed groups. It does not show that Treatment causes worse outcomes.
Reweighting an observational table cannot, by itself, remove confounding.
</p>
<ul>
<li>Within-group gaps may reflect confounding unless assignment was randomized.</li>
<li>A causal claim needs a design, consistency, adequate overlap, and appropriate adjustment.</li>
<li>The weights are an analytic re-expression of the data—not an intervention on group membership.</li>
</ul>
</div>
<details>
<summary>Exact calculation</summary>
<div class="formula">
p = low-risk share in Treatment<br />
q = low-risk share in Control<br /><br />
A<sub>T</sub> = 0.80p + 0.50(1 − p)<br />
A<sub>C</sub> = 0.70q + 0.30(1 − q)<br /><br />
D = A<sub>T</sub> − A<sub>C</sub><br />
Tie threshold: q = 0.50 + 0.75p
</div>
<p style="margin-bottom: 0">
A symmetric decomposition uses m = (p + q)/2 and d = (p − q)/2:
D = m(10) + (1 − m)(20) + d(30 + 40), in percentage points.
</p>
</details>
<p class="footnote">
Educational demonstration · All calculations run locally in this file
</p>
</div>
</aside>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const rates = {
low: { treatment: 0.80, control: 0.70, gap: 0.10 },
high: { treatment: 0.50, control: 0.30, gap: 0.20 }
};
const state = {
p: 0.25,
q: 0.85,
matched: false
};
const pInput = $("pInput");
const qInput = $("qInput");
const matchToggle = $("matchToggle");
const fmtPercent = (value, decimals = 1) =>
`${(value * 100).toFixed(decimals).replace(/\.0$/, "")}%`;
const fmtPoints = (value, decimals = 1) => {
const points = value * 100;
const absolute = Math.abs(points).toFixed(decimals).replace(/\.0$/, "");
if (Math.abs(points) < 0.00005) return `0${decimals ? "" : ""} pp`;
return `${points > 0 ? "+" : "−"}${absolute} pp`;
};
function aggregateRates(p, q) {
const treatment = p * rates.low.treatment + (1 - p) * rates.high.treatment;
const control = q * rates.low.control + (1 - q) * rates.high.control;
const gap = treatment - control;
const m = (p + q) / 2;
const d = (p - q) / 2;
const withinTerm = m * rates.low.gap + (1 - m) * rates.high.gap;
const compositionTerm = d * (
(rates.low.treatment - rates.high.treatment) +
(rates.low.control - rates.high.control)
);
const thresholdQ = 0.50 + 0.75 * p;
return { treatment, control, gap, withinTerm, compositionTerm, thresholdQ };
}
function updateUI() {
const result = aggregateRates(state.p, state.q);
const reversed = result.gap < -0.00005;
const tied = Math.abs(result.gap) <= 0.00005;
pInput.value = Math.round(state.p * 100);
qInput.value = Math.round(state.q * 100);
qInput.disabled = state.matched;
$("pOutput").textContent = fmtPercent(state.p, 0);
$("qOutput").textContent = fmtPercent(state.q, 0);
$("pLowFill").style.width = `${state.p * 100}%`;
$("qLowFill").style.width = `${state.q * 100}%`;
$("aggTValue").textContent = fmtPercent(result.treatment);
$("aggCValue").textContent = fmtPercent(result.control);
$("labelTValue").textContent = fmtPercent(result.treatment);
$("labelCValue").textContent = fmtPercent(result.control);
const gapText = fmtPoints(result.gap);
$("labelGap").textContent = `Treatment − Control: ${gapText}`;
$("labelGap").classList.toggle("reverse", reversed);
const sceneState = $("sceneState");
sceneState.classList.toggle("reverse", reversed);
sceneState.classList.toggle("tie", tied);
const statusCard = $("statusCard");
statusCard.classList.toggle("reverse", reversed);
statusCard.classList.toggle("tie", tied);
if (reversed) {
$("sceneState").querySelector("strong").textContent = "Aggregate ordering reversed";
$("sceneStateText").textContent =
`Control is ${fmtPoints(Math.abs(result.gap))} higher in the aggregate.`;
$("statusKicker").textContent = "Aggregate ordering reversed";
$("statusTitle").textContent = "Control now ranks above Treatment";
$("statusCopy").textContent =
"Treatment is better inside both groups, but its aggregate rate is lower.";
$("arithmeticText").textContent =
`Control's aggregate is ${fmtPoints(Math.abs(result.gap))} higher. ` +
`Its larger low-risk share contributes ${fmtPoints(result.compositionTerm)}, ` +
`overpowering the ${fmtPoints(result.withinTerm)} weighted within-group gap.`;
} else if (tied) {
$("sceneState").querySelector("strong").textContent = "Aggregate tie";
$("sceneStateText").textContent = "The two weighted averages are equal.";
$("statusKicker").textContent = "Aggregate tie";
$("statusTitle").textContent = "The weighted averages are equal";
$("statusCopy").textContent =
"This is the exact boundary where the aggregate ordering changes.";
$("arithmeticText").textContent =
"The positive within-group gap and the negative composition term exactly cancel.";
} else {
$("sceneState").querySelector("strong").textContent = "No aggregate reversal";
$("sceneStateText").textContent =
`Treatment is ${fmtPoints(result.gap)} higher in the aggregate.`;
$("statusKicker").textContent = "Aggregate ordering preserved";
$("statusTitle").textContent = "Treatment ranks above Control";
$("statusCopy").textContent =
"The current group mix does not overturn the within-group ordering.";
$("arithmeticText").textContent =
`Treatment's aggregate is ${fmtPoints(result.gap)} higher. ` +
`The composition term is ${fmtPoints(result.compositionTerm)}, while the ` +
`weighted within-group gap remains ${fmtPoints(result.withinTerm)}.`;
}
$("equation").textContent =
`D = (${fmtPoints(result.withinTerm)}) + (${fmtPoints(result.compositionTerm)}) = ${fmtPoints(result.gap)}`;
$("withinValue").textContent = fmtPoints(result.withinTerm);
$("withinValue").className = result.withinTerm >= 0 ? "positive" : "negative";
$("compositionValue").textContent = fmtPoints(result.compositionTerm);
$("compositionValue").className = result.compositionTerm <= 0 ? "negative" : "positive";
if (result.thresholdQ <= 1) {
$("thresholdValue").textContent =
`Control share > ${fmtPercent(result.thresholdQ)}`;
$("qThreshold").style.display = "block";
$("qThreshold").style.left = `${result.thresholdQ * 100}%`;
$("qThreshold").title = `Aggregate tie at ${fmtPercent(result.thresholdQ)}`;
} else {
$("thresholdValue").textContent = "Not reachable with Treatment mix fixed";
$("qThreshold").style.display = "none";
}
document.querySelectorAll(".preset").forEach((button) => {
const buttonP = Number(button.dataset.p);
const buttonQ = Number(button.dataset.q);
const active =
Math.abs(buttonP - state.p) < 0.005 &&
Math.abs(buttonQ - state.q) < 0.005;
button.classList.toggle("active", active);
});
}
function setState(p, q, matched = false) {
state.p = Math.min(1, Math.max(0, p));
state.q = Math.min(1, Math.max(0, q));
state.matched = matched;
matchToggle.checked = matched;
if (matched) state.q = state.p;
updateUI();
}
pInput.addEventListener("input", () => {
state.p = Number(pInput.value) / 100;
if (state.matched) state.q = state.p;
updateUI();
});
qInput.addEventListener("input", () => {
state.q = Number(qInput.value) / 100;
updateUI();
});
matchToggle.addEventListener("change", () => {
state.matched = matchToggle.checked;
if (state.matched) state.q = state.p;
updateUI();
});
document.querySelectorAll(".preset").forEach((button) => {
button.addEventListener("click", () => {
setState(Number(button.dataset.p), Number(button.dataset.q), false);
});
});
updateUI();
// -------------------------------------------------------------------------
// Three.js core scene. No addons are used; camera controls are implemented
// directly with pointer and wheel events.
// -------------------------------------------------------------------------
const canvas = $("scene");
const viewport = $("viewport");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8eee4);
scene.fog = new THREE.Fog(0xe8eee4, 18, 34);
const camera = new THREE.PerspectiveCamera(37, 1, 0.1, 80);
const cameraTarget = new THREE.Vector3(0, 2.45, 0);
const cameraSpherical = new THREE.Spherical(15.2, 1.02, 0.53);
function resetCamera() {
cameraSpherical.radius = 15.2;
cameraSpherical.phi = 1.02;
cameraSpherical.theta = 0.53;
}
function updateCamera() {
const offset = new THREE.Vector3().setFromSpherical(cameraSpherical);
camera.position.copy(cameraTarget).add(offset);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xffffff, 0x6f806f, 2.2);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff7e8, 3.0);
keyLight.position.set(-6, 11, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xbdd8ff, 1.25);
rimLight.position.set(8, 6, -8);
scene.add(rimLight);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0xcfd9cb,
roughness: 0.95,
flatShading: true
});
const ground = new THREE.Mesh(
new THREE.CylinderGeometry(9.2, 9.8, 0.72, 6),
groundMaterial
);
ground.position.y = -0.4;
ground.receiveShadow = true;
scene.add(ground);
const groundTop = new THREE.Mesh(
new THREE.CylinderGeometry(8.95, 9.12, 0.08, 6),
new THREE.MeshStandardMaterial({
color: 0xe3e9dd,
roughness: 0.96,
flatShading: true
})
);
groundTop.position.y = 0.01;
groundTop.receiveShadow = true;
scene.add(groundTop);
const grid = new THREE.GridHelper(15, 15, 0xaebcaf, 0xc8d2c5);
grid.position.y = 0.065;
grid.material.transparent = true;
grid.material.opacity = 0.22;
scene.add(grid);
const treatmentX = -2.75;
const controlX = 2.75;
const baseY = 0.32;
const rateScale = 6;
function createPedestal(x) {
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(1.72, 1.9, 0.28, 6),
new THREE.MeshStandardMaterial({
color: 0xf1eee2,
roughness: 0.82,
flatShading: true
})
);
pedestal.position.set(x, 0.16, 0);
pedestal.receiveShadow = true;
pedestal.castShadow = true;
scene.add(pedestal);
}
createPedestal(treatmentX);
createPedestal(controlX);
function createSegment(color, x) {
const group = new THREE.Group();
const geometry = new THREE.CylinderGeometry(0.92, 0.92, 1, 6);
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.02,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: 0x17352d,
transparent: true,
opacity: 0.24
})
);
group.add(edges);
group.position.x = x;
scene.add(group);
return {
group,
targetHeight: 0,
targetY: baseY
};
}
const segments = {
treatmentLow: createSegment(0x20b89a, treatmentX),
treatmentHigh: createSegment(0xff7b55, treatmentX),
controlLow: createSegment(0x20b89a, controlX),
controlHigh: createSegment(0xff7b55, controlX)
};
function createMarker(color, x) {
const group = new THREE.Group();
const ring = new THREE.Mesh(
new THREE.TorusGeometry(1.08, 0.065, 6, 36),
new THREE.MeshBasicMaterial({ color })
);
ring.rotation.x = Math.PI / 2;
group.add(ring);
const cap = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
new THREE.MeshBasicMaterial({ color })
);
cap.position.y = 0.16;
group.add(cap);
group.position.set(x, baseY, 0);
scene.add(group);
return group;
}
const treatmentMarker = createMarker(0x315efb, treatmentX);
const controlMarker = createMarker(0x8a52d8, controlX);
function createFixedPin(color, x, z, height) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.75,
transparent: true,
opacity: 0.48,
depthWrite: false,
flatShading: true
});
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.095, 0.095, 1, 6),
material
);
group.add(post);
const cap = new THREE.Mesh(
new THREE.OctahedronGeometry(0.14, 0),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.7
})
);
cap.position.y = 0.5;
group.add(cap);
group.position.set(x, baseY + height / 2, z);
group.scale.y = height;
scene.add(group);
return {
group,
anchor: new THREE.Vector3(x, baseY + height + 0.28, z)
};
}
const fixedPins = {
treatmentLow: createFixedPin(
0x20b89a, treatmentX - 1.27, -0.78, rates.low.treatment * rateScale
),
treatmentHigh: createFixedPin(
0xff7b55, treatmentX + 1.27, -0.78, rates.high.treatment * rateScale
),
controlLow: createFixedPin(
0x20b89a, controlX - 1.27, -0.78, rates.low.control * rateScale
),
controlHigh: createFixedPin(
0xff7b55, controlX + 1.27, -0.78, rates.high.control * rateScale
)
};
const comparisonGeometry = new THREE.BufferGeometry();
comparisonGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(6), 3)
);
const comparisonMaterial = new THREE.LineBasicMaterial({
color: 0xd94b43,
transparent: true,
opacity: 0.9
});
const comparisonLine = new THREE.Line(
comparisonGeometry,
comparisonMaterial
);
scene.add(comparisonLine);
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.15, 0.4, 6),
new THREE.MeshBasicMaterial({ color: 0xd94b43 })
);
scene.add(arrow);
// A few restrained faceted objects make the scene feel spatial without
// distracting from the comparison.
const decorationMaterialA = new THREE.MeshStandardMaterial({
color: 0xa8c4b4,
roughness: 0.9,
flatShading: true
});
const decorationMaterialB = new THREE.MeshStandardMaterial({
color: 0xe8b38e,
roughness: 0.9,
flatShading: true
});
const decorations = [
{ x: -6.1, z: -3.2, s: 0.65, material: decorationMaterialA },
{ x: 5.9, z: -3.5, s: 0.8, material: decorationMaterialB },
{ x: 6.5, z: 2.0, s: 0.42, material: decorationMaterialA }
];
decorations.forEach((item) => {
const mesh = new THREE.Mesh(
new THREE.IcosahedronGeometry(item.s, 0),
item.material
);
mesh.position.set(item.x, item.s * 0.72, item.z);
mesh.rotation.set(0.3, 0.5, -0.15);
mesh.castShadow = true;
scene.add(mesh);
});
const visual = { p: state.p, q: state.q };
function damp(current, target, speed, dt) {
return current + (target - current) * (1 - Math.exp(-speed * dt));
}
function updateBars(dt, immediate = false) {
const p = visual.p;
const q = visual.q;
const treatmentHighHeight = (1 - p) * rates.high.treatment * rateScale;
const treatmentLowHeight = p * rates.low.treatment * rateScale;
const controlHighHeight = (1 - q) * rates.high.control * rateScale;
const controlLowHeight = q * rates.low.control * rateScale;
function setSegment(segment, height, bottom) {
const factor = immediate ? 1 : 1 - Math.exp(-13 * dt);
segment.group.scale.y += (height - segment.group.scale.y) * factor;
const targetY = bottom + height / 2;
segment.group.position.y += (targetY - segment.group.position.y) * factor;
segment.group.visible = segment.group.scale.y > 0.004;
}
setSegment(segments.treatmentHigh, treatmentHighHeight, baseY);
setSegment(
segments.treatmentLow,
treatmentLowHeight,
baseY + treatmentHighHeight
);
setSegment(segments.controlHigh, controlHighHeight, baseY);
setSegment(
segments.controlLow,
controlLowHeight,
baseY + controlHighHeight
);
const treatmentAggregateY =
baseY +
(p * rates.low.treatment + (1 - p) * rates.high.treatment) * rateScale;
const controlAggregateY =
baseY +
(q * rates.low.control + (1 - q) * rates.high.control) * rateScale;
const markerFactor = immediate ? 1 : 1 - Math.exp(-13 * dt);
treatmentMarker.position.y +=
(treatmentAggregateY - treatmentMarker.position.y) * markerFactor;
controlMarker.position.y +=
(controlAggregateY - controlMarker.position.y) * markerFactor;
const start = new THREE.Vector3(
treatmentX,
treatmentMarker.position.y,
1.03
);
const end = new THREE.Vector3(
controlX,
controlMarker.position.y,
1.03
);
const positionAttribute = comparisonGeometry.getAttribute("position");
positionAttribute.setXYZ(0, start.x, start.y, start.z);
positionAttribute.setXYZ(1, end.x, end.y, end.z);
positionAttribute.needsUpdate = true;
comparisonGeometry.computeBoundingSphere();
const direction = end.clone().sub(start);
const arrowLength = direction.length();
if (arrowLength > 0.001) {
arrow.visible = true;
arrow.position.copy(end);
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
} else {
arrow.visible = false;
}
const result = aggregateRates(state.p, state.q);
const reversed = result.gap < -0.00005;
comparisonMaterial.color.set(reversed ? 0xd94b43 : 0x168566);
arrow.material.color.set(reversed ? 0xd94b43 : 0x168566);
}
function projectLabel(element, position) {
const projected = position.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.display = visible ? "" : "none";
if (!visible) return;
const width = viewport.clientWidth;
const height = viewport.clientHeight;
element.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
}
function updateLabels() {
projectLabel(
$("labelT"),
new THREE.Vector3(treatmentX, treatmentMarker.position.y + 0.52, 0.05)
);
projectLabel(
$("labelC"),
new THREE.Vector3(controlX, controlMarker.position.y + 0.52, 0.05)
);
projectLabel($("labelTLow"), fixedPins.treatmentLow.anchor);
projectLabel($("labelTHigh"), fixedPins.treatmentHigh.anchor);
projectLabel($("labelCLow"), fixedPins.controlLow.anchor);
projectLabel($("labelCHigh"), fixedPins.controlHigh.anchor);
projectLabel(
$("labelTBase"),
new THREE.Vector3(treatmentX, 0.34, 1.7)
);
projectLabel(
$("labelCBase"),
new THREE.Vector3(controlX, 0.34, 1.7)
);
const gapAnchor = new THREE.Vector3(
(treatmentX + controlX) / 2,
(treatmentMarker.position.y + controlMarker.position.y) / 2 + 0.55,
1.25
);
projectLabel($("labelGap"), gapAnchor);
}
function resizeRenderer() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(viewport);
resizeRenderer();
// Direct camera controls: orbit, zoom, and reset.
let dragging = false;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraSpherical.theta -= deltaX * 0.007;
cameraSpherical.phi = THREE.MathUtils.clamp(
cameraSpherical.phi - deltaY * 0.006,
0.43,
1.38
);
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraSpherical.radius = THREE.MathUtils.clamp(
cameraSpherical.radius * Math.exp(event.deltaY * 0.001),
9.5,
23
);
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
visual.p = damp(visual.p, state.p, 10, dt);
visual.q = damp(visual.q, state.q, 10, dt);
updateCamera();
updateBars(dt);
updateLabels();
renderer.render(scene, camera);
}
updateBars(0, true);
animate();
</script>
</body>
</html>
```