confidence-intervals / web /src /components /TabBootstrap.vue
keefereuther's picture
Cursor
Use local tutor URLs in development, deployed URLs in production
d8d79a7
Raw History Blame Contribute Delete
12.8 kB
<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from 'vue'
import * as d3 from 'd3'
import {
rnorm,
mean,
sampleSd,
qnorm,
quantile7,
histDensity,
bootstrapMeans,
} from '../lib/stats.js'
const tutorUrl = import.meta.env.DEV
? 'http://127.0.0.1:7863'
: 'https://keefereuther-ci-tab3.hf.space'
const normalSD = ref(1)
const sampleSize = ref(50)
const bootstrapReps = ref(1000)
const confidenceLevel = ref(95)
const initialSample = ref(null)
const bootMeans = ref(null)
const plotEl = ref(null)
let plotResizeObserver = null
const margin = { top: 56, right: 24, bottom: 56, left: 72 }
function measurePlotSize() {
const el = plotEl.value
if (!el) return { W: 920, H: 460 }
const w = el.getBoundingClientRect().width || el.clientWidth
const W = Math.max(280, Math.floor(w))
const H = Math.max(340, Math.round((W * 460) / 920))
return { W, H }
}
function generateInitial() {
initialSample.value = rnorm(sampleSize.value, 0, normalSD.value)
bootMeans.value = null
}
function runBootstrap() {
if (!initialSample.value || !initialSample.value.length) return
bootMeans.value = bootstrapMeans(initialSample.value, bootstrapReps.value)
}
function renderPlot() {
const root = plotEl.value
if (!root) return
d3.select(root).selectAll('*').remove()
const { W, H } = measurePlotSize()
const innerW = W - margin.left - margin.right
const innerH = H - margin.top - margin.bottom
const clipId = `ci-clip-tab3-${Math.random().toString(36).slice(2, 9)}`
const svg = d3
.select(root)
.append('svg')
.attr('viewBox', `0 0 ${W} ${H}`)
.attr('width', '100%')
.attr('preserveAspectRatio', 'xMinYMid meet')
.style('display', 'block')
.style('max-width', '100%')
.style('height', 'auto')
.style('vertical-align', 'top')
.style('font-family', 'system-ui, sans-serif')
const x = initialSample.value
const bm = bootMeans.value
if (!x || !x.length || !bm || !bm.length) {
svg
.append('text')
.attr('x', W / 2)
.attr('y', H / 2)
.attr('text-anchor', 'middle')
.attr('fill', '#64748b')
.attr('font-size', 16)
.text('Generate an initial sample, then run bootstrap.')
return
}
const origMean = mean(x)
const alpha = 1 - confidenceLevel.value / 100
const qLow = quantile7(bm, alpha / 2)
const qHigh = quantile7(bm, 1 - alpha / 2)
const xMin = -1
const xMax = 1
const { breaks, heights } = histDensity(bm)
const ymax = Math.max(0.01, ...heights) * 1.05
const xS = d3.scaleLinear().domain([xMin, xMax]).range([0, innerW])
const yS = d3.scaleLinear().domain([0, ymax]).range([innerH, 0])
const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`)
g.append('clipPath')
.attr('id', clipId)
.append('rect')
.attr('width', innerW)
.attr('height', innerH)
const panel = g.append('g').attr('clip-path', `url(#${clipId})`)
const fillGreen = '#90ee90'
panel
.selectAll('rect.hist')
.data(heights.map((h, i) => ({ h, x0: breaks[i], x1: breaks[i + 1] })))
.join('rect')
.attr('class', 'hist')
.attr('x', (d) => Math.max(xS(xMin), xS(d.x0)))
.attr('y', (d) => yS(d.h))
.attr('width', (d) => Math.max(0, Math.min(xS(xMax), xS(d.x1)) - Math.max(xS(xMin), xS(d.x0))))
.attr('height', (d) => yS(0) - yS(d.h))
.attr('fill', fillGreen)
.attr('stroke', '#ffffff')
.attr('stroke-width', 1)
const vline = (xv, stroke, width, dash) => {
panel
.append('line')
.attr('x1', xS(xv))
.attr('x2', xS(xv))
.attr('y1', yS(0))
.attr('y2', yS(ymax))
.attr('stroke', stroke)
.attr('stroke-width', width)
.attr('stroke-dasharray', dash || null)
}
vline(0, '#ff0000', 3, null)
vline(origMean, '#0000ff', 3, '8 6')
vline(qLow, '#90ee90', 3, '4 4')
vline(qHigh, '#90ee90', 3, '4 4')
g.append('g')
.attr('transform', `translate(0,${innerH})`)
.call(d3.axisBottom(xS).ticks(8))
.call((ga) => ga.select('.domain').attr('stroke', '#333'))
.call((ga) => ga.selectAll('.tick line').attr('stroke', '#ccc'))
g.append('g')
.call(d3.axisLeft(yS).ticks(6))
.call((ga) => ga.select('.domain').attr('stroke', '#333'))
.call((ga) => ga.selectAll('.tick line').attr('stroke', '#ccc'))
svg
.append('text')
.attr('x', margin.left + innerW / 2)
.attr('y', margin.top + innerH + 42)
.attr('text-anchor', 'middle')
.attr('font-size', 14)
.attr('fill', '#0f172a')
.text('Bootstrap Means')
svg
.append('text')
.attr('transform', 'rotate(-90)')
.attr('x', -(margin.top + innerH / 2))
.attr('y', 22)
.attr('text-anchor', 'middle')
.attr('font-size', 14)
.attr('fill', '#0f172a')
.text('Density')
svg
.append('text')
.attr('x', margin.left)
.attr('y', 28)
.attr('font-size', 17)
.attr('font-weight', 600)
.attr('fill', '#0f172a')
.text('Bootstrap Distribution of Means')
const LEGEND_W = 148
const leg = g.append('g').attr('transform', `translate(${Math.max(0, innerW - LEGEND_W - 8)}, 10)`)
const legRows = [
{ label: 'Population mean', color: '#ff0000', dash: null, lw: 3 },
{ label: 'Sample mean', color: '#0000ff', dash: '8 6', lw: 3 },
{ label: '95% CI', color: '#90ee90', dash: '4 4', lw: 3 },
]
legRows.forEach((row, i) => {
const rowG = leg.append('g').attr('transform', `translate(0, ${i * 22})`)
rowG
.append('line')
.attr('x1', 0)
.attr('x2', 28)
.attr('y1', 0)
.attr('y2', 0)
.attr('stroke', row.color)
.attr('stroke-width', row.lw)
.attr('stroke-dasharray', row.dash || null)
rowG
.append('text')
.attr('x', 34)
.attr('y', 4)
.attr('text-anchor', 'start')
.attr('font-size', 12)
.attr('fill', '#0f172a')
.text(row.label)
})
}
watch(
[initialSample, bootMeans, confidenceLevel, normalSD, sampleSize, bootstrapReps],
() => nextTick().then(renderPlot),
{ deep: true },
)
onMounted(() => {
nextTick(() => {
plotResizeObserver = new ResizeObserver(() => nextTick(renderPlot))
if (plotEl.value) plotResizeObserver.observe(plotEl.value)
renderPlot()
})
})
onUnmounted(() => {
plotResizeObserver?.disconnect()
plotResizeObserver = null
})
</script>
<template>
<div class="flex flex-col gap-6 lg:flex-row">
<aside class="w-full shrink-0 space-y-4 rounded-lg border border-slate-200 bg-white p-4 shadow-sm lg:w-72">
<h3 class="text-lg font-semibold text-slate-800">The Population</h3>
<div>
<label class="mb-1 block text-sm font-medium text-slate-600">Population SD:</label>
<input
v-model.number="normalSD"
type="number"
min="0.01"
step="0.1"
class="w-full rounded border border-slate-300 px-3 py-2 shadow-sm focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500"
/>
</div>
<hr class="border-slate-200" />
<h3 class="text-lg font-semibold text-slate-800">Your Initial Sample</h3>
<div>
<label class="mb-1 block text-sm font-medium text-slate-600">Sample Size (initial):</label>
<input
v-model.number="sampleSize"
type="number"
min="1"
class="w-full rounded border border-slate-300 px-3 py-2 shadow-sm focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500"
/>
</div>
<p class="text-sm font-semibold text-slate-800">You must select this button before running the bootstrap:</p>
<button
type="button"
class="w-full rounded-md bg-sky-700 px-4 py-2 text-white shadow hover:bg-sky-800 focus:outline-none focus:ring-2 focus:ring-sky-500 focus:ring-offset-2"
@click="generateInitial"
>
Generate New Initial Sample
</button>
<hr class="border-slate-200" />
<h3 class="text-lg font-semibold text-slate-800">Bootstrapping</h3>
<div>
<label class="mb-1 block text-sm font-medium text-slate-600">Number of Bootstrap Replicates:</label>
<input
v-model.number="bootstrapReps"
type="number"
min="1"
class="w-full rounded border border-slate-300 px-3 py-2 shadow-sm focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500"
/>
</div>
<div>
<label class="mb-1 block text-sm font-medium text-slate-600">Confidence Level (%)</label>
<input
v-model.number="confidenceLevel"
type="range"
min="50"
max="99"
step="1"
class="w-full accent-sky-600"
/>
<div class="text-sm text-slate-600">{{ confidenceLevel }}%</div>
</div>
<button
type="button"
class="w-full rounded-md bg-emerald-700 px-4 py-2 text-white shadow hover:bg-emerald-800 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2"
@click="runBootstrap"
>
Run Bootstrap
</button>
<hr class="border-slate-200" />
<h4 class="font-semibold text-slate-800">Guiding Questions:</h4>
<p class="text-sm text-slate-700">
1. What is the effect on the 95% CI if you bootstrap 10,000X instead of 100X?
</p>
<p class="text-sm text-slate-700">
2. When you bootstrap 10,000X, does it seem to give a very similar 95% CI compared to the theoretical CI
calculated from the sample size and standard deviation?
</p>
</aside>
<div class="min-w-0 flex-1 space-y-4">
<div class="overflow-x-auto rounded-lg border border-slate-200 bg-white p-2 shadow-sm">
<div ref="plotEl" class="ci-plot-host min-h-[300px] w-full min-w-0" />
</div>
<div v-if="initialSample && initialSample.length && bootMeans && bootMeans.length" class="inline-block overflow-x-auto rounded-lg border border-slate-200 bg-white shadow-sm">
<table class="min-w-[320px] text-sm">
<thead>
<tr class="border-b border-slate-200 bg-slate-50">
<th class="px-4 py-2 text-left font-semibold text-slate-700">Statistic</th>
<th class="px-4 py-2 text-right font-semibold text-slate-700">Value</th>
</tr>
</thead>
<tbody>
<tr class="border-b border-slate-100">
<td class="px-4 py-2 text-slate-800">
Bootstrap {{ confidenceLevel }}% CI (Lower)
</td>
<td class="px-4 py-2 text-right font-medium text-slate-900">
{{ quantile7(bootMeans, (1 - confidenceLevel / 100) / 2).toFixed(3) }}
</td>
</tr>
<tr class="border-b border-slate-100">
<td class="px-4 py-2 text-slate-800">Z-based {{ confidenceLevel }}% CI (Lower)</td>
<td class="px-4 py-2 text-right font-medium text-slate-900">
{{
(
mean(initialSample) -
qnorm(1 - (1 - confidenceLevel / 100) / 2) *
(sampleSd(initialSample) / Math.sqrt(initialSample.length))
).toFixed(3)
}}
</td>
</tr>
<tr class="border-b border-slate-100">
<td class="px-4 py-2 text-slate-800">
Bootstrap {{ confidenceLevel }}% CI (Upper)
</td>
<td class="px-4 py-2 text-right font-medium text-slate-900">
{{ quantile7(bootMeans, 1 - (1 - confidenceLevel / 100) / 2).toFixed(3) }}
</td>
</tr>
<tr>
<td class="px-4 py-2 text-slate-800">Z-based {{ confidenceLevel }}% CI (Upper)</td>
<td class="px-4 py-2 text-right font-medium text-slate-900">
{{
(
mean(initialSample) +
qnorm(1 - (1 - confidenceLevel / 100) / 2) *
(sampleSd(initialSample) / Math.sqrt(initialSample.length))
).toFixed(3)
}}
</td>
</tr>
</tbody>
</table>
</div>
<p v-else-if="initialSample && initialSample.length" class="text-sm text-slate-600">
Run bootstrap to see percentile and z-based confidence interval estimates.
</p>
<hr class="border-slate-200" />
<h4 class="text-lg font-semibold text-slate-800">AI Tutor</h4>
<p class="text-sm text-slate-600">Have a conversation with the chatbot about this simulation!</p>
<iframe
:src="tutorUrl"
class="h-[500px] w-full rounded-lg border border-slate-200"
title="AI Tutor tab 3"
style="border: none"
/>
</div>
</div>
</template>