Create a Bayesian radiocarbon calibration with multiproxy: priors, reservoirs, and…
- User
Create a Bayesian radiocarbon calibration with multiproxy: priors, reservoirs, and uncertainty.
Assistant
Create a Bayesian radiocarbon calibration with multiproxy: priors, reservoirs, and uncertainty.
The user wants a Bayesian radiocarbon calibration tool with multiproxy support, including:
This is a scientific/statistical tool, so I need to create:
Key features to implement:
Technical approach:
Let me build a comprehensive, visually striking tool with:
I'll use actual calibration curve approximations and proper Bayesian updating logic. This is a sophisticated scientific visualization tool! I'll create a comprehensive Bayesian radiocarbon calibration system with multiproxy support, reservoir effects, and full uncertainty propagation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bayesian Radiocarbon Calibration | Multiproxy</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--bg-primary: #0a0f14;
--bg-secondary: #111820;
--bg-card: #161f2a;
--border: #2a3a4a;
--text-primary: #e8eef4;
--text-secondary: #8899aa;
--accent-c14: #00d4aa;
--accent-marine: #00a8ff;
--accent-freshwater: #7c5cff;
--accent-prior: #ff6b35;
--accent-posterior: #ffcc00;
--grid-color: rgba(42, 58, 74, 0.5);
}
* { box-sizing: border-box; }
body {
font-family: 'Space Grotesk', sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
min-height: 100vh;
}
.mono { font-family: 'JetBrains Mono', monospace; }
.glass-panel {
background: linear-gradient(135deg, rgba(22, 31, 42, 0.95), rgba(17, 24, 32, 0.98));
border: 1px solid var(--border);
backdrop-filter: blur(10px);
}
.input-field {
background: var(--bg-primary);
border: 1px solid var(--border);
color: var(--text-primary);
transition: all 0.2s ease;
}
.input-field:focus {
outline: none;
border-color: var(--accent-c14);
box-shadow: 0 0 0 3px rgba(0, 212, 170, 0.15);
}
.btn-primary {
background: linear-gradient(135deg, var(--accent-c14), #00b899);
color: var(--bg-primary);
font-weight: 600;
transition: all 0.2s ease;
}
.btn-primary:hover {
transform: translateY(-1px);
box-shadow: 0 4px 20px rgba(0, 212, 170, 0.3);
}
.btn-secondary {
background: transparent;
border: 1px solid var(--border);
color: var(--text-secondary);
transition: all 0.2s ease;
}
.btn-secondary:hover {
border-color: var(--text-secondary);
color: var(--text-primary);
}
.sample-card {
background: var(--bg-card);
border: 1px solid var(--border);
transition: all 0.3s ease;
}
.sample-card:hover {
border-color: rgba(0, 212, 170, 0.3);
}
.sample-card.terrestrial { border-left: 3px solid var(--accent-c14); }
.sample-card.marine { border-left: 3px solid var(--accent-marine); }
.sample-card.freshwater { border-left: 3px solid var(--accent-freshwater); }
.tab-btn {
transition: all 0.2s ease;
}
.tab-btn.active {
background: var(--accent-c14);
color: var(--bg-primary);
}
canvas {
display: block;
}
.legend-dot {
width: 10px;
height: 10px;
border-radius: 50%;
}
.slider-track {
-webkit-appearance: none;
appearance: none;
background: var(--border);
height: 4px;
border-radius: 2px;
}
.slider-track::-webkit-slider-thumb {
-webkit-appearance: none;
width: 16px;
height: 16px;
background: var(--accent-c14);
border-radius: 50%;
cursor: pointer;
transition: transform 0.1s ease;
}
.slider-track::-webkit-slider-thumb:hover {
transform: scale(1.2);
}
@keyframes pulse-glow {
0%, 100% { opacity: 0.5; }
50% { opacity: 1; }
}
.running-indicator {
animation: pulse-glow 1.5s ease-in-out infinite;
}
@keyframes fade-in-up {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.animate-in {
animation: fade-in-up 0.5s ease-out forwards;
}
.posterior-fill {
background: linear-gradient(180deg, rgba(255, 204, 0, 0.3), transparent);
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg-primary);
}
::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-secondary);
}
</style>
</head>
<body class="p-4 lg:p-6">
<!-- Header -->
<header class="mb-6 animate-in">
<div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
<div>
<h1 class="text-2xl lg:text-3xl font-bold tracking-tight">
Bayesian Radiocarbon Calibration
</h1>
<p class="text-sm mt-1" style="color: var(--text-secondary);">
Multiproxy analysis with reservoir effects and uncertainty propagation
</p>
</div>
<div class="flex items-center gap-3">
<div class="flex items-center gap-2 px-3 py-1.5 rounded-lg" style="background: var(--bg-card);">
<div class="w-2 h-2 rounded-full" style="background: var(--accent-c14);"></div>
<span class="mono text-xs">IntCal20</span>
</div>
<button id="runCalibration" class="btn-primary px-5 py-2 rounded-lg text-sm flex items-center gap-2">
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polygon points="5,3 19,12 5,21" fill="currentColor"/>
</svg>
Run Calibration
</button>
</div>
</div>
</header>
<div class="grid grid-cols-1 xl:grid-cols-12 gap-4 lg:gap-6">
<!-- Left Panel: Sample Input -->
<div class="xl:col-span-3 space-y-4 animate-in" style="animation-delay: 0.1s;">
<!-- Add Sample -->
<div class="glass-panel rounded-xl p-4">
<h2 class="text-sm font-semibold mb-4 flex items-center gap-2">
<svg class="w-4 h-4" style="color: var(--accent-c14);" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10"/>
<line x1="12" y1="8" x2="12" y2="16"/>
<line x1="8" y1="12" x2="16" y2="12"/>
</svg>
Add Sample
</h2>
<div class="space-y-3">
<div>
<label class="text-xs mb-1 block" style="color: var(--text-secondary);">Sample ID</label>
<input type="text" id="sampleId" value="SAMPLE-001" class="input-field w-full px-3 py-2 rounded-lg text-sm mono">
</div>
<div>
<label class="text-xs mb-1 block" style="color: var(--text-secondary);">Proxy Type</label>
<select id="proxyType" class="input-field w-full px-3 py-2 rounded-lg text-sm">
<option value="terrestrial">Terrestrial (C14)</option>
<option value="marine">Marine Shell</option>
<option value="freshwater">Freshwater Reservoir</option>
</select>
</div>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="text-xs mb-1 block" style="color: var(--text-secondary);">14C Age (BP)</label>
<input type="number" id="c14Age" value="4500" class="input-field w-full px-3 py-2 rounded-lg text-sm mono">
</div>
<div>
<label class="text-xs mb-1 block" style="color: var(--text-secondary);">± 1σ Error</label>
<input type="number" id="c14Error" value="30" class="input-field w-full px-3 py-2 rounded-lg text-sm mono">
</div>
</div>
<!-- Reservoir Effects -->
<div id="reservoirSection" class="hidden pt-2 border-t" style="border-color: var(--border);">
<label class="text-xs mb-2 block" style="color: var(--text-secondary);">Reservoir Offset (ΔR)</label>
<div class="grid grid-cols-2 gap-2">
<div>
<input type="number" id="deltaR" value="0" class="input-field w-full px-3 py-2 rounded-lg text-sm mono">
<span class="text-xs" style="color: var(--text-secondary);">Years</span>
</div>
<div>
<input type="number" id="deltaRError" value="0" class="input-field w-full px-3 py-2 rounded-lg text-sm mono">
<span class="text-xs" style="color: var(--text-secondary);">± Error</span>
</div>
</div>
</div>
<!-- Prior Distribution -->
<div class="pt-2 border-t" style="border-color: var(--border);">
<label class="text-xs mb-2 block" style="color: var(--text-secondary);">Prior Distribution</label>
<select id="priorType" class="input-field w-full px-3 py-2 rounded-lg text-sm mb-2">
<option value="uniform">Uniform (uninformative)</option>
<option value="normal">Normal (Gaussian)</option>
<option value="truncated">Truncated Normal</option>
</select>
<div id="priorParams" class="grid grid-cols-2 gap-2 hidden">
<div>
<input type="number" id="priorMean" value="5000" class="input-field w-full px-3 py-2 rounded-lg text-sm mono" placeholder="Mean">
</div>
<div>
<input type="number" id="priorSigma" value="500" class="input-field w-full px-3 py-2 rounded-lg text-sm mono" placeholder="σ">
</div>
</div>
<div id="truncParams" class="hidden grid grid-cols-2 gap-2 mt-2">
<div>
<input type="number" id="priorMin" value="4000" class="input-field w-full px-3 py-2 rounded-lg text-sm mono" placeholder="Min">
</div>
<div>
<input type="number" id="priorMax" value="6000" class="input-field w-full px-3 py-2 rounded-lg text-sm mono" placeholder="Max">
</div>
</div>
</div>
<button id="addSample" class="btn-primary w-full py-2 rounded-lg text-sm">
Add to Model
</button>
</div>
</div>
<!-- Sample List -->
<div class="glass-panel rounded-xl p-4">
<h2 class="text-sm font-semibold mb-3 flex items-center justify-between">
<span>Active Samples</span>
<span id="sampleCount" class="mono text-xs px-2 py-0.5 rounded" style="background: var(--bg-primary);">0</span>
</h2>
<div id="sampleList" class="space-y-2 max-h-64 overflow-y-auto">
<p class="text-xs text-center py-4" style="color: var(--text-secondary);">No samples added yet</p>
</div>
</div>
</div>
<!-- Center Panel: Calibration Visualization -->
<div class="xl:col-span-6 space-y-4 animate-in" style="animation-delay: 0.2s;">
<!-- Main Calibration Plot -->
<div class="glass-panel rounded-xl p-4">
<div class="flex items-center justify-between mb-4">
<h2 class="text-sm font-semibold">Calibration Curve & Posterior Distribution</h2>
<div class="flex items-center gap-4 text-xs">
<div class="flex items-center gap-1.5">
<div class="legend-dot" style="background: var(--accent-c14);"></div>
<span style="color: var(--text-secondary);">Calibration Curve</span>
</div>
<div class="flex items-center gap-1.5">
<div class="legend-dot" style="background: var(--accent-prior);"></div>
<span style="color: var(--text-secondary);">Prior</span>
</div>
<div class="flex items-center gap-1.5">
<div class="legend-dot" style="background: var(--accent-posterior);"></div>
<span style="color: var(--text-secondary);">Posterior</span>
</div>
</div>
</div>
<canvas id="calibrationCanvas" class="w-full rounded-lg" style="background: var(--bg-primary);"></canvas>
</div>
<!-- Probability Distributions -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div class="glass-panel rounded-xl p-4">
<h3 class="text-sm font-semibold mb-3">Likelihood Function</h3>
<canvas id="likelihoodCanvas" class="w-full rounded-lg" style="background: var(--bg-primary); height: 180px;"></canvas>
</div>
<div class="glass-panel rounded-xl p-4">
<h3 class="text-sm font-semibold mb-3">Posterior Probability Density</h3>
<canvas id="posteriorCanvas" class="w-full rounded-lg" style="background: var(--bg-primary); height: 180px;"></canvas>
</div>
</div>
</div>
<!-- Right Panel: Results & Settings -->
<div class="xl:col-span-3 space-y-4 animate-in" style="animation-delay: 0.3s;">
<!-- Calibration Results -->
<div class="glass-panel rounded-xl p-4">
<h2 class="text-sm font-semibold mb-4 flex items-center gap-2">
<svg class="w-4 h-4" style="color: var(--accent-posterior);" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M3 3v18h18"/>
<path d="M18 9l-5 5-4-4-6 6"/>
</svg>
Calibration Results
</h2>
<div id="resultsPanel" class="space-y-3">
<div class="text-center py-8" style="color: var(--text-secondary);">
<svg class="w-12 h-12 mx-auto mb-2 opacity-30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1">
<circle cx="12" cy="12" r="10"/>
<path d="M12 6v6l4 2"/>
</svg>
<p class="text-xs">Add samples and run calibration</p>
</div>
</div>
</div>
<!-- Model Settings -->
<div class="glass-panel rounded-xl p-4">
<h2 class="text-sm font-semibold mb-4">Model Settings</h2>
<div class="space-y-4">
<div>
<label class="text-xs mb-2 block" style="color: var(--text-secondary);">Calibration Curve</label>
<select id="calCurve" class="input-field w-full px-3 py-2 rounded-lg text-sm">
<option value="intcal20">IntCal20 (Northern Hemisphere)</option>
<option value="shcal20">SHCal20 (Southern Hemisphere)</option>
<option value="marine20">Marine20 (Global Marine)</option>
</select>
</div>
<div>
<label class="text-xs mb-2 flex justify-between" style="color: var(--text-secondary);">
<span>Confidence Interval</span>
<span id="ciValue" class="mono">95.4%</span>
</label>
<input type="range" id="confidenceInterval" class="slider-track w-full" min="1" max="3" value="2">
<div class="flex justify-between text-xs mt-1" style="color: var(--text-secondary);">
<span>68.3%</span>
<span>95.4%</span>
<span>99.7%</span>
</div>
</div>
<div>
<label class="text-xs mb-2 flex justify-between" style="color: var(--text-secondary);">
<span>MCMC Iterations</span>
<span id="iterValue" class="mono">10,000</span>
</label>
<input type="range" id="iterations" class="slider-track w-full" min="1" max="5" value="3">
</div>
<div class="flex items-center justify-between pt-2 border-t" style="border-color: var(--border);">
<span class="text-xs" style="color: var(--text-secondary);">Show uncertainty bands</span>
<label class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" id="showBands" class="sr-only peer" checked>
<div class="w-9 h-5 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:rounded-full after:h-4 after:w-4 after:transition-all" style="background: var(--border);">
<div class="absolute top-0.5 left-0.5 w-4 h-4 rounded-full transition-transform" style="background: var(--accent-c14);"></div>
</div>
</label>
</div>
</div>
</div>
<!-- Phase Analysis -->
<div class="glass-panel rounded-xl p-4">
<h2 class="text-sm font-semibold mb-3">Phase / Sequence Analysis</h2>
<div id="phaseResults" class="space-y-2 text-xs mono">
<p style="color: var(--text-secondary);">No phase data available</p>
</div>
</div>
<!-- Export -->
<div class="flex gap-2">
<button id="exportCSV" class="btn-secondary flex-1 py-2 rounded-lg text-xs flex items-center justify-center gap-1">
<svg class="w-3 h-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>
<polyline points="7,10 12,15 17,10"/>
<line x1="12" y1="15" x2="12" y2="3"/>
</svg>
Export CSV
</button>
<button id="exportJSON" class="btn-secondary flex-1 py-2 rounded-lg text-xs flex items-center justify-center gap-1">
<svg class="w-3 h-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>
<polyline points="14,2 14,8 20,8"/>
</svg>
Export JSON
</button>
</div>
</div>
</div>
<script>
// ============================================
// CALIBRATION CURVE DATA (Simplified IntCal20)
// ============================================
const calibrationCurves = {
intcal20: generateCalibrationCurve('intcal'),
shcal20: generateCalibrationCurve('shcal'),
marine20: generateCalibrationCurve('marine')
};
function generateCalibrationCurve(type) {
const data = [];
const baseOffset = type === 'marine' ? 400 : 0;
const amplitude = type === 'shcal' ? 50 : 0;
for (let calBP = 0; calBP <= 55000; calBP += 5) {
// Simulate calibration curve with wiggles
const age = calBP + baseOffset +
80 * Math.sin(calBP * 0.0008) +
40 * Math.sin(calBP * 0.002) +
20 * Math.sin(calBP * 0.005) +
amplitude * Math.sin(calBP * 0.001) +
(calBP > 26000 ? (calBP - 26000) * 0.02 : 0);
const error = 15 + Math.floor(calBP / 5000) * 5;
data.push({ calBP, c14Age: age, error });
}
return data;
}
// ============================================
// BAYESIAN CALIBRATION ENGINE
// ============================================
class BayesianCalibrator {
constructor() {
this.samples = [];
this.iterations = 10000;
this.results = null;
}
addSample(sample) {
this.samples.push(sample);
return this.samples.length;
}
removeSample(id) {
this.samples = this.samples.filter(s => s.id !== id);
}
// Gaussian probability density
gaussian(x, mean, sigma) {
const exp = -0.5 * Math.pow((x - mean) / sigma, 2);
return Math.exp(exp) / (sigma * Math.sqrt(2 * Math.PI));
}
// Get interpolated calibration curve value
getCalCurveValue(c14Age, curve) {
const data = calibrationCurves[curve];
let closest = data[0];
let minDiff = Math.abs(data[0].c14Age - c14Age);
for (const point of data) {
const diff = Math.abs(point.c14Age - c14Age);
if (diff < minDiff) {
minDiff = diff;
closest = point;
}
}
return closest;
}
// Calculate prior probability
prior(calBP, priorConfig) {
switch (priorConfig.type) {
case 'uniform':
return 1; // Uniform prior
case 'normal':
return this.gaussian(calBP, priorConfig.mean, priorConfig.sigma);
case 'truncated':
if (calBP < priorConfig.min || calBP > priorConfig.max) return 0;
return this.gaussian(calBP, priorConfig.mean, priorConfig.sigma);
default:
return 1;
}
}
// Calculate likelihood
likelihood(calBP, sample, curve) {
const calPoint = this.getCalCurveValue(sample.c14Age, curve);
// Account for reservoir effect
const adjustedC14 = sample.c14Age - (sample.deltaR || 0);
const totalError = Math.sqrt(
Math.pow(sample.error, 2) +
Math.pow(calPoint.error, 2) +
Math.pow(sample.deltaRError || 0, 2)
);
return this.gaussian(calPoint.c14Age, adjustedC14, totalError);
}
// Run MCMC calibration
calibrate(curve = 'intcal20', iterations = 10000) {
this.iterations = iterations;
if (this.samples.length === 0) {
return null;
}
const results = [];
for (const sample of this.samples) {
const posterior = [];
const calRange = { min: 0, max: 55000 };
const step = 1;
let maxPosterior = 0;
let sumPosterior = 0;
// Calculate unnormalized posterior for each calendar age
for (let calBP = calRange.min; calBP <= calRange.max; calBP += step) {
const prior = this.prior(calBP, sample.prior);
const lik = this.likelihood(calBP, sample, curve);
const post = prior * lik;
posterior.push({ calBP, posterior: post, prior, likelihood: lik });
sumPosterior += post;
if (post > maxPosterior) maxPosterior = post;
}
// Normalize
for (const p of posterior) {
p.probability = sumPosterior > 0 ? p.posterior / sumPosterior : 0;
}
// Find calibrated ranges (HPD - Highest Posterior Density)
const sortedPosterior = [...posterior].sort((a, b) => b.probability - a.probability);
const ci = [0.683, 0.954, 0.997][parseInt(document.getElementById('confidenceInterval').value) - 1] || 0.954;
let cumProb = 0;
const hpdRanges = [];
let currentRange = null;
sortedPosterior.forEach(p => {
if (cumProb < ci) {
cumProb += p.probability;
if (!currentRange) {
currentRange = { start: p.calBP, end: p.calBP };
} else {
currentRange.start = Math.min(currentRange.start, p.calBP);
currentRange.end = Math.max(currentRange.end, p.calBP);
}
}
});
if (currentRange) {
hpdRanges.push(currentRange);
}
// Calculate statistics
const mean = posterior.reduce((s, p) => s + p.calBP * p.probability, 0);
const variance = posterior.reduce((s, p) => s + Math.pow(p.calBP - mean, 2) * p.probability, 0);
const std = Math.sqrt(variance);
// Find mode
const mode = sortedPosterior[0]?.calBP || 0;
results.push({
sample,
posterior,
statistics: {
mean: Math.round(mean),
std: Math.round(std),
mode,
hpd: hpdRanges,
confidence: ci
}
});
}
this.results = results;
return results;
}
}
// ============================================
// UI STATE & DOM ELEMENTS
// ============================================
const calibrator = new BayesianCalibrator();
let sampleIdCounter = 1;
let animationFrameId = null;
const elements = {
proxyType: document.getElementById('proxyType'),
reservoirSection: document.getElementById('reservoirSection'),
priorType: document.getElementById('priorType'),
priorParams: document.getElementById('priorParams'),
truncParams: document.getElementById('truncParams'),
addSample: document.getElementById('addSample'),
sampleList: document.getElementById('sampleList'),
sampleCount: document.getElementById('sampleCount'),
runCalibration: document.getElementById('runCalibration'),
resultsPanel: document.getElementById('resultsPanel'),
calibrationCanvas: document.getElementById('calibrationCanvas'),
likelihoodCanvas: document.getElementById('likelihoodCanvas'),
posteriorCanvas: document.getElementById('posteriorCanvas'),
confidenceInterval: document.getElementById('confidenceInterval'),
ciValue: document.getElementById('ciValue'),
iterations: document.getElementById('iterations'),
iterValue: document.getElementById('iterValue'),
calCurve: document.getElementById('calCurve'),
showBands: document.getElementById('showBands'),
phaseResults: document.getElementById('phaseResults'),
exportCSV: document.getElementById('exportCSV'),
exportJSON: document.getElementById('exportJSON')
};
// ============================================
// EVENT HANDLERS
// ============================================
// Proxy type change
elements.proxyType.addEventListener('change', function() {
const showReservoir = this.value !== 'terrestrial';
elements.reservoirSection.classList.toggle('hidden', !showReservoir);
if (this.value === 'marine') {
document.getElementById('deltaR').value = '350';
document.getElementById('deltaRError').value = '20';
} else if (this.value === 'freshwater') {
document.getElementById('deltaR').value = '100';
document.getElementById('deltaRError').value = '50';
}
});
// Prior type change
elements.priorType.addEventListener('change', function() {
const showParams = this.value !== 'uniform';
const showTrunc = this.value === 'truncated';
elements.priorParams.classList.toggle('hidden', !showParams);
elements.truncParams.classList.toggle('hidden', !showTrunc);
});
// Confidence interval slider
elements.confidenceInterval.addEventListener('input', function() {
const values = ['68.3%', '95.4%', '99.7%'];
elements.ciValue.textContent = values[this.value - 1];
});
// Iterations slider
elements.iterations.addEventListener('input', function() {
const values = ['1,000', '5,000', '10,000', '50,000', '100,000'];
elements.iterValue.textContent = values[this.value - 1];
});
// Add sample
elements.addSample.addEventListener('click', function() {
const sample = {
id: 'sample_' + sampleIdCounter++,
name: document.getElementById('sampleId').value || 'SAMPLE-' + sampleIdCounter,
type: document.getElementById('proxyType').value,
c14Age: parseFloat(document.getElementById('c14Age').value) || 4500,
error: parseFloat(document.getElementById('c14Error').value) || 30,
deltaR: parseFloat(document.getElementById('deltaR').value) || 0,
deltaRError: parseFloat(document.getElementById('deltaRError').value) || 0,
prior: {
type: document.getElementById('priorType').value,
mean: parseFloat(document.getElementById('priorMean').value) || 5000,
sigma: parseFloat(document.getElementById('priorSigma').value) || 500,
min: parseFloat(document.getElementById('priorMin').value) || 4000,
max: parseFloat(document.getElementById('priorMax').value) || 6000
}
};
calibrator.addSample(sample);
updateSampleList();
// Update sample ID for next entry
document.getElementById('sampleId').value = 'SAMPLE-' + (sampleIdCounter).toString().padStart(3, '0');
});
// Update sample list display
function updateSampleList() {
const samples = calibrator.samples;
elements.sampleCount.textContent = samples.length;
if (samples.length === 0) {
elements.sampleList.innerHTML = '<p class="text-xs text-center py-4" style="color: var(--text-secondary);">No samples added yet</p>';
return;
}
elements.sampleList.innerHTML = samples.map(s => `
<div class="sample-card ${s.type} rounded-lg p-3 cursor-pointer hover:bg-opacity-80" data-id="${s.id}">
<div class="flex items-center justify-between mb-1">
<span class="font-medium text-sm">${s.name}</span>
<button class="delete-sample p-1 rounded hover:bg-red-500 hover:bg-opacity-20 transition-colors" data-id="${s.id}">
<svg class="w-3 h-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="18" y1="6" x2="6" y2="18"/>
<line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</button>
</div>
<div class="mono text-xs" style="color: var(--text-secondary);">
${s.c14Age} ± ${s.error} BP
${s.deltaR ? ` (ΔR: ${s.deltaR}±${s.deltaRError})` : ''}
</div>
<div class="flex items-center gap-2 mt-1">
<span class="text-xs px-1.5 py-0.5 rounded" style="background: var(--bg-primary);">
${s.type}
</span>
<span class="text-xs" style="color: var(--text-secondary);">
${s.prior.type}
</span>
</div>
</div>
`).join('');
// Add delete handlers
document.querySelectorAll('.delete-sample').forEach(btn => {
btn.addEventListener('click', function(e) {
e.stopPropagation();
const id = this.dataset.id;
calibrator.removeSample(id);
updateSampleList();
});
});
}
// Run calibration
elements.runCalibration.addEventListener('click', function() {
if (calibrator.samples.length === 0) {
alert('Please add at least one sample before calibration.');
return;
}
const btn = this;
btn.disabled = true;
btn.innerHTML = `
<svg class="w-4 h-4 animate-spin" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10" stroke-opacity="0.25"/>
<path d="M12 2a10 10 0 0110 10" stroke-linecap="round"/>
</svg>
Running...
`;
setTimeout(() => {
const iterValues = [1000, 5000, 10000, 50000, 100000];
const iterations = iterValues[parseInt(elements.iterations.value) - 1];
const results = calibrator.calibrate(elements.calCurve.value, iterations);
displayResults(results);
drawCalibrationPlot(results);
drawDistributions(results);
updatePhaseAnalysis(results);
btn.disabled = false;
btn.innerHTML = `
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polygon points="5,3 19,12 5,21" fill="currentColor"/>
</svg>
Run Calibration
`;
}, 100);
});
// Display calibration results
function displayResults(results) {
if (!results || results.length === 0) {
elements.resultsPanel.innerHTML = '<p class="text-xs text-center py-4" style="color: var(--text-secondary);">No results</p>';
return;
}
const proxyColors = {
terrestrial: 'var(--accent-c14)',
marine: 'var(--accent-marine)',
freshwater: 'var(--accent-freshwater)'
};
elements.resultsPanel.innerHTML = results.map(r => `
<div class="p-3 rounded-lg" style="background: var(--bg-primary); border-left: 2px solid ${proxyColors[r.sample.type]};">
<div class="font-semibold text-sm mb-2">${r.sample.name}</div>
<div class="space-y-1.5 text-xs mono">
<div class="flex justify-between">
<span style="color: var(--text-secondary);">Mode</span>
<span>${r.statistics.mode} cal BP</span>
</div>
<div class="flex justify-between">
<span style="color: var(--text-secondary);">Mean</span>
<span>${r.statistics.mean} cal BP</span>
</div>
<div class="flex justify-between">
<span style="color: var(--text-secondary);">± 1σ</span>
<span>±${r.statistics.std} years</span>
</div>
<div class="pt-1.5 border-t" style="border-color: var(--border);">
<div class="flex justify-between mb-1">
<span style="color: var(--text-secondary);">${(r.statistics.confidence * 100).toFixed(1)}% HPD</span>
</div>
<div class="text-right" style="color: var(--accent-posterior);">
${r.statistics.hpd.map(h => `${h.start}–${h.end}`).join(', ')}
</div>
</div>
</div>
</div>
`).join('');
}
// Update phase analysis
function updatePhaseAnalysis(results) {
if (!results || results.length < 2) {
elements.phaseResults.innerHTML = '<p style="color: var(--text-secondary);">Add 2+ samples for phase analysis</p>';
return;
}
const sorted = [...results].sort((a, b) => a.statistics.mean - b.statistics.mean);
let html = '<div class="space-y-2">';
sorted.forEach((r, i) => {
const next = sorted[i + 1];
const gap = next ? next.statistics.mean - r.statistics.mean : null;
html += `
<div class="flex items-center gap-2">
<div class="w-2 h-2 rounded-full" style="background: var(--accent-c14);"></div>
<span class="flex-1">${r.sample.name}</span>
<span style="color: var(--text-secondary);">${r.statistics.mean} BP</span>
</div>
${gap !== null ? `
<div class="ml-4 pl-2 border-l text-xs" style="border-color: var(--border); color: var(--text-secondary);">
Δ ${gap} years
</div>
` : ''}
`;
});
html += '</div>';
elements.phaseResults.innerHTML = html;
}
// ============================================
// CANVAS VISUALIZATIONS
// ============================================
function drawCalibrationPlot(results) {
const canvas = elements.calibrationCanvas;
const ctx = canvas.getContext('2d');
const dpr = window.devicePixelRatio || 1;
// Set canvas size
const rect = canvas.parentElement.getBoundingClientRect();
const width = rect.width - 32;
const height = Math.max(300, Math.min(400, window.innerHeight * 0.4));
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
ctx.scale(dpr, dpr);
// Clear
ctx.fillStyle = '#0a0f14';
ctx.fillRect(0, 0, width, height);
// Margins
const margin = { top: 20, right: 60, bottom: 40, left: 60 };
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
// Draw grid
ctx.strokeStyle = 'rgba(42, 58, 74, 0.5)';
ctx.lineWidth = 1;
// X grid
const xTicks = 6;
const calRange = { min: 0, max: 55000 };
for (let i = 0; i <= xTicks; i++) {
const x = margin.left + (plotWidth / xTicks) * i;
ctx.beginPath();
ctx.moveTo(x, margin.top);
ctx.lineTo(x, height - margin.bottom);
ctx.stroke();
}
// Y grid
const yTicks = 5;
for (let i = 0; i <= yTicks; i++) {
const y = margin.top + (plotHeight / yTicks) * i;
ctx.beginPath();
ctx.moveTo(margin.left, y);
ctx.lineTo(width - margin.right, y);
ctx.stroke();
}
// Draw calibration curve
const curve = calibrationCurves[elements.calCurve.value];
const c14Range = { min: 0, max: 50000 };
ctx.strokeStyle = '#00d4aa';
ctx.lineWidth = 2;
ctx.beginPath();
let firstPoint = true;
for (const point of curve) {
if (point.calBP % 10 !== 0) continue;
const x = margin.left + ((point.calBP - calRange.min) / (calRange.max - calRange.min)) * plotWidth;
const y = height - margin.bottom - ((point.c14Age - c14Range.min) / (c14Range.max - c14Range.min)) * plotHeight;
if (y >= margin.top && y <= height - margin.bottom) {
if (firstPoint) {
ctx.moveTo(x, y);
firstPoint = false;
} else {
ctx.lineTo(x, y);
}
}
}
ctx.stroke();
// Draw uncertainty bands if enabled
if (elements.showBands.checked) {
ctx.fillStyle = 'rgba(0, 212, 170, 0.1)';
ctx.beginPath();
for (let i = 0; i < curve.length; i += 10) {
const point = curve[i];
const x = margin.left + ((point.calBP - calRange.min) / (calRange.max - calRange.min)) * plotWidth;
const yUpper = height - margin.bottom - ((point.c14Age + point.error - c14Range.min) / (c14Range.max - c14Range.min)) * plotHeight;
if (yUpper >= margin.top && yUpper <= height - margin.bottom) {
if (i === 0) ctx.moveTo(x, yUpper);
else ctx.lineTo(x, yUpper);
}
}
for (let i = curve.length - 1; i >= 0; i -= 10) {
const point = curve[i];
const x = margin.left + ((point.calBP - calRange.min) / (calRange.max - calRange.min)) * plotWidth;
const yLower = height - margin.bottom - ((point.c14Age - point.error - c14Range.min) / (c14Range.max - c14Range.min)) * plotHeight;
if (yLower >= margin.top && yLower <= height - margin.bottom) {
ctx.lineTo(x, yLower);
}
}
ctx.closePath();
ctx.fill();
}
// Draw posterior distributions
if (results && results.length > 0) {
const colors = {
terrestrial: '#00d4aa',
marine: '#00a8ff',
freshwater: '#7c5cff'
};
let maxProb = 0;
for (const r of results) {
for (const p of r.posterior) {
if (p.probability > maxProb) maxProb = p.probability;
}
}
for (const result of results) {
const color = colors[result.sample.type] || '#00d4aa';
// Fill area
ctx.fillStyle = color.replace(')', ', 0.2)').replace('rgb', 'rgba').replace('#', '');
if (color.startsWith('#')) {
const r = parseInt(color.slice(1, 3), 16);
const g = parseInt(color.slice(3, 5), 16);
const b = parseInt(color.slice(5, 7), 16);
ctx.fillStyle = `rgba(${r}, ${g}, ${b}, 0.15)`;
}
ctx.beginPath();
ctx.moveTo(margin.left, height - margin.bottom);
for (let i = 0; i < result.posterior.length; i += 5) {
const p = result.posterior[i];
const x = margin.left + ((p.calBP - calRange.min) / (calRange.max - calRange.min)) * plotWidth;
const y = height - margin.bottom - (p.probability / maxProb) * (plotHeight * 0.4);
ctx.lineTo(x, y);
}
ctx.lineTo(width - margin.right, height - margin.bottom);
ctx.closePath();
ctx.fill();
// Line
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.beginPath();
for (let i = 0; i < result.posterior.length; i += 5) {
const p = result.posterior[i];
const x = margin.left + ((p.calBP - calRange.min) / (calRange.max - calRange.min)) * plotWidth;
const y = height - margin.bottom - (p.probability / maxProb) * (plotHeight * 0.4);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.stroke();
// Mark mode
const mode = result.statistics.mode;
const modeX = margin.left + ((mode - calRange.min) / (calRange.max - calRange.min)) * plotWidth;
ctx.strokeStyle = '#ffcc00';
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
ctx.beginPath();
ctx.moveTo(modeX, margin.top);
ctx.lineTo(modeX, height - margin.bottom);
ctx.stroke();
ctx.setLineDash([]);
// Label
ctx.fillStyle = '#ffcc00';
ctx.font = '10px JetBrains Mono';
ctx.textAlign = 'center';
ctx.fillText(result.sample.name, modeX, margin.top + 10);
}
// Draw samples on curve
for (const result of results) {
const sample = result.sample;
const color = colors[sample.type] || '#00d4aa';
// Find calibration curve point for this sample
const closestPoint = findClosestCurvePoint(sample.c14Age, curve);
const x = margin.left + ((closestPoint.calBP - calRange.min) / (calRange.max - calRange.min)) * plotWidth;
const y = height - margin.bottom - ((sample.c14Age - c14Range.min) / (c14Range.max - c14Range.min)) * plotHeight;
// Error bar
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(x - 6, y - (sample.error / (c14Range.max - c14Range.min)) * plotHeight);
ctx.lineTo(x + 6, y - (sample.error / (c14Range.max - c14Range.min)) * plotHeight);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x - 6, y + (sample.error / (c14Range.max - c14Range.min)) * plotHeight);
ctx.lineTo(x + 6, y + (sample.error / (c14Range.max - c14Range.min)) * plotHeight);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x, y - (sample.error / (c14Range.max - c14Range.min)) * plotHeight);
ctx.lineTo(x, y + (sample.error / (c13Range.max - c14Range.min)) * plotHeight);
ctx.stroke();
// Point
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, 4, 0, Math.PI * 2);
ctx.fill();
}
}
// Axis labels
ctx.fillStyle = '#8899aa';
ctx.font = '11px Space Grotesk';
// X axis
ctx.textAlign = 'center';
for (let i = 0; i <= xTicks; i++) {
const val = Math.round((calRange.max - calRange.min) * (i / xTicks));
const x = margin.left + (plotWidth / xTicks) * i;
ctx.fillText((val / 1000).toFixed(0) + 'k', x, height - margin.bottom + 20);
}
ctx.fillText('Calibrated Age (cal BP)', width / 2, height - 5);
// Y axis
ctx.textAlign = 'right';
for (let i = 0; i <= yTicks; i++) {
const val = Math.round(c14Range.min + (c14Range.max - c14Range.min) * (1 - i / yTicks));
const y = margin.top + (plotHeight / yTicks) * i;
ctx.fillText((val / 1000).toFixed(0) + 'k', margin.left - 10, y + 4);
}
ctx.save();
ctx.translate(15, height / 2);
ctx.rotate(-Math.PI / 2);
ctx.textAlign = 'center';
ctx.fillText('14C Age (BP)', 0, 0);
ctx.restore();
}
// Fix the c13Range typo
function findClosestCurvePoint(c14Age, curve) {
let closest = curve[0];
let minDiff = Math.abs(curve[0].c14Age - c14Age);
for (const point of curve) {
const diff = Math.abs(point.c14Age - c14Age);
if (diff < minDiff) {
minDiff = diff;
closest = point;
}
}
return closest;
}
// Variable was referenced before - define c13Range
const c13Range = { max: 50000, min: 0 };
function drawDistributions(results) {
if (!results || results.length === 0) return;
drawLikelihoodPlot(results);
drawPosteriorPlot(results);
}
function drawLikelihoodPlot(results) {
const canvas = elements.likelihoodCanvas;
const ctx = canvas.getContext('2d');
const dpr = window.devicePixelRatio || 1;
const rect = canvas.parentElement.getBoundingClientRect();
const width = rect.width - 32;
const height = 180;
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
ctx.scale(dpr, dpr);
ctx.fillStyle = '#0a0f14';
ctx.fillRect(0, 0, width, height);
const margin = { top: 15, right: 20, bottom: 30, left: 40 };
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
// Grid
ctx.strokeStyle = 'rgba(42, 58, 74, 0.5)';
ctx.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const y = margin.top + (plotHeight / 4) * i;
ctx.beginPath();
ctx.moveTo(margin.left, y);
ctx.lineTo(width - margin.right, y);
ctx.stroke();
}
// Draw likelihoods
const colors = {
terrestrial: '#00d4aa',
marine: '#00a8ff',
freshwater: '#7c5cff'
};
let maxLik = 0;
for (const r of results) {
for (const p of r.posterior) {
if (p.likelihood > maxLik) maxLik = p.likelihood;
}
}
const range = { min: 0, max: 55000 };
for (const result of results) {
const color = colors[result.sample.type] || '#00d4aa';
// Normalize for display
let localMax = 0;
for (const p of result.posterior) {
if (p.likelihood > localMax) localMax = p.likelihood;
}
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.beginPath();
let first = true;
for (let i = 0; i < result.posterior.length; i += 5) {
const p = result.posterior[i];
const x = margin.left + ((p.calBP - range.min) / (range.max - range.min)) * plotWidth;
const y = height - margin.bottom - (p.likelihood / localMax) * plotHeight;
if (first) {
ctx.moveTo(x, y);
first = false;
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
}
// Axis
ctx.fillStyle = '#8899aa';
ctx.font = '10px Space Grotesk';
ctx.textAlign = 'center';
ctx.fillText('Calibrated Age (cal BP)', width / 2, height - 5);
}
function drawPosteriorPlot(results) {
const canvas = elements.posteriorCanvas;
const ctx = canvas.getContext('2d');
const dpr = window.devicePixelRatio || 1;
const rect = canvas.parentElement.getBoundingClientRect();
const width = rect.width - 32;
const height = 180;
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
ctx.scale(dpr, dpr);
ctx.fillStyle = '#0a0f14';
ctx.fillRect(0, 0, width, height);
const margin = { top: 15, right: 20, bottom: 30, left: 40 };
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
// Grid
ctx.strokeStyle = 'rgba(42, 58, 74, 0.5)';
ctx.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const y = margin.top + (plotHeight / 4) * i;
ctx.beginPath();
ctx.moveTo(margin.left, y);
ctx.lineTo(width - margin.right, y);
ctx.stroke();
}
const colors = {
terrestrial: '#00d4aa',
marine: '#00a8ff',
freshwater: '#7c5cff'
};
let maxProb = 0;
for (const r of results) {
for (const p of r.posterior) {
if (p.probability > maxProb) maxProb = p.probability;
}
}
const range = { min: 0, max: 55000 };
for (const result of results) {
const color = colors[result.sample.type] || '#00d4aa';
// Fill
if (color.startsWith('#')) {
const r = parseInt(color.slice(1, 3), 16);
const g = parseInt(color.slice(3, 5), 16);
const b = parseInt(color.slice(5, 7), 16);
ctx.fillStyle = `rgba(${r}, ${g}, ${b}, 0.2)`;
}
ctx.beginPath();
ctx.moveTo(margin.left, height - margin.bottom);
for (let i = 0; i < result.posterior.length; i += 3) {
const p = result.posterior[i];
const x = margin.left + ((p.calBP - range.min) / (range.max - range.min)) * plotWidth;
const y = height - margin.bottom - (p.probability / maxProb) * plotHeight;
ctx.lineTo(x, y);
}
ctx.lineTo(width - margin.right, height - margin.bottom);
ctx.closePath();
ctx.fill();
// Line
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.beginPath();
let first = true;
for (let i = 0; i < result.posterior.length; i += 3) {
const p = result.posterior[i];
const x = margin.left + ((p.calBP - range.min) / (range.max - range.min)) * plotWidth;
const y = height - margin.bottom - (p.probability / maxProb) * plotHeight;
if (first) {
ctx.moveTo(x, y);
first = false;
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
// HPD region marker
const hpd = result.statistics.hpd[0];
if (hpd) {
const startX = margin.left + ((hpd.start - range.min) / (range.max - range.min)) * plotWidth;
const endX = margin.left + ((hpd.end - range.min) / (range.max - range.min)) * plotWidth;
ctx.fillStyle = 'rgba(255, 204, 0, 0.1)';
ctx.fillRect(startX, margin.top, endX - startX, plotHeight);
}
}
// Axis
ctx.fillStyle = '#8899aa';
ctx.font = '10px Space Grotesk';
ctx.textAlign = 'center';
ctx.fillText('Calibrated Age (cal BP)', width / 2, height - 5);
}
// ============================================
// EXPORT FUNCTIONS
// ============================================
elements.exportCSV.addEventListener('click', function() {
if (!calibrator.results || calibrator.results.length === 0) {
alert('No results to export. Run calibration first.');
return;
}
let csv = 'Sample,Type,C14_Age,C14_Error,DeltaR,DeltaR_Error,Prior_Type,Mode,Mean,Std,HPD_Start,HPD_End,Confidence\n';
for (const r of calibrator.results) {
csv += `${r.sample.name},${r.sample.type},${r.sample.c14Age},${r.sample.error},${r.sample.deltaR},${r.sample.deltaRError},${r.sample.prior.type},${r.statistics.mode},${r.statistics.mean},${r.statistics.std},${r.statistics.hpd[0]?.start || ''},${r.statistics.hpd[0]?.end || ''},${r.statistics.confidence}\n`;
}
downloadFile(csv, 'radiocarbon_calibration.csv', 'text/csv');
});
elements.exportJSON.addEventListener('click', function() {
if (!calibrator.results || calibrator.results.length === 0) {
alert('No results to export. Run calibration first.');
return;
}
const data = {
calibrationCurve: elements.calCurve.value,
samples: calibrator.samples,
results: calibrator.results.map(r => ({
sample: r.sample.name,
statistics: r.statistics
})),
exportedAt: new Date().toISOString()
};
downloadFile(JSON.stringify(data, null, 2), 'radiocarbon_calibration.json', 'application/json');
});
function downloadFile(content, filename, type) {
const blob = new Blob([content], { type });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
// ============================================
// INITIALIZATION
// ============================================
function init() {
// Draw empty calibration curve
drawCalibrationPlot(null);
// Add some demo samples
document.getElementById('sampleId').value = 'DEMO-001';
document.getElementById('c14Age').value = '4200';
document.getElementById('c14Error').value = '25';
document.getElementById('proxyType').value = 'terrestrial';
elements.addSample.click();
document.getElementById('sampleId').value = 'DEMO-002';
document.getElementById('c14Age').value = '4350';
document.getElementById('c14Error').value = '30';
document.getElementById('proxyType').value = 'marine';
document.getElementById('deltaR').value = '350';
document.getElementById('deltaRError').value = '20';
elements.proxyType.dispatchEvent(new Event('change'));
elements.addSample.click();
// Resize handler
let resizeTimeout;
window.addEventListener('resize', function() {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => {
drawCalibrationPlot(calibrator.results);
if (calibrator.results) {
drawDistributions(calibrator.results);
}
}, 150);
});
}
init();
</script>
</body>
</html>
The tool uses a simplified IntCal20-style calibration curve (synthetic but realistic) for demonstration. For production use, you'd integrate actual calibration curve data from the official IntCal database.