Prompt specification
Build or customize the Three.js 3D scene "Binomial assumption explorer" 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: Binomial assumption explorer
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/binomial-assumption-explorer-x1772
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing binomial counts from repeated independent trials. Compare the exact independent model with a clearly defined correlated toy alternative; show how the count distribution changes and explain why identical marginal probabilities are insufficient. Low-poly.
Working Three.js Starter (binomial-assumption-explorer-x1772):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Same Margins, Different Counts</title>
<style>
:root {
color-scheme: dark;
--bg: #071119;
--panel: #0c1b25;
--panel-2: #10232e;
--line: #213946;
--text: #eaf5f5;
--muted: #91aab4;
--cyan: #56dfce;
--cyan-dark: #174b49;
--orange: #ff925d;
--orange-dark: #512b25;
--yellow: #f5d477;
}
* {
box-sizing: border-box;
}
html {
min-width: 320px;
background: var(--bg);
}
body {
min-height: 100vh;
margin: 0;
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
background:
radial-gradient(circle at 12% 0%, rgba(52, 156, 151, 0.13), transparent 29rem),
radial-gradient(circle at 90% 16%, rgba(255, 132, 79, 0.10), transparent 26rem),
var(--bg);
}
button,
input {
font: inherit;
}
button {
cursor: pointer;
}
.app {
width: min(1500px, 100%);
margin: 0 auto;
padding: 28px;
}
header {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 28px;
align-items: end;
margin-bottom: 22px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 10px;
color: var(--cyan);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 9px;
height: 9px;
content: "";
background: var(--cyan);
clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);
box-shadow: 0 0 16px rgba(86, 223, 206, 0.8);
}
h1 {
max-width: 780px;
margin: 0;
font-size: clamp(2.25rem, 5vw, 4.8rem);
font-weight: 780;
line-height: 0.98;
letter-spacing: -0.055em;
}
h1 em {
color: var(--cyan);
font-style: normal;
}
.intro {
max-width: 760px;
margin: 17px 0 0;
color: var(--muted);
font-size: clamp(0.95rem, 1.3vw, 1.08rem);
line-height: 1.65;
}
.control-deck {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 13px 17px;
min-width: 390px;
padding: 17px;
border: 1px solid var(--line);
background: rgba(12, 27, 37, 0.86);
clip-path: polygon(
0 0,
calc(100% - 14px) 0,
100% 14px,
100% 100%,
14px 100%,
0 calc(100% - 14px)
);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.18);
}
.control {
min-width: 0;
}
.control-label {
display: flex;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
color: var(--muted);
font-size: 0.75rem;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.control-label output {
color: var(--text);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 0;
border-radius: 10px;
accent-color: var(--cyan);
cursor: ew-resize;
}
.button-row {
grid-column: 1 / -1;
display: flex;
gap: 8px;
}
button {
min-height: 40px;
padding: 9px 13px;
border: 1px solid #31505e;
border-radius: 5px;
color: var(--text);
background: #112733;
font-size: 0.79rem;
font-weight: 750;
transition:
border-color 140ms ease,
background 140ms ease,
transform 140ms ease;
}
button:hover {
border-color: var(--cyan);
background: #16343e;
}
button:active {
transform: translateY(1px);
}
button.primary {
flex: 1;
border-color: var(--cyan);
color: #06201e;
background: var(--cyan);
}
button.primary:hover {
background: #7ce9dc;
}
main {
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
gap: 18px;
align-items: start;
}
.viewport-card,
.side-card {
border: 1px solid var(--line);
background: rgba(10, 24, 33, 0.9);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.2);
}
.viewport-card {
overflow: hidden;
}
.toolbar {
display: flex;
justify-content: space-between;
gap: 15px;
align-items: center;
min-height: 55px;
padding: 11px 15px;
border-bottom: 1px solid var(--line);
background: #0b1a23;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 10px 17px;
align-items: center;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 7px;
color: #c6d6db;
font-size: 0.74rem;
font-weight: 700;
}
.swatch {
width: 11px;
height: 11px;
background: var(--cyan);
clip-path: polygon(25% 0, 75% 0, 100% 25%, 100% 75%, 75% 100%, 25% 100%, 0 75%, 0 25%);
}
.swatch.orange {
background: var(--orange);
}
.scene-hint {
color: #6f8994;
font-size: 0.68rem;
white-space: nowrap;
}
#stage {
position: relative;
height: clamp(470px, 61vh, 690px);
min-height: 430px;
overflow: hidden;
background: #08151e;
}
#stage canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#stage canvas.dragging {
cursor: grabbing;
}
.scale-badge {
position: absolute;
top: 14px;
right: 15px;
z-index: 2;
padding: 7px 9px;
border: 1px solid rgba(110, 143, 154, 0.28);
color: #91aab4;
background: rgba(5, 14, 20, 0.68);
font-size: 0.62rem;
font-weight: 750;
letter-spacing: 0.09em;
pointer-events: none;
}
.chart-caption {
position: absolute;
bottom: 13px;
left: 15px;
z-index: 2;
max-width: 230px;
color: #79939d;
font-size: 0.68rem;
line-height: 1.45;
pointer-events: none;
}
#tooltip {
position: absolute;
z-index: 5;
width: 205px;
padding: 11px 12px;
border: 1px solid #365563;
border-radius: 5px;
color: #dbe9ec;
background: rgba(7, 18, 25, 0.96);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.32);
font-size: 0.72rem;
line-height: 1.55;
pointer-events: none;
}
#tooltip[hidden] {
display: none;
}
#tooltip .tip-model {
display: block;
margin-bottom: 3px;
font-weight: 800;
}
#tooltip .tip-value {
display: block;
margin-top: 4px;
color: white;
font-size: 1.1rem;
font-weight: 800;
}
.draw-strip {
display: grid;
gap: 8px;
padding: 14px 15px 16px;
border-top: 1px solid var(--line);
background: #0b1922;
}
.draw-row {
display: grid;
grid-template-columns: 132px minmax(0, 1fr) 44px;
gap: 11px;
align-items: center;
}
.draw-name {
color: #a8bdc5;
font-size: 0.69rem;
font-weight: 750;
line-height: 1.35;
}
.draw-name strong {
display: block;
margin-bottom: 2px;
color: var(--cyan);
font-size: 0.72rem;
}
.draw-row.correlated .draw-name strong {
color: var(--orange);
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 4px;
min-height: 18px;
}
.trial {
width: 13px;
height: 13px;
flex: 0 0 auto;
background: #263a45;
clip-path: polygon(25% 0, 75% 0, 100% 25%, 100% 75%, 75% 100%, 25% 100%, 0 75%, 0 25%);
animation: chip-in 240ms ease-out both;
animation-delay: var(--delay, 0ms);
}
.trial.on {
background: var(--cyan);
box-shadow: 0 0 8px rgba(86, 223, 206, 0.22);
}
.draw-row.correlated .trial.on {
background: var(--orange);
box-shadow: 0 0 8px rgba(255, 146, 93, 0.22);
}
.draw-count {
padding: 4px 5px;
border: 1px solid #29424e;
color: #e7f2f3;
background: #10232d;
text-align: center;
font-size: 0.72rem;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
@keyframes chip-in {
from {
opacity: 0;
transform: scale(0.35) rotate(12deg);
}
to {
opacity: 1;
transform: scale(1) rotate(0);
}
}
aside {
display: grid;
gap: 12px;
}
.side-card {
padding: 17px;
}
.side-card h2 {
margin: 0 0 10px;
font-size: 0.94rem;
letter-spacing: -0.01em;
}
.side-card p {
margin: 0;
color: var(--muted);
font-size: 0.79rem;
line-height: 1.62;
}
.model-tag {
display: inline-block;
margin-bottom: 9px;
padding: 4px 7px;
border: 1px solid rgba(86, 223, 206, 0.35);
color: var(--cyan);
background: rgba(86, 223, 206, 0.08);
font-size: 0.61rem;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.model-tag.orange {
border-color: rgba(255, 146, 93, 0.38);
color: var(--orange);
background: rgba(255, 146, 93, 0.08);
}
.equation {
margin-top: 11px !important;
padding: 10px;
border-left: 2px solid var(--cyan);
color: #d9eeee !important;
background: #0a2028;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.72rem !important;
line-height: 1.65 !important;
overflow-wrap: anywhere;
}
.correlated-card .equation {
border-left-color: var(--orange);
}
.marginal-bridge {
padding: 15px;
border: 1px solid #35505a;
background:
linear-gradient(135deg, rgba(86, 223, 206, 0.08), transparent 45%),
linear-gradient(315deg, rgba(255, 146, 93, 0.08), transparent 45%),
#0d1c25;
text-align: center;
}
.marginal-bridge span {
display: block;
color: #7f9aa5;
font-size: 0.61rem;
font-weight: 800;
letter-spacing: 0.13em;
}
.marginal-bridge strong {
display: block;
margin: 7px 0 2px;
color: #f1f9f9;
font-size: 1.22rem;
}
.marginal-bridge small {
color: var(--muted);
font-size: 0.68rem;
}
.key-point {
margin-top: 12px !important;
padding-left: 12px;
border-left: 2px solid var(--yellow);
color: #dce5df !important;
}
table {
width: 100%;
margin-top: 13px;
border-collapse: collapse;
font-size: 0.69rem;
font-variant-numeric: tabular-nums;
}
th,
td {
padding: 8px 5px;
border-bottom: 1px solid #1c333e;
text-align: right;
}
th:first-child,
td:first-child {
padding-left: 0;
text-align: left;
}
th {
color: #7f9aa5;
font-size: 0.61rem;
letter-spacing: 0.07em;
text-transform: uppercase;
}
td {
color: #cddcdf;
}
td:nth-child(2) {
color: var(--cyan);
}
td:nth-child(3) {
color: var(--orange);
}
.footnote {
margin-top: 8px !important;
color: #718d98 !important;
font-size: 0.69rem !important;
}
footer {
padding: 17px 2px 0;
color: #617b86;
font-size: 0.68rem;
line-height: 1.55;
}
@media (max-width: 1120px) {
header {
grid-template-columns: 1fr;
}
.control-deck {
width: min(100%, 520px);
}
main {
grid-template-columns: 1fr;
}
aside {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.marginal-bridge {
grid-column: 1 / -1;
grid-row: 1;
}
}
@media (max-width: 680px) {
.app {
padding: 15px 11px;
}
header {
gap: 19px;
}
h1 {
font-size: clamp(2.2rem, 13vw, 3.7rem);
}
.control-deck {
min-width: 0;
}
.toolbar {
align-items: flex-start;
flex-direction: column;
}
#stage {
height: 510px;
}
.draw-row {
grid-template-columns: 105px minmax(0, 1fr) 38px;
gap: 7px;
}
.draw-name {
font-size: 0.62rem;
}
aside {
grid-template-columns: 1fr;
}
.marginal-bridge {
grid-column: auto;
grid-row: auto;
}
}
@media (prefers-reduced-motion: reduce) {
.trial {
animation: none;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div>
<div class="eyebrow">Three.js probability lab</div>
<h1>Same marginals.<br /><em>Different counts.</em></h1>
<p class="intro">
An exact independent Bernoulli model and a deliberately correlated toy
model give every trial the same success probability. Watch their count
distributions separate: matching one-trial probabilities does not
specify how trials depend on one another.
</p>
</div>
<div class="control-deck" aria-label="Model controls">
<label class="control">
<span class="control-label">
Trials <output id="nOutput">20</output>
</span>
<input id="nInput" type="range" min="8" max="36" step="1" value="20" />
</label>
<label class="control">
<span class="control-label">
Marginal p <output id="pOutput">0.50</output>
</span>
<input id="pInput" type="range" min="0.05" max="0.95" step="0.05" value="0.5" />
</label>
<div class="button-row">
<button id="drawButton" class="primary" type="button">New paired draw</button>
<button id="playButton" type="button" aria-pressed="false">▶ Play</button>
<button id="resetButton" type="button">Reset view</button>
</div>
</div>
</header>
<main>
<section class="viewport-card" aria-label="Interactive count distribution comparison">
<div class="toolbar">
<div class="legend">
<span class="legend-item">
<span class="swatch"></span>
Exact independent binomial
</span>
<span class="legend-item">
<span class="swatch orange"></span>
Correlated shared-switch toy
</span>
</div>
<span class="scene-hint">Drag to orbit · wheel to zoom · hover a column</span>
</div>
<div id="stage">
<div class="scale-badge">COMMON LINEAR PROBABILITY SCALE</div>
<div class="chart-caption">
Five-sided columns use flat shading. Both distributions use the same
vertical probability axis.
</div>
<div id="tooltip" hidden></div>
</div>
<div class="draw-strip">
<div class="draw-row">
<div class="draw-name">
<strong>Independent draw</strong>
One Bernoulli trial per position
</div>
<div id="independentChips" class="chips"></div>
<div id="independentCount" class="draw-count">—</div>
</div>
<div class="draw-row correlated">
<div class="draw-name">
<strong>Correlated draw</strong>
All positions share one switch
</div>
<div id="correlatedChips" class="chips"></div>
<div id="correlatedCount" class="draw-count">—</div>
</div>
</div>
</section>
<aside>
<section class="side-card">
<span class="model-tag">Model 1 · exact</span>
<h2>Independent Bernoulli trials</h2>
<p>
For each trial, <strong>Y<sub>i</sub> ~ Bernoulli(p)</strong>, and the
trials are mutually independent. The number of successes
<strong>S = ΣY<sub>i</sub></strong> therefore has an exact binomial
distribution.
</p>
<p class="equation">
P(S = k) = C(n,k) · p<sup>k</sup> · (1−p)<sup>n−k</sup>
</p>
</section>
<section class="marginal-bridge">
<span>ONE-TRIAL MARGINAL</span>
<strong>P(Y<sub>i</sub> = 1) = p</strong>
<small>Exactly the same in both models</small>
</section>
<section class="side-card correlated-card">
<span class="model-tag orange">Model 2 · correlated toy</span>
<h2>One shared Bernoulli switch</h2>
<p>
Draw a single <strong>Z ~ Bernoulli(p)</strong>, then set
<strong>Y<sub>i</sub> = Z</strong> for every trial. Every individual
trial still succeeds with probability p, but all outcomes always move
together.
</p>
<p class="equation">
S = nZ<br />
P(S = 0) = 1−p, P(S = n) = p<br />
P(S = k) = 0 for 0 < k < n
</p>
</section>
<section class="side-card">
<h2>Why identical marginals are insufficient</h2>
<p>
A marginal probability describes one trial in isolation. A count
depends on the <strong>joint probability law</strong>—how all trial
outcomes occur together. Independence supplies the factorization that
produces the binomial law; the toy model deliberately replaces it
with perfect dependence.
</p>
<p class="key-point">
The means can match while the distributions do not. Knowing
<strong>E[S]</strong> is also not enough: compare the variances.
</p>
<table aria-label="Comparison statistics">
<thead>
<tr>
<th>Quantity</th>
<th>Independent</th>
<th>Correlated</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mean count</td>
<td id="meanIndependent">—</td>
<td id="meanCorrelated">—</td>
</tr>
<tr>
<td>Variance</td>
<td id="varianceIndependent">—</td>
<td id="varianceCorrelated">—</td>
</tr>
<tr>
<td>Std. deviation</td>
<td id="sdIndependent">—</td>
<td id="sdCorrelated">—</td>
</tr>
<tr>
<td>Pairwise correlation</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>Possible sequences</td>
<td id="sequenceIndependent">—</td>
<td>2</td>
</tr>
<tr>
<td>P(mixed sequence)</td>
<td id="mixedIndependent">—</td>
<td>0</td>
</tr>
</tbody>
</table>
<p class="footnote">
The chart computes exact PMFs. The small trial squares are illustrative
random draws, not estimates of the plotted probabilities.
</p>
</section>
</aside>
</main>
<footer>
The correlated alternative is intentionally extreme and is not an
independent-trial binomial model. Its purpose is to demonstrate that equal
one-trial marginal probabilities do not determine a count distribution.
</footer>
</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 COLORS = {
independent: 0x56dfce,
correlated: 0xff925d,
background: 0x08151e
};
const state = {
n: 20,
p: 0.5
};
const stage = $("stage");
const nInput = $("nInput");
const pInput = $("pInput");
const tooltip = $("tooltip");
// -------------------------------------------------------------------------
// Three.js core scene
// -------------------------------------------------------------------------
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
} catch (error) {
stage.innerHTML = `
<div style="padding:30px;color:#eaf5f5">
This visualization requires a browser with WebGL enabled.
</div>`;
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(COLORS.background, 1);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Three-dimensional comparison of exact independent and perfectly correlated count distributions"
);
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLORS.background);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 250);
const hemisphere = new THREE.HemisphereLight(0xc7f5ff, 0x172431, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.8);
keyLight.position.set(9, 16, 11);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -32;
keyLight.shadow.camera.right = 32;
keyLight.shadow.camera.top = 25;
keyLight.shadow.camera.bottom = -25;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 65;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4ed9e9, 1.25);
rimLight.position.set(-12, 7, -10);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(160, 160),
new THREE.MeshStandardMaterial({
color: 0x091721,
roughness: 1,
metalness: 0,
flatShading: true
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.035;
floor.receiveShadow = true;
scene.add(floor);
let chartGroup = null;
let barMeshes = [];
let animatedBars = [];
const STEP = 1.05;
const ROW_DEPTH = 1.6;
const HEIGHT = 5.4;
// Direct camera controls; no addons are imported.
const cameraTarget = new THREE.Vector3(0, 2.1, 0);
let cameraTheta = 0.72;
let cameraPhi = 1.02;
let zoomFactor = 1;
let baseRadius = 0;
let cameraRadius = 0;
function computeBaseRadius() {
const verticalHalfFov = THREE.MathUtils.degToRad(camera.fov / 2);
const horizontalHalfFov = Math.atan(
Math.tan(verticalHalfFov) * camera.aspect
);
const chartWidth = state.n * STEP + 4;
const fitDistance =
chartWidth / (2 * Math.tan(horizontalHalfFov));
return Math.max(18, fitDistance * 1.12);
}
function updateCamera() {
if (!baseRadius) return;
cameraRadius = baseRadius * zoomFactor;
const spherical = new THREE.Spherical(
cameraRadius,
cameraPhi,
cameraTheta
);
const offset = new THREE.Vector3().setFromSpherical(spherical);
camera.position.copy(cameraTarget).add(offset);
camera.lookAt(cameraTarget);
}
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
const oldBase = baseRadius;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
baseRadius = computeBaseRadius();
if (!oldBase) {
cameraRadius = baseRadius;
} else {
cameraRadius *= baseRadius / oldBase;
}
cameraRadius = THREE.MathUtils.clamp(
cameraRadius,
baseRadius * 0.55,
baseRadius * 1.65
);
updateCamera();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
// -------------------------------------------------------------------------
// Exact probability calculations
// -------------------------------------------------------------------------
function binomialCoefficient(n, k) {
let coefficient = 1;
for (let i = 1; i <= k; i++) {
coefficient *= (n - k + i) / i;
}
return coefficient;
}
function independentPMF(k) {
return (
binomialCoefficient(state.n, k) *
Math.pow(state.p, k) *
Math.pow(1 - state.p, state.n - k)
);
}
function correlatedPMF(k) {
if (k === 0) return 1 - state.p;
if (k === state.n) return state.p;
return 0;
}
function formatProbability(value) {
if (value === 0) return "0%";
if (value < 0.0001) {
return `${(value * 100).toExponential(2)}%`;
}
if (value < 0.01) {
return `${(value * 100).toFixed(3)}%`;
}
return `${(value * 100).toFixed(1)}%`;
}
function formatDecimal(value) {
if (value === 0) return "0";
if (value < 0.001) return value.toExponential(2);
return value.toFixed(2);
}
function formatStat(value) {
if (Math.abs(value) >= 100) return value.toFixed(0);
if (Math.abs(value) >= 10) return value.toFixed(1);
return value.toFixed(2);
}
// -------------------------------------------------------------------------
// Low-poly chart construction
// -------------------------------------------------------------------------
function disposeChart(group) {
group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of materials) {
if (material.map) material.map.dispose();
material.dispose();
}
}
});
scene.remove(group);
}
function addLine(points, color, opacity = 1) {
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map((point) => new THREE.Vector3(...point))
);
const material = new THREE.LineBasicMaterial({
color,
transparent: opacity < 1,
opacity,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
chartGroup.add(line);
return line;
}
function addTextSprite(
text,
color,
x,
y,
z,
width = 0.8,
height = 0.28
) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 96;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = color;
context.font =
"700 42px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.position.set(x, y, z);
sprite.scale.set(width, height, 1);
chartGroup.add(sprite);
return sprite;
}
function addBar(model, k, probability, x, z, yMax, startTime) {
if (probability <= 1e-12) return;
const height = HEIGHT * probability / yMax;
const isIndependent = model === "independent";
const geometry = new THREE.CylinderGeometry(
0.34,
0.43,
1,
5,
1,
false
);
const color = isIndependent
? COLORS.independent
: COLORS.correlated;
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.76,
metalness: 0.06,
flatShading: true,
emissive: color,
emissiveIntensity: 0.075
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, 0, z);
mesh.rotation.y = Math.PI / 5 + (k % 2) * 0.07;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData = {
model,
k,
probability,
targetHeight: height,
startTime
};
mesh.scale.y = 0.001;
mesh.position.y = 0.0005;
chartGroup.add(mesh);
barMeshes.push(mesh);
animatedBars.push(mesh);
}
function buildChart() {
if (chartGroup) disposeChart(chartGroup);
chartGroup = new THREE.Group();
scene.add(chartGroup);
barMeshes = [];
animatedBars = [];
const probabilities = [];
for (let k = 0; k <= state.n; k++) {
probabilities.push(independentPMF(k));
}
const yMax =
Math.max(
...probabilities,
state.p,
1 - state.p
) * 1.18;
const chartWidth = state.n * STEP;
const left = -chartWidth / 2;
const right = chartWidth / 2;
const startTime = performance.now();
// Colored row foundations.
const independentBase = new THREE.Mesh(
new THREE.BoxGeometry(chartWidth + 1, 0.075, 0.92),
new THREE.MeshStandardMaterial({
color: 0x12343a,
roughness: 0.95,
flatShading: true
})
);
independentBase.position.set(0, 0.035, ROW_DEPTH);
independentBase.receiveShadow = true;
chartGroup.add(independentBase);
const correlatedBase = new THREE.Mesh(
new THREE.BoxGeometry(chartWidth + 1, 0.075, 0.92),
new THREE.MeshStandardMaterial({
color: 0x3a2723,
roughness: 0.95,
flatShading: true
})
);
correlatedBase.position.set(0, 0.035, -ROW_DEPTH);
correlatedBase.receiveShadow = true;
chartGroup.add(correlatedBase);
// Probability grid.
const gridLevels = 5;
for (let i = 0; i <= gridLevels; i++) {
const probability = yMax * i / gridLevels;
const y = HEIGHT * probability / yMax;
addLine(
[
[left - 0.55, y, -2.75],
[right + 0.55, y, -2.75]
],
0x7896a1,
0.12
);
addLine(
[
[left - 0.55, y, 0],
[right + 0.55, y, 0]
],
0x7896a1,
0.1
);
addTextSprite(
formatDecimal(probability),
"#8ca8b2",
left - 1.0,
y,
0,
0.95,
0.31
);
}
// Count grid and axes.
const labelEvery = state.n <= 24 ? 1 : 2;
for (let k = 0; k <= state.n; k++) {
const x = (k - state.n / 2) * STEP;
addLine(
[
[x, 0.02, 0],
[x, HEIGHT, 0]
],
0x7896a1,
0.075
);
if (k % labelEvery === 0 || k === state.n) {
addTextSprite(
String(k),
"#829da8",
x,
0.08,
3.12,
0.43,
0.24
);
}
}
addLine(
[
[left - 0.55, 0.02, 0],
[left - 0.55, HEIGHT + 0.15, 0]
],
0xa9c1c8,
0.4
);
addLine(
[
[left - 0.55, 0.02, 0],
[right + 0.55, 0.02, 0]
],
0xa9c1c8,
0.35
);
// Exact independent bars in the front row.
for (let k = 0; k <= state.n; k++) {
const x = (k - state.n / 2) * STEP;
addBar(
"independent",
k,
independentPMF(k),
x,
ROW_DEPTH,
yMax,
startTime + k * 7
);
}
// Correlated toy bars in the back row.
for (let k = 0; k <= state.n; k++) {
const x = (k - state.n / 2) * STEP;
addBar(
"correlated",
k,
correlatedPMF(k),
x,
-ROW_DEPTH,
yMax,
startTime + k * 7
);
}
addTextSprite(
"INDEPENDENT · EXACT",
"#56dfce",
0,
0.22,
2.72,
2.7,
0.37
);
addTextSprite(
"CORRELATED TOY",
"#ff925d",
0,
0.22,
-2.72,
2.35,
0.37
);
addTextSprite(
"NUMBER OF SUCCESSES (k)",
"#9db4bc",
0,
0.12,
4.15,
2.65,
0.34
);
tooltip.hidden = true;
}
// -------------------------------------------------------------------------
// Hover inspection
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function inspectPointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(barMeshes, false);
if (!hits.length) {
tooltip.hidden = true;
return;
}
const hit = hits[0].object;
const data = hit.userData;
const modelName =
data.model === "independent"
? "Exact independent model"
: "Correlated shared-switch toy";
tooltip.innerHTML = `
<span class="tip-model">${modelName}</span>
<span>Number of successes: k = ${data.k}</span>
<span class="tip-value">${formatProbability(data.probability)}</span>
`;
tooltip.hidden = false;
const localX = event.clientX - rect.left;
const localY = event.clientY - rect.top;
const x = THREE.MathUtils.clamp(
localX + 14,
8,
Math.max(8, rect.width - 218)
);
const y = THREE.MathUtils.clamp(
localY + 14,
8,
Math.max(8, rect.height - 115)
);
tooltip.style.left = `${x}px`;
tooltip.style.top = `${y}px`;
}
// -------------------------------------------------------------------------
// Camera interaction
// -------------------------------------------------------------------------
let dragging = false;
let movedWhileDragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
movedWhileDragging = false;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.classList.add("dragging");
renderer.domElement.setPointerCapture(event.pointerId);
tooltip.hidden = true;
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (dragging) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
if (Math.abs(dx) + Math.abs(dy) > 2) {
movedWhileDragging = true;
}
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi + dy * 0.005,
0.43,
1.43
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
} else {
inspectPointer(event);
}
});
function endDrag(event) {
if (!dragging) return;
dragging = false;
renderer.domElement.classList.remove("dragging");
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (!movedWhileDragging) {
inspectPointer(event);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("pointerleave", () => {
if (!dragging) tooltip.hidden = true;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
zoomFactor = THREE.MathUtils.clamp(
zoomFactor * Math.exp(event.deltaY * 0.001),
0.55,
1.65
);
updateCamera();
},
{ passive: false }
);
$("resetButton").addEventListener("click", () => {
cameraTheta = 0.72;
cameraPhi = 1.02;
zoomFactor = 1;
cameraRadius = baseRadius;
updateCamera();
});
// -------------------------------------------------------------------------
// Illustrative random draws
// -------------------------------------------------------------------------
function randomUnit() {
if (window.crypto?.getRandomValues) {
const values = new Uint32Array(1);
window.crypto.getRandomValues(values);
return values[0] / 4294967296;
}
return Math.random();
}
function renderChips(container, values, mode) {
container.replaceChildren();
values.forEach((value, index) => {
const chip = document.createElement("span");
chip.className = `trial${value ? " on" : ""}`;
chip.style.setProperty("--delay", `${index * 12}ms`);
chip.title = `Trial ${index + 1}: ${value ? "success" : "failure"}`;
chip.setAttribute(
"aria-label",
`Trial ${index + 1}: ${value ? "success" : "failure"}`
);
container.appendChild(chip);
});
}
function newDraw() {
const independent = Array.from(
{ length: state.n },
() => (randomUnit() < state.p ? 1 : 0)
);
const sharedSwitch = randomUnit() < state.p ? 1 : 0;
const correlated = Array(state.n).fill(sharedSwitch);
renderChips($("independentChips"), independent, "independent");
renderChips($("correlatedChips"), correlated, "correlated");
const independentSum = independent.reduce((sum, value) => sum + value, 0);
$("independentCount").textContent = independentSum;
$("correlatedCount").textContent = sharedSwitch * state.n;
}
$("drawButton").addEventListener("click", newDraw);
let playTimer = null;
$("playButton").addEventListener("click", () => {
if (playTimer) {
clearInterval(playTimer);
playTimer = null;
$("playButton").textContent = "▶ Play";
$("playButton").setAttribute("aria-pressed", "false");
return;
}
newDraw();
$("playButton").textContent = "■ Pause";
$("playButton").setAttribute("aria-pressed", "true");
playTimer = window.setInterval(newDraw, 700);
});
// -------------------------------------------------------------------------
// Interface updates
// -------------------------------------------------------------------------
function updateStats() {
const mean = state.n * state.p;
const independentVariance =
state.n * state.p * (1 - state.p);
const correlatedVariance =
state.n * state.n * state.p * (1 - state.p);
const mixedProbability =
1 -
Math.pow(state.p, state.n) -
Math.pow(1 - state.p, state.n);
$("nOutput").textContent = state.n;
$("pOutput").textContent = state.p.toFixed(2);
$("meanIndependent").textContent = formatStat(mean);
$("meanCorrelated").textContent = formatStat(mean);
$("varianceIndependent").textContent =
formatStat(independentVariance);
$("varianceCorrelated").textContent =
formatStat(correlatedVariance);
$("sdIndependent").textContent =
formatStat(Math.sqrt(independentVariance));
$("sdCorrelated").textContent =
formatStat(Math.sqrt(correlatedVariance));
$("sequenceIndependent").textContent =
`2^${state.n}`;
$("mixedIndependent").textContent =
formatProbability(mixedProbability);
}
function updateModel() {
state.n = Number(nInput.value);
state.p = Number(pInput.value);
updateStats();
buildChart();
baseRadius = computeBaseRadius();
cameraRadius = baseRadius;
updateCamera();
newDraw();
}
nInput.addEventListener("input", updateModel);
pInput.addEventListener("input", updateModel);
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
function animate(time) {
for (const mesh of animatedBars) {
const raw = THREE.MathUtils.clamp(
(time - mesh.userData.startTime) / 520,
0,
1
);
const eased = 1 - Math.pow(1 - raw, 3);
const height = mesh.userData.targetHeight * eased;
mesh.scale.y = Math.max(0.001, height);
mesh.position.y = Math.max(0.0005, height / 2);
}
renderer.render(scene, camera);
}
resize();
updateStats();
buildChart();
newDraw();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```