Build a dendrochronology climate signal extraction: cross-dating, chronologies, and…
- User
Build a dendrochronology climate signal extraction: cross-dating, chronologies, and validation.
Assistant
Build a dendrochronology climate signal extraction: cross-dating, chronologies, and validation.
The user wants a dendrochronology climate signal extraction tool. This is a scientific application used in tree-ring analysis to:
I'll create a comprehensive dendrochronology application with:
Key features:
I'll use:
Let me build this comprehensive tool.
This is a comprehensive scientific application for tree-ring analysis including cross-dating, chronology building, and statistical validation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dendrochronology Climate Signal Extraction</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=Source+Serif+4:wght@400;600;700&display=swap" rel="stylesheet">
<style>
:root {
--bg: #1a1714;
--bg-elevated: #252220;
--bg-card: #2d2926;
--fg: #e8e2dc;
--fg-muted: #9a938c;
--accent: #c4956a;
--accent-bright: #e0a878;
--ring-early: #d4a574;
--ring-late: #8b6f47;
--positive: #6b9b7a;
--negative: #b87a6b;
--border: #3d3835;
--glow: rgba(196, 149, 106, 0.15);
}
* {
box-sizing: border-box;
}
body {
font-family: 'IBM Plex Mono', monospace;
background: var(--bg);
color: var(--fg);
}
h1, h2, h3, h4 {
font-family: 'Source Serif 4', serif;
}
.pattern-bg {
background-image:
radial-gradient(circle at 20% 80%, var(--glow) 0%, transparent 50%),
radial-gradient(circle at 80% 20%, rgba(107, 155, 122, 0.08) 0%, transparent 40%),
url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Ccircle cx='30' cy='30' r='0.5' fill='%23c4956a' fill-opacity='0.1'/%3E%3C/svg%3E");
}
.tree-ring-pattern {
background: repeating-conic-gradient(
from 0deg,
var(--ring-early) 0deg 2deg,
var(--ring-late) 2deg 4deg
);
}
.scrollbar-thin::-webkit-scrollbar {
width: 6px;
height: 6px;
}
.scrollbar-thin::-webkit-scrollbar-track {
background: var(--bg);
}
.scrollbar-thin::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 3px;
}
.btn-primary {
background: linear-gradient(135deg, var(--accent) 0%, var(--accent-bright) 100%);
color: var(--bg);
transition: all 0.2s ease;
}
.btn-primary:hover {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(196, 149, 106, 0.3);
}
.btn-secondary {
background: var(--bg-card);
border: 1px solid var(--border);
color: var(--fg);
transition: all 0.2s ease;
}
.btn-secondary:hover {
border-color: var(--accent);
background: var(--bg-elevated);
}
.input-field {
background: var(--bg);
border: 1px solid var(--border);
color: var(--fg);
transition: border-color 0.2s ease;
}
.input-field:focus {
outline: none;
border-color: var(--accent);
}
.card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 8px;
}
.tab-active {
background: var(--bg-card);
border-bottom: 2px solid var(--accent);
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.animate-fade-in {
animation: fadeIn 0.4s ease forwards;
}
.stagger-1 { animation-delay: 0.1s; }
.stagger-2 { animation-delay: 0.2s; }
.stagger-3 { animation-delay: 0.3s; }
.stagger-4 { animation-delay: 0.4s; }
.ring-highlight {
animation: pulse 2s ease-in-out infinite;
}
canvas {
image-rendering: crisp-edges;
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
</style>
</head>
<body class="min-h-screen pattern-bg">
<!-- Header -->
<header class="border-b border-[var(--border)] bg-[var(--bg)]/80 backdrop-blur-sm sticky top-0 z-50">
<div class="max-w-7xl mx-auto px-4 py-4 flex items-center justify-between">
<div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-full tree-ring-pattern opacity-80"></div>
<div>
<h1 class="text-xl font-bold text-[var(--fg)]">DendroLab</h1>
<p class="text-xs text-[var(--fg-muted)]">Climate Signal Extraction</p>
</div>
</div>
<div class="flex items-center gap-4">
<span class="text-xs text-[var(--fg-muted)]" id="statusText">Ready</span>
<button onclick="showHelp()" class="btn-secondary px-3 py-1.5 rounded text-xs">
Guide
</button>
</div>
</div>
</header>
<!-- Main Content -->
<main class="max-w-7xl mx-auto px-4 py-6">
<!-- Tabs -->
<nav class="flex gap-1 mb-6 border-b border-[var(--border)]" role="tablist">
<button onclick="switchTab('data')" class="tab-btn px-4 py-3 text-sm tab-active" data-tab="data" role="tab" aria-selected="true">
Data Input
</button>
<button onclick="switchTab('crossdating')" class="tab-btn px-4 py-3 text-sm" data-tab="crossdating" role="tab" aria-selected="false">
Cross-Dating
</button>
<button onclick="switchTab('chronology')" class="tab-btn px-4 py-3 text-sm" data-tab="chronology" role="tab" aria-selected="false">
Chronology
</button>
<button onclick="switchTab('extraction')" class="tab-btn px-4 py-3 text-sm" data-tab="extraction" role="tab" aria-selected="false">
Signal Extraction
</button>
<button onclick="switchTab('validation')" class="tab-btn px-4 py-3 text-sm" data-tab="validation" role="tab" aria-selected="false">
Validation
</button>
</nav>
<!-- Data Input Panel -->
<section id="panel-data" class="tab-panel animate-fade-in">
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Sample Input -->
<div class="lg:col-span-1 card p-5">
<h3 class="text-lg font-semibold mb-4 text-[var(--accent)]">Sample Series</h3>
<div class="space-y-4">
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Sample ID</label>
<input type="text" id="sampleId" value="OAK-2024-001" class="input-field w-full px-3 py-2 rounded text-sm">
</div>
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Start Year</label>
<input type="number" id="startYear" value="1900" class="input-field w-full px-3 py-2 rounded text-sm">
</div>
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Ring Width Data (comma-separated, mm)</label>
<textarea id="ringData" rows="6" class="input-field w-full px-3 py-2 rounded text-sm scrollbar-thin" placeholder="1.23, 1.45, 0.98, ..."></textarea>
</div>
<div class="flex gap-2">
<button onclick="addSample()" class="btn-primary px-4 py-2 rounded text-sm font-medium flex-1">
Add Sample
</button>
<button onclick="generateSampleData()" class="btn-secondary px-4 py-2 rounded text-sm">
Generate
</button>
</div>
<button onclick="loadDemoDataset()" class="btn-secondary w-full px-4 py-2 rounded text-sm">
Load Demo Dataset
</button>
</div>
</div>
<!-- Sample List -->
<div class="lg:col-span-2 card p-5">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-semibold text-[var(--accent)]">Loaded Series</h3>
<span class="text-xs text-[var(--fg-muted)]" id="sampleCount">0 samples</span>
</div>
<div id="sampleList" class="space-y-2 max-h-80 overflow-y-auto scrollbar-thin mb-4">
<p class="text-sm text-[var(--fg-muted)] text-center py-8">No samples loaded</p>
</div>
<div class="border-t border-[var(--border)] pt-4">
<canvas id="samplePreviewCanvas" width="600" height="200" class="w-full rounded bg-[var(--bg)]"></canvas>
</div>
</div>
</div>
</section>
<!-- Cross-Dating Panel -->
<section id="panel-crossdating" class="tab-panel hidden">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<!-- Cross-Dating Controls -->
<div class="card p-5">
<h3 class="text-lg font-semibold mb-4 text-[var(--accent)]">Cross-Dating Analysis</h3>
<div class="space-y-4">
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Reference Series</label>
<select id="referenceSeries" class="input-field w-full px-3 py-2 rounded text-sm">
<option value="">Select reference...</option>
</select>
</div>
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Target Series</label>
<select id="targetSeries" class="input-field w-full px-3 py-2 rounded text-sm">
<option value="">Select target...</option>
</select>
</div>
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Window Size (years)</label>
<input type="number" id="windowSize" value="50" min="10" max="100" class="input-field w-full px-3 py-2 rounded text-sm">
</div>
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Lag Range (years)</label>
<div class="flex gap-2">
<input type="number" id="lagMin" value="-20" class="input-field w-full px-3 py-2 rounded text-sm">
<span class="text-[var(--fg-muted)] self-center">to</span>
<input type="number" id="lagMax" value="20" class="input-field w-full px-3 py-2 rounded text-sm">
</div>
</div>
<button onclick="runCrossDating()" class="btn-primary w-full px-4 py-2 rounded text-sm font-medium">
Run Cross-Dating
</button>
</div>
</div>
<!-- Cross-Dating Results -->
<div class="card p-5">
<h3 class="text-lg font-semibold mb-4 text-[var(--accent)]">Correlation Results</h3>
<canvas id="crossDatingCanvas" width="500" height="250" class="w-full rounded bg-[var(--bg)] mb-4"></canvas>
<div id="crossDatingResults" class="space-y-3">
<div class="grid grid-cols-2 gap-4">
<div class="bg-[var(--bg)] p-3 rounded">
<p class="text-xs text-[var(--fg-muted)]">Best Correlation (r)</p>
<p class="text-xl font-semibold text-[var(--positive)]" id="bestCorrelation">—</p>
</div>
<div class="bg-[var(--bg)] p-3 rounded">
<p class="text-xs text-[var(--fg-muted)]">Optimal Lag</p>
<p class="text-xl font-semibold text-[var(--accent)]" id="optimalLag">—</p>
</div>
</div>
<div class="bg-[var(--bg)] p-3 rounded">
<p class="text-xs text-[var(--fg-muted)]">T-Value</p>
<p class="text-lg font-semibold" id="tValue">—</p>
</div>
<div class="bg-[var(--bg)] p-3 rounded">
<p class="text-xs text-[var(--fg-muted)]">Significance</p>
<p class="text-sm" id="significance">—</p>
</div>
</div>
</div>
</div>
<!-- Skeleton Plot -->
<div class="card p-5 mt-6">
<h3 class="text-lg font-semibold mb-4 text-[var(--accent)]">Skeleton Plot Comparison</h3>
<canvas id="skeletonPlotCanvas" width="1000" height="180" class="w-full rounded bg-[var(--bg)]"></canvas>
</div>
</section>
<!-- Chronology Panel -->
<section id="panel-chronology" class="tab-panel hidden">
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Standardization Options -->
<div class="card p-5">
<h3 class="text-lg font-semibold mb-4 text-[var(--accent)]">Standardization</h3>
<div class="space-y-4">
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Method</label>
<select id="stdMethod" class="input-field w-full px-3 py-2 rounded text-sm">
<option value="negexp">Negative Exponential</option>
<option value="spline">Cubic Spline</option>
<option value="mean">Mean Value</option>
<option value="ar">AR Modeling</option>
</select>
</div>
<div id="splineOptions" class="hidden">
<label class="block text-xs text-[var(--fg-muted)] mb-2">Spline Stiffness (%)</label>
<input type="range" id="splineStiffness" min="10" max="90" value="50" class="w-full accent-[var(--accent)]">
<p class="text-xs text-[var(--fg-muted)] mt-1">50% variance retained</p>
</div>
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Variance Stabilization</label>
<select id="varStabilization" class="input-field w-full px-3 py-2 rounded text-sm">
<option value="none">None</option>
<option value="rbar">Rbar-weighted</option>
<option value="cac">VSM (OSL)</option>
</select>
</div>
<button onclick="buildChronology()" class="btn-primary w-full px-4 py-2 rounded text-sm font-medium">
Build Chronology
</button>
</div>
<div class="mt-6 pt-4 border-t border-[var(--border)]">
<h4 class="text-sm font-semibold mb-3">Chronology Stats</h4>
<div class="space-y-2 text-sm">
<div class="flex justify-between">
<span class="text-[var(--fg-muted)]">Time Span</span>
<span id="timeSpan">—</span>
</div>
<div class="flex justify-between">
<span class="text-[var(--fg-muted)]">Mean</span>
<span id="chronoMean">—</span>
</div>
<div class="flex justify-between">
<span class="text-[var(--fg-muted)]">Std Dev</span>
<span id="chronoStd">—</span>
</div>
<div class="flex justify-between">
<span class="text-[var(--fg-muted)]">Series Intercorrelation</span>
<span id="intercorr">—</span>
</div>
</div>
</div>
</div>
<!-- Chronology Visualization -->
<div class="lg:col-span-2 card p-5">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-semibold text-[var(--accent)]">Master Chronology</h3>
<div class="flex gap-2">
<button onclick="toggleView('raw')" class="btn-secondary px-3 py-1 rounded text-xs view-btn" data-view="raw">Raw</button>
<button onclick="toggleView('indexed')" class="btn-secondary px-3 py-1 rounded text-xs view-btn active" data-view="indexed">Indexed</button>
</div>
</div>
<canvas id="chronologyCanvas" width="700" height="300" class="w-full rounded bg-[var(--bg)] mb-4"></canvas>
<div class="grid grid-cols-3 gap-4">
<div>
<p class="text-xs text-[var(--fg-muted)] mb-1">Sample Depth</p>
<canvas id="sampleDepthCanvas" width="200" height="80" class="w-full rounded bg-[var(--bg)]"></canvas>
</div>
<div>
<p class="text-xs text-[var(--fg-muted)] mb-1">Running Rbar</p>
<canvas id="runningRbarCanvas" width="200" height="80" class="w-full rounded bg-[var(--bg)]"></canvas>
</div>
<div>
<p class="text-xs text-[var(--fg-muted)] mb-1">EPS</p>
<canvas id="epsCanvas" width="200" height="80" class="w-full rounded bg-[var(--bg)]"></canvas>
</div>
</div>
</div>
</div>
</section>
<!-- Signal Extraction Panel -->
<section id="panel-extraction" class="tab-panel hidden">
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Extraction Controls -->
<div class="card p-5">
<h3 class="text-lg font-semibold mb-4 text-[var(--accent)]">Climate Signal</h3>
<div class="space-y-4">
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Target Climate Variable</label>
<select id="climateVar" class="input-field w-full px-3 py-2 rounded text-sm">
<option value="temp">Temperature</option>
<option value="precip">Precipitation</option>
<option value="pdsi">PDSI (Drought Index)</option>
<option value="custom">Custom Variable</option>
</select>
</div>
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Season Definition</label>
<div class="flex gap-2">
<select id="seasonStart" class="input-field w-full px-3 py-2 rounded text-sm">
<option value="1">January</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5" selected>May</option>
<option value="6">June</option>
</select>
<span class="text-[var(--fg-muted)] self-center">-</span>
<select id="seasonEnd" class="input-field w-full px-3 py-2 rounded text-sm">
<option value="7">July</option>
<option value="8">August</option>
<option value="9" selected>September</option>
<option value="10">October</option>
</select>
</div>
</div>
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Analysis Method</label>
<select id="analysisMethod" class="input-field w-full px-3 py-2 rounded text-sm">
<option value="corr">Correlation Analysis</option>
<option value="regression">Regression</option>
<option value="response">Response Function</option>
</select>
</div>
<button onclick="extractSignal()" class="btn-primary w-full px-4 py-2 rounded text-sm font-medium">
Extract Signal
</button>
<button onclick="loadClimateData()" class="btn-secondary w-full px-4 py-2 rounded text-sm">
Load Climate Data
</button>
</div>
</div>
<!-- Climate Response -->
<div class="lg:col-span-2 card p-5">
<h3 class="text-lg font-semibold mb-4 text-[var(--accent)]">Climate Response Analysis</h3>
<canvas id="climateResponseCanvas" width="700" height="280" class="w-full rounded bg-[var(--bg)] mb-4"></canvas>
<div class="grid grid-cols-2 gap-4">
<div class="bg-[var(--bg)] p-3 rounded">
<p class="text-xs text-[var(--fg-muted)]">Correlation with Climate</p>
<p class="text-xl font-semibold text-[var(--positive)]" id="climateCorr">—</p>
</div>
<div class="bg-[var(--bg)] p-3 rounded">
<p class="text-xs text-[var(--fg-muted)]">Explained Variance (R²)</p>
<p class="text-xl font-semibold" id="explainedVar">—</p>
</div>
</div>
</div>
</div>
<!-- Monthly Response -->
<div class="card p-5 mt-6">
<h3 class="text-lg font-semibold mb-4 text-[var(--accent)]">Monthly Response Function</h3>
<canvas id="monthlyResponseCanvas" width="1000" height="200" class="w-full rounded bg-[var(--bg)]"></canvas>
</div>
</section>
<!-- Validation Panel -->
<section id="panel-validation" class="tab-panel hidden">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<!-- Validation Metrics -->
<div class="card p-5">
<h3 class="text-lg font-semibold mb-4 text-[var(--accent)]">Statistical Validation</h3>
<div class="space-y-4">
<div>
<label class="block text-xs text-[var(--fg-muted)] mb-2">Validation Method</label>
<select id="validationMethod" class="input-field w-full px-3 py-2 rounded text-sm">
<option value="split">Split-Sample</option>
<option value="leaveone">Leave-One-Out</option>
<option value="bootstrap">Bootstrap</option>
<option value="jackknife">Jackknife</option>
</select>
</div>
<div id="splitOptions">
<label class="block text-xs text-[var(--fg-muted)] mb-2">Calibration Period</label>
<div class="flex gap-2 items-center">
<input type="number" id="calibStart" value="1900" class="input-field w-full px-3 py-2 rounded text-sm">
<span class="text-[var(--fg-muted)]">-</span>
<input type="number" id="calibEnd" value="1970" class="input-field w-full px-3 py-2 rounded text-sm">
</div>
<p class="text-xs text-[var(--fg-muted)] mt-2">Verification: remainder of series</p>
</div>
<button onclick="runValidation()" class="btn-primary w-full px-4 py-2 rounded text-sm font-medium">
Run Validation
</button>
</div>
<div class="mt-6 pt-4 border-t border-[var(--border)]">
<h4 class="text-sm font-semibold mb-3">Calibration Statistics</h4>
<div class="grid grid-cols-2 gap-3 text-sm">
<div class="bg-[var(--bg)] p-2 rounded">
<p class="text-xs text-[var(--fg-muted)]">R² (calibration)</p>
<p class="font-semibold" id="r2Calib">—</p>
</div>
<div class="bg-[var(--bg)] p-2 rounded">
<p class="text-xs text-[var(--fg-muted)]">R² (verification)</p>
<p class="font-semibold" id="r2Verif">—</p>
</div>
<div class="bg-[var(--bg)] p-2 rounded">
<p class="text-xs text-[var(--fg-muted)]">RE (Reduction of Error)</p>
<p class="font-semibold" id="reStat">—</p>
</div>
<div class="bg-[var(--bg)] p-2 rounded">
<p class="text-xs text-[var(--fg-muted)]">CE (Coefficient of Efficiency)</p>
<p class="font-semibold" id="ceStat">—</p>
</div>
</div>
</div>
</div>
<!-- Validation Results -->
<div class="card p-5">
<h3 class="text-lg font-semibold mb-4 text-[var(--accent)]">Validation Results</h3>
<canvas id="validationCanvas" width="500" height="280" class="w-full rounded bg-[var(--bg)] mb-4"></canvas>
<div class="bg-[var(--bg)] p-3 rounded">
<p class="text-xs text-[var(--fg-muted)] mb-2">Quality Assessment</p>
<div id="qualityAssessment" class="flex items-center gap-3">
<span class="text-2xl">—</span>
<p class="text-sm text-[var(--fg-muted)]">Run validation to assess</p>
</div>
</div>
</div>
</div>
<!-- Quality Metrics Table -->
<div class="card p-5 mt-6">
<h3 class="text-lg font-semibold mb-4 text-[var(--accent)]">Chronology Quality Metrics</h3>
<div class="overflow-x-auto scrollbar-thin">
<table class="w-full text-sm">
<thead>
<tr class="border-b border-[var(--border)]">
<th class="text-left py-3 px-4 text-[var(--fg-muted)] font-medium">Metric</th>
<th class="text-left py-3 px-4 text-[var(--fg-muted)] font-medium">Value</th>
<th class="text-left py-3 px-4 text-[var(--fg-muted)] font-medium">Threshold</th>
<th class="text-left py-3 px-4 text-[var(--fg-muted)] font-medium">Status</th>
</tr>
</thead>
<tbody id="metricsTable">
<tr class="border-b border-[var(--border)]/50">
<td class="py-3 px-4">Expressed Population Signal (EPS)</td>
<td class="py-3 px-4" id="epsValue">—</td>
<td class="py-3 px-4">> 0.85</td>
<td class="py-3 px-4" id="epsStatus">—</td>
</tr>
<tr class="border-b border-[var(--border)]/50">
<td class="py-3 px-4">Mean Interseries Correlation (Rbar)</td>
<td class="py-3 px-4" id="rbarValue">—</td>
<td class="py-3 px-4">> 0.30</td>
<td class="py-3 px-4" id="rbarStatus">—</td>
</tr>
<tr class="border-b border-[var(--border)]/50">
<td class="py-3 px-4">Subsample Signal Strength (SSS)</td>
<td class="py-3 px-4" id="sssValue">—</td>
<td class="py-3 px-4">> 0.75</td>
<td class="py-3 px-4" id="sssStatus">—</td>
</tr>
<tr class="border-b border-[var(--border)]/50">
<td class="py-3 px-4">First Order Autocorrelation (AC1)</td>
<td class="py-3 px-4" id="ac1Value">—</td>
<td class="py-3 px-4">< 0.70</td>
<td class="py-3 px-4" id="ac1Status">—</td>
</tr>
<tr>
<td class="py-3 px-4">Mean Sensitivity (MS)</td>
<td class="py-3 px-4" id="msValue">—</td>
<td class="py-3 px-4">0.15 - 0.40</td>
<td class="py-3 px-4" id="msStatus">—</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</main>
<!-- Help Modal -->
<div id="helpModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4">
<div class="card max-w-lg w-full max-h-[80vh] overflow-y-auto p-6 scrollbar-thin">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-semibold text-[var(--accent)]">User Guide</h3>
<button onclick="closeHelp()" class="text-[var(--fg-muted)] hover:text-[var(--fg)]">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 6L6 18M6 6l12 12"/>
</svg>
</button>
</div>
<div class="space-y-4 text-sm">
<div>
<h4 class="font-semibold mb-2">1. Data Input</h4>
<p class="text-[var(--fg-muted)]">Enter ring width measurements manually or generate synthetic data. Click "Load Demo Dataset" to get started quickly.</p>
</div>
<div>
<h4 class="font-semibold mb-2">2. Cross-Dating</h4>
<p class="text-[var(--fg-muted)]">Match patterns between series to verify dating. The skeleton plot shows narrow rings as vertical bars for visual comparison.</p>
</div>
<div>
<h4 class="font-semibold mb-2">3. Chronology</h4>
<p class="text-[var(--fg-muted)]">Standardize series using negative exponential or spline detrending. Build a master chronology from all samples.</p>
</div>
<div>
<h4 class="font-semibold mb-2">4. Signal Extraction</h4>
<p class="text-[var(--fg-muted)]">Correlate chronology with climate variables. Monthly response shows which months have strongest influence.</p>
</div>
<div>
<h4 class="font-semibold mb-2">5. Validation</h4>
<p class="text-[var(--fg-muted)]">Assess chronology quality using split-sample calibration/verification. Check EPS, Rbar, and other metrics.</p>
</div>
</div>
</div>
</div>
<script>
// ============================================
// STATE & DATA
// ============================================
const state = {
samples: [],
chronology: null,
climateData: null,
activeTab: 'data',
analysisResults: null
};
// ============================================
// TAB NAVIGATION
// ============================================
function switchTab(tabName) {
document.querySelectorAll('.tab-panel').forEach(p => p.classList.add('hidden'));
document.querySelectorAll('.tab-btn').forEach(b => {
b.classList.remove('tab-active');
b.setAttribute('aria-selected', 'false');
});
const panel = document.getElementById(`panel-${tabName}`);
const btn = document.querySelector(`[data-tab="${tabName}"]`);
if (panel && btn) {
panel.classList.remove('hidden');
panel.classList.add('animate-fade-in');
btn.classList.add('tab-active');
btn.setAttribute('aria-selected', 'true');
state.activeTab = tabName;
}
updateStatus(`Viewing ${tabName}`);
}
// ============================================
// SAMPLE MANAGEMENT
// ============================================
function addSample() {
const id = document.getElementById('sampleId').value.trim();
const startYear = parseInt(document.getElementById('startYear').value);
const dataStr = document.getElementById('ringData').value.trim();
if (!id || !dataStr) {
updateStatus('Please enter sample ID and data');
return;
}
const data = dataStr.split(',').map(v => parseFloat(v.trim())).filter(v => !isNaN(v) && v > 0);
if (data.length < 10) {
updateStatus('Need at least 10 valid ring measurements');
return;
}
state.samples.push({
id,
startYear,
data,
endYear: startYear + data.length - 1
});
updateSampleList();
updateStatus(`Added sample ${id}`);
clearSampleForm();
}
function removeSample(index) {
const removed = state.samples.splice(index, 1);
updateSampleList();
updateStatus(`Removed ${removed[0].id}`);
}
function clearSampleForm() {
document.getElementById('ringData').value = '';
const num = state.samples.length + 1;
document.getElementById('sampleId').value = `OAK-2024-${String(num).padStart(3, '0')}`;
}
function updateSampleList() {
const list = document.getElementById('sampleList');
const count = document.getElementById('sampleCount');
count.textContent = `${state.samples.length} sample${state.samples.length !== 1 ? 's' : ''}`;
if (state.samples.length === 0) {
list.innerHTML = '<p class="text-sm text-[var(--fg-muted)] text-center py-8">No samples loaded</p>';
drawSamplePreview();
return;
}
list.innerHTML = state.samples.map((s, i) => `
<div class="flex items-center justify-between bg-[var(--bg)] p-3 rounded group">
<div>
<p class="font-medium text-sm">${s.id}</p>
<p class="text-xs text-[var(--fg-muted)]">${s.startYear}-${s.endYear} (${s.data.length} years)</p>
</div>
<div class="flex items-center gap-2">
<span class="text-xs text-[var(--fg-muted)]">μ=${(mean(s.data)).toFixed(2)}</span>
<button onclick="removeSample(${i})" class="opacity-0 group-hover:opacity-100 text-[var(--negative)] transition-opacity" aria-label="Remove sample">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 6L6 18M6 6l12 12"/>
</svg>
</button>
</div>
</div>
`).join('');
updateCrossDatingSelects();
drawSamplePreview();
}
function drawSamplePreview() {
const canvas = document.getElementById('samplePreviewCanvas');
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
ctx.fillStyle = '#1a1714';
ctx.fillRect(0, 0, W, H);
if (state.samples.length === 0) {
ctx.fillStyle = '#9a938c';
ctx.font = '12px IBM Plex Mono';
ctx.textAlign = 'center';
ctx.fillText('No data to display', W/2, H/2);
return;
}
// Draw each series
const allYears = new Set();
state.samples.forEach(s => {
for (let y = s.startYear; y <= s.endYear; y++) allYears.add(y);
});
const years = Array.from(allYears).sort((a, b) => a - b);
const minYear = years[0];
const maxYear = years[years.length - 1];
const yearRange = Math.max(1, maxYear - minYear);
const padding = 40;
const plotW = W - padding * 2;
const plotH = H - padding * 2;
// Axes
ctx.strokeStyle = '#3d3835';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(padding, padding);
ctx.lineTo(padding, H - padding);
ctx.lineTo(W - padding, H - padding);
ctx.stroke();
// Y-axis label
ctx.save();
ctx.translate(15, H/2);
ctx.rotate(-Math.PI/2);
ctx.fillStyle = '#9a938c';
ctx.font = '10px IBM Plex Mono';
ctx.textAlign = 'center';
ctx.fillText('Ring Width (mm)', 0, 0);
ctx.restore();
// X-axis label
ctx.textAlign = 'center';
ctx.fillText('Year', W/2, H - 5);
// Year ticks
ctx.font = '9px IBM Plex Mono';
ctx.fillStyle = '#9a938c';
for (let y = minYear; y <= maxYear; y += Math.ceil(yearRange / 10)) {
const x = padding + ((y - minYear) / yearRange) * plotW;
ctx.fillText(y.toString(), x, H - padding + 15);
}
// Draw series
const colors = ['#c4956a', '#6b9b7a', '#7a9bb8', '#b87a6b', '#9b7ab8'];
state.samples.forEach((sample, idx) => {
const color = colors[idx % colors.length];
const maxVal = Math.max(...sample.data);
const minVal = Math.min(...sample.data);
const range = Math.max(0.01, maxVal - minVal);
ctx.strokeStyle = color;
ctx.lineWidth = 1.5;
ctx.beginPath();
sample.data.forEach((val, i) => {
const year = sample.startYear + i;
const x = padding + ((year - minYear) / yearRange) * plotW;
const y = (H - padding) - ((val - minVal) / range) * plotH * 0.8 - plotH * 0.1;
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
// Series label
ctx.fillStyle = color;
ctx.font = '9px IBM Plex Mono';
ctx.textAlign = 'left';
ctx.fillText(sample.id, W - padding + 5, padding + idx * 12);
});
}
// ============================================
// DATA GENERATION
// ============================================
function generateSampleData() {
const years = Math.floor(Math.random() * 50) + 80; // 80-130 years
const baseTrend = 1.5 + Math.random() * 0.5;
const data = [];
for (let i = 0; i < years; i++) {
// Age trend (negative exponential)
const ageEffect = baseTrend * Math.exp(-i * 0.015);
// Climate signal (sinusoidal + noise)
const climateSignal = 0.3 * Math.sin(i * 0.3) + 0.2 * Math.sin(i * 0.1);
// Random variation
const noise = (Math.random() - 0.5) * 0.4;
const value = Math.max(0.1, ageEffect + climateSignal + noise);
data.push(parseFloat(value.toFixed(3)));
}
document.getElementById('ringData').value = data.join(', ');
updateStatus('Generated sample data');
}
function loadDemoDataset() {
state.samples = [];
// Generate 5 correlated samples
const nYears = 120;
const startYear = 1900;
// Common climate signal
const climateSignal = [];
for (let i = 0; i < nYears; i++) {
const signal = 0.3 * Math.sin(i * 0.25 + 0.5) +
0.2 * Math.sin(i * 0.08) +
0.15 * Math.cos(i * 0.15);
climateSignal.push(signal);
}
const species = ['QURU', 'QUAL', 'QUPR', 'QUVE', 'QUCO'];
for (let s = 0; s < 5; s++) {
const data = [];
const baseGrowth = 1.2 + Math.random() * 0.6;
for (let i = 0; i < nYears; i++) {
const ageEffect = baseGrowth * Math.exp(-i * 0.012);
const signal = climateSignal[i] * (0.6 + Math.random() * 0.4);
const noise = (Math.random() - 0.5) * 0.3;
const value = Math.max(0.1, ageEffect + signal + noise);
data.push(parseFloat(value.toFixed(3)));
}
state.samples.push({
id: `${species[s]}-${startYear + s}`,
startYear,
data,
endYear: startYear + nYears - 1
});
}
updateSampleList();
updateStatus('Loaded demo dataset (5 oak samples, 120 years)');
}
// ============================================
// CROSS-DATING
// ============================================
function updateCrossDatingSelects() {
const refSelect = document.getElementById('referenceSeries');
const targetSelect = document.getElementById('targetSeries');
const options = state.samples.map((s, i) =>
`<option value="${i}">${s.id} (${s.startYear}-${s.endYear})</option>`
).join('');
refSelect.innerHTML = '<option value="">Select reference...</option>' + options;
targetSelect.innerHTML = '<option value="">Select target...</option>' + options;
if (state.samples.length >= 2) {
refSelect.value = '0';
targetSelect.value = '1';
}
}
function runCrossDating() {
const refIdx = parseInt(document.getElementById('referenceSeries').value);
const targetIdx = parseInt(document.getElementById('targetSeries').value);
const windowSize = parseInt(document.getElementById('windowSize').value);
const lagMin = parseInt(document.getElementById('lagMin').value);
const lagMax = parseInt(document.getElementById('lagMax').value);
if (isNaN(refIdx) || isNaN(targetIdx) || refIdx === targetIdx) {
updateStatus('Select different reference and target series');
return;
}
const ref = state.samples[refIdx];
const target = state.samples[targetIdx];
// Calculate correlations at different lags
const correlations = [];
for (let lag = lagMin; lag <= lagMax; lag++) {
const result = calculateLaggedCorrelation(ref.data, target.data, lag, windowSize);
correlations.push({ lag, r: result.r, n: result.n });
}
// Find best correlation
const best = correlations.reduce((a, b) => Math.abs(a.r) > Math.abs(b.r) ? a : b);
const tValue = best.r * Math.sqrt((best.n - 2) / (1 - best.r * best.r));
// Update UI
document.getElementById('bestCorrelation').textContent = best.r.toFixed(4);
document.getElementById('optimalLag').textContent = best.lag === 0 ? 'Aligned' : `${best.lag > 0 ? '+' : ''}${best.lag} years`;
document.getElementById('tValue').textContent = tValue.toFixed(2);
const pValue = 2 * (1 - tDistribution(Math.abs(tValue), best.n - 2));
const sigLevel = pValue < 0.001 ? 'p < 0.001 ***' :
pValue < 0.01 ? 'p < 0.01 **' :
pValue < 0.05 ? 'p < 0.05 *' : 'Not significant';
document.getElementById('significance').textContent = sigLevel;
drawCrossDatingPlot(correlations, best);
drawSkeletonPlot(ref, target, best.lag);
updateStatus('Cross-dating complete');
}
function calculateLaggedCorrelation(ref, target, lag, windowSize) {
let refStart = 0;
let targetStart = lag;
if (lag < 0) {
refStart = -lag;
targetStart = 0;
}
const refSlice = ref.slice(refStart, refStart + windowSize);
const targetSlice = target.slice(targetStart, targetStart + windowSize);
const n = Math.min(refSlice.length, targetSlice.length);
if (n < 10) return { r: 0, n: 0 };
return { r: pearson(refSlice.slice(0, n), targetSlice.slice(0, n)), n };
}
function drawCrossDatingPlot(correlations, best) {
const canvas = document.getElementById('crossDatingCanvas');
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
ctx.fillStyle = '#1a1714';
ctx.fillRect(0, 0, W, H);
const padding = { left: 50, right: 20, top: 20, bottom: 40 };
const plotW = W - padding.left - padding.right;
const plotH = H - padding.top - padding.bottom;
const lags = correlations.map(c => c.lag);
const rVals = correlations.map(c => c.r);
const minLag = Math.min(...lags);
const maxLag = Math.max(...lags);
const maxAbsR = Math.max(0.1, ...rVals.map(Math.abs));
// Axes
ctx.strokeStyle = '#3d3835';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(padding.left, padding.top);
ctx.lineTo(padding.left, H - padding.bottom);
ctx.lineTo(W - padding.right, H - padding.bottom);
ctx.stroke();
// Zero line
const zeroY = padding.top + plotH / 2;
ctx.strokeStyle = '#3d3835';
ctx.setLineDash([4, 4]);
ctx.beginPath();
ctx.moveTo(padding.left, zeroY);
ctx.lineTo(W - padding.right, zeroY);
ctx.stroke();
ctx.setLineDash([]);
// Significance threshold (p=0.05)
const threshold = 0.27; // Approximate for n~50
const threshY = padding.top + plotH * (0.5 - threshold / maxAbsR / 2);
ctx.strokeStyle = 'rgba(107, 155, 122, 0.5)';
ctx.beginPath();
ctx.moveTo(padding.left, threshY);
ctx.lineTo(W - padding.right, threshY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(padding.left, H - padding.bottom - (threshY - padding.top));
ctx.lineTo(W - padding.right, H - padding.bottom - (threshY - padding.top));
ctx.stroke();
// Bars
correlations.forEach(c => {
const x = padding.left + ((c.lag - minLag) / (maxLag - minLag)) * plotW;
const barH = (c.r / maxAbsR) * (plotH / 2);
ctx.fillStyle = c === best ? '#c4956a' :
Math.abs(c.r) > threshold ? 'rgba(107, 155, 122, 0.6)' : '#4a4542';
if (c.r >= 0) {
ctx.fillRect(x - 3, zeroY - barH, 6, barH);
} else {
ctx.fillRect(x - 3, zeroY, 6, -barH);
}
});
// Labels
ctx.fillStyle = '#9a938c';
ctx.font = '9px IBM Plex Mono';
ctx.textAlign = 'center';
for (let l = minLag; l <= maxLag; l += 10) {
const x = padding.left + ((l - minLag) / (maxLag - minLag)) * plotW;
ctx.fillText(l.toString(), x, H - padding.bottom + 15);
}
ctx.textAlign = 'right';
ctx.fillText(maxAbsR.toFixed(2), padding.left - 5, padding.top + 5);
ctx.fillText('0', padding.left - 5, zeroY + 3);
ctx.fillText((-maxAbsR).toFixed(2), padding.left - 5, H - padding.bottom);
ctx.textAlign = 'center';
ctx.fillText('Lag (years)', W / 2, H - 5);
}
function drawSkeletonPlot(ref, target, optimalLag) {
const canvas = document.getElementById('skeletonPlotCanvas');
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
ctx.fillStyle = '#1a1714';
ctx.fillRect(0, 0, W, H);
const nYears = 50;
const startIdx = Math.floor((ref.data.length - nYears) / 2);
// Find narrow rings (below mean)
const refMean = mean(ref.data.slice(startIdx, startIdx + nYears));
const refNarrow = ref.data.slice(startIdx, startIdx + nYears).map((v, i) => ({
idx: i,
isNarrow: v < refMean * 0.85,
value: v
}));
const targetShift = startIdx + optimalLag;
const targetMean = mean(target.data.slice(targetShift, targetShift + nYears));
const targetNarrow = target.data.slice(targetShift, targetShift + nYears).map((v, i) => ({
idx: i,
isNarrow: v < targetMean * 0.85,
value: v
}));
const padding = { left: 60, right: 60, top: 30, bottom: 30 };
const plotW = W - padding.left - padding.right;
const barW = plotW / nYears;
// Reference skeleton
ctx.fillStyle = '#9a938c';
ctx.font = '10px IBM Plex Mono';
ctx.textAlign = 'right';
ctx.fillText(ref.id, padding.left - 10, padding.top + 5);
ctx.strokeStyle = '#3d3835';
ctx.beginPath();
ctx.moveTo(padding.left, padding.top + 50);
ctx.lineTo(W - padding.right, padding.top + 50);
ctx.stroke();
refNarrow.forEach((r, i) => {
const x = padding.left + i * barW;
if (r.isNarrow) {
const h = Math.max(15, (refMean - r.value) / refMean * 40);
ctx.fillStyle = '#c4956a';
ctx.fillRect(x + 1, padding.top + 50 - h, barW - 2, h);
}
// Year markers every 10 years
if (i % 10 === 0) {
ctx.fillStyle = '#9a938c';
ctx.font = '8px IBM Plex Mono';
ctx.textAlign = 'center';
ctx.fillText((ref.startYear + startIdx + i).toString(), x + barW/2, H - padding.bottom + 10);
}
});
// Target skeleton (offset below)
ctx.fillStyle = '#9a938c';
ctx.font = '10px IBM Plex Mono';
ctx.textAlign = 'right';
ctx.fillText(target.id, padding.left - 10, padding.top + 85);
targetNarrow.forEach((r, i) => {
const x = padding.left + i * barW;
if (r.isNarrow) {
const h = Math.max(15, (targetMean - r.value) / targetMean * 40);
ctx.fillStyle = '#6b9b7a';
ctx.fillRect(x + 1, padding.top + 70, barW - 2, h);
}
});
// Legend
ctx.fillStyle = '#c4956a';
ctx.fillRect(W - padding.right + 10, padding.top + 10, 10, 10);
ctx.fillStyle = '#9a938c';
ctx.textAlign = 'left';
ctx.fillText('Reference', W - padding.right + 25, padding.top + 18);
ctx.fillStyle = '#6b9b7a';
ctx.fillRect(W - padding.right + 10, padding.top + 25, 10, 10);
ctx.fillStyle = '#9a938c';
ctx.fillText('Target', W - padding.right + 25, padding.top + 33);
}
// ============================================
// CHRONOLOGY BUILDING
// ============================================
function buildChronology() {
if (state.samples.length < 2) {
updateStatus('Need at least 2 samples to build chronology');
return;
}
const method = document.getElementById('stdMethod').value;
// Standardize each series
const standardized = state.samples.map(s => standardizeSeries(s.data, method));
// Find common period
const allYears = new Set();
state.samples.forEach((s, i) => {
for (let y = s.startYear; y <= s.endYear; y++) allYears.add(y);
});
const years = Array.from(allYears).sort((a, b) => a - b);
// Build chronology
const chronology = years.map(year => {
let sum = 0;
let count = 0;
state.samples.forEach((s, i) => {
const idx = year - s.startYear;
if (idx >= 0 && idx < standardized[i].length) {
sum += standardized[i][idx];
count++;
}
});
return {
year,
value: count > 0 ? sum / count : null,
depth: count
};
});
state.chronology = {
years,
values: chronology.map(c => c.value),
depths: chronology.map(c => c.depth),
standardized,
method
};
// Calculate statistics
const validValues = chronology.filter(c => c.value !== null).map(c => c.value);
const chronoMean = mean(validValues);
const chronoStd = std(validValues);
const intercorr = calculateIntercorrelation(standardized);
document.getElementById('timeSpan').textContent = `${years[0]}-${years[years.length-1]}`;
document.getElementById('chronoMean').textContent = chronoMean.toFixed(3);
document.getElementById('chronoStd').textContent = chronoStd.toFixed(3);
document.getElementById('intercorr').textContent = intercorr.toFixed(3);
drawChronologyPlot();
calculateValidationMetrics();
updateStatus(`Built chronology using ${method} standardization`);
}
function standardizeSeries(data, method) {
const n = data.length;
const result = new Array(n);
switch (method) {
case 'negexp':
// Negative exponential detrending
const a = Math.max(...data) * 1.2;
const b = 0.02;
for (let i = 0; i < n; i++) {
const expected = a * Math.exp(-b * i);
result[i] = expected > 0.01 ? data[i] / expected : 1;
}
break;
case 'spline':
// Simple moving average smoothing
const window = Math.max(5, Math.floor(n / 10));
for (let i = 0; i < n; i++) {
const start = Math.max(0, i - Math.floor(window/2));
const end = Math.min(n, i + Math.ceil(window/2));
const ma = mean(data.slice(start, end));
result[i] = ma > 0.01 ? data[i] / ma : 1;
}
break;
case 'mean':
const avg = mean(data);
for (let i = 0; i < n; i++) {
result[i] = data[i] / avg;
}
break;
case 'ar':
// AR(1) modeling
const lag1Corr = autocorrelation(data, 1);
for (let i = 1; i < n; i++) {
result[i] = data[i] - lag1Corr * data[i-1];
}
result[0] = data[0];
// Normalize
const resMean = mean(result);
const resStd = std(result);
for (let i = 0; i < n; i++) {
result[i] = (result[i] - resMean) / resStd + 1;
}
break;
default:
return [...data];
}
return result;
}
function calculateIntercorrelation(series) {
const n = series.length;
if (n < 2) return 0;
let sumR = 0;
let count = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
const minLen = Math.min(series[i].length, series[j].length);
if (minLen > 10) {
sumR += pearson(
series[i].slice(0, minLen),
series[j].slice(0, minLen)
);
count++;
}
}
}
return count > 0 ? sumR / count : 0;
}
function drawChronologyPlot() {
if (!state.chronology) return;
const canvas = document.getElementById('chronologyCanvas');
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
ctx.fillStyle = '#1a1714';
ctx.fillRect(0, 0, W, H);
const { years, values, depths } = state.chronology;
const validIdx = values.map((v, i) => v !== null ? i : -1).filter(i => i >= 0);
const validYears = validIdx.map(i => years[i]);
const validValues = validIdx.map(i => values[i]);
const padding = { left: 50, right: 40, top: 30, bottom: 40 };
const plotW = W - padding.left - padding.right;
const plotH = H - padding.top - padding.bottom;
const minYear = validYears[0];
const maxYear = validYears[validYears.length - 1];
const yearRange = Math.max(1, maxYear - minYear);
const meanVal = mean(validValues);
const stdVal = std(validValues);
const maxVal = meanVal + stdVal * 2;
const minVal = meanVal - stdVal * 2;
const valRange = Math.max(0.01, maxVal - minVal);
// Grid
ctx.strokeStyle = '#2d2926';
ctx.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const y = padding.top + (i / 4) * plotH;
ctx.beginPath();
ctx.moveTo(padding.left, y);
ctx.lineTo(W - padding.right, y);
ctx.stroke();
}
// Mean line
const meanY = padding.top + ((maxVal - meanVal) / valRange) * plotH;
ctx.strokeStyle = 'rgba(196, 149, 106, 0.5)';
ctx.setLineDash([5, 5]);
ctx.beginPath();
ctx.moveTo(padding.left, meanY);
ctx.lineTo(W - padding.right, meanY);
ctx.stroke();
ctx.setLineDash([]);
// Chronology line
ctx.strokeStyle = '#c4956a';
ctx.lineWidth = 2;
ctx.beginPath();
let firstPoint = true;
validIdx.forEach(i => {
const x = padding.left + ((years[i] - minYear) / yearRange) * plotW;
const y = padding.top + ((maxVal - values[i]) / valRange) * plotH;
if (firstPoint) {
ctx.moveTo(x, y);
firstPoint = false;
} else {
ctx.lineTo(x, y);
}
});
ctx.stroke();
// Fill
ctx.lineTo(padding.left + plotW, H - padding.bottom);
ctx.lineTo(padding.left, H - padding.bottom);
ctx.closePath();
ctx.fillStyle = 'rgba(196, 149, 106, 0.1)';
ctx.fill();
// Axes
ctx.strokeStyle = '#3d3835';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(padding.left, padding.top);
ctx.lineTo(padding.left, H - padding.bottom);
ctx.lineTo(W - padding.right, H - padding.bottom);
ctx.stroke();
// Labels
ctx.fillStyle = '#9a938c';
ctx.font = '9px IBM Plex Mono';
ctx.textAlign = 'center';
for (let y = minYear; y <= maxYear; y += Math.ceil(yearRange / 8)) {
const x = padding.left + ((y - minYear) / yearRange) * plotW;
ctx.fillText(y.toString(), x, H - padding.bottom + 15);
}
ctx.textAlign = 'right';
ctx.fillText(maxVal.toFixed(2), padding.left - 5, padding.top + 5);
ctx.fillText(meanVal.toFixed(2), padding.left - 5, meanY + 3);
ctx.fillText(minVal.toFixed(2), padding.left - 5, H - padding.bottom);
ctx.textAlign = 'center';
ctx.fillText('Year', W / 2, H - 5);
ctx.save();
ctx.translate(15, H / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText('Ring Width Index', 0, 0);
ctx.restore();
// Draw sub-plots
drawSampleDepthPlot();
drawRunningRbarPlot();
drawEPSPlot();
}
function drawSampleDepthPlot() {
const canvas = document.getElementById('sampleDepthCanvas');
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
ctx.fillStyle = '#1a1714';
ctx.fillRect(0, 0, W, H);
if (!state.chronology) return;
const { years, depths } = state.chronology;
const maxDepth = Math.max(...depths);
const padding = 10;
ctx.fillStyle = 'rgba(139, 111, 71, 0.5)';
depths.forEach((d, i) => {
const x = padding + (i / depths.length) * (W - 2 * padding);
const h = (d / maxDepth) * (H - 2 * padding);
ctx.fillRect(x, H - padding - h, 2, h);
});
}
function drawRunningRbarPlot() {
const canvas = document.getElementById('runningRbarCanvas');
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
ctx.fillStyle = '#1a1714';
ctx.fillRect(0, 0, W, H);
if (!state.chronology || !state.chronology.standardized) return;
// Calculate running Rbar
const window = 20;
const rbars = [];
const { standardized } = state.chronology;
const minLen = Math.min(...standardized.map(s => s.length));
for (let i = window; i < minLen - window; i++) {
const slices = standardized.map(s => s.slice(i - window/2, i + window/2));
rbars.push(calculateIntercorrelation(slices));
}
if (rbars.length === 0) return;
const maxR = Math.max(0.5, ...rbars);
const padding = 10;
ctx.strokeStyle = '#6b9b7a';
ctx.lineWidth = 1.5;
ctx.beginPath();
rbars.forEach((r, i) => {
const x = padding + (i / rbars.length) * (W - 2 * padding);
const y = H - padding - (r / maxR) * (H - 2 * padding);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
// Threshold line
ctx.strokeStyle = 'rgba(196, 149, 106, 0.5)';
ctx.setLineDash([3, 3]);
const threshY = H - padding - (0.3 / maxR) * (H - 2 * padding);
ctx.beginPath();
ctx.moveTo(padding, threshY);
ctx.lineTo(W - padding, threshY);
ctx.stroke();
ctx.setLineDash([]);
}
function drawEPSPlot() {
const canvas = document.getElementById('epsCanvas');
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
ctx.fillStyle = '#1a1714';
ctx.fillRect(0, 0, W, H);
if (!state.chronology) return;
const { depths, standardized } = state.chronology;
const rbar = calculateIntercorrelation(standardized);
// Calculate EPS for each year
const epsValues = depths.map(n => {
if (n < 2) return 0;
return (n * rbar) / ((n - 1) * rbar + 1);
});
const padding = 10;
ctx.strokeStyle = '#7a9bb8';
ctx.lineWidth = 1.5;
ctx.beginPath();
epsValues.forEach((eps, i) => {
const x = padding + (i / epsValues.length) * (W - 2 * padding);
const y = H - padding - eps * (H - 2 * padding);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
// 0.85 threshold
ctx.strokeStyle = 'rgba(184, 122, 107, 0.5)';
ctx.setLineDash([3, 3]);
const threshY = H - padding - 0.85 * (H - 2 * padding);
ctx.beginPath();
ctx.moveTo(padding, threshY);
ctx.lineTo(W - padding, threshY);
ctx.stroke();
ctx.setLineDash([]);
}
// ============================================
// SIGNAL EXTRACTION
// ============================================
function loadClimateData() {
if (!state.chronology) {
updateStatus('Build chronology first');
return;
}
// Generate synthetic climate data
const years = state.chronology.years;
const n = years.length;
const temp = [];
const precip = [];
const pdsi = [];
for (let i = 0; i < n; i++) {
// Temperature: warming trend + variability
temp.push(12 + 0.005 * i + (Math.sin(i * 0.3) * 0.8) + (Math.random() - 0.5) * 1.5);
// Precipitation: random + some periodicity
precip.push(800 + Math.sin(i * 0.15) * 150 + (Math.random() - 0.5) * 200);
// PDSI: correlated with temp and precip
pdsi.push(-0.3 * temp[i] + 0.002 * precip[i] + (Math.random() - 0.5) * 2);
}
state.climateData = { years, temp, precip, pdsi };
updateStatus('Loaded synthetic climate data');
}
function extractSignal() {
if (!state.chronology || !state.climateData) {
updateStatus('Build chronology and load climate data first');
return;
}
const climateVar = document.getElementById('climateVar').value;
const method = document.getElementById('analysisMethod').value;
const { years, values } = state.chronology;
const climate = state.climateData[climateVar === 'temp' ? 'temp' :
climateVar === 'precip' ? 'precip' : 'pdsi'];
// Match years
const matchedChrono = [];
const matchedClimate = [];
years.forEach((y, i) => {
const climateIdx = state.climateData.years.indexOf(y);
if (climateIdx >= 0 && values[i] !== null) {
matchedChrono.push(values[i]);
matchedClimate.push(climate[climateIdx]);
}
});
if (matchedChrono.length < 20) {
updateStatus('Insufficient overlapping years');
return;
}
const r = pearson(matchedChrono, matchedClimate);
const r2 = r * r;
document.getElementById('climateCorr').textContent = r.toFixed(4);
document.getElementById('explainedVar').textContent = (r2 * 100).toFixed(1) + '%';
drawClimateResponsePlot(matchedChrono, matchedClimate, r);
drawMonthlyResponse();
updateStatus(`Extracted ${climateVar} signal: r=${r.toFixed(3)}`);
}
function drawClimateResponsePlot(chrono, climate, r) {
const canvas = document.getElementById('climateResponseCanvas');
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
ctx.fillStyle = '#1a1714';
ctx.fillRect(0, 0, W, H);
const padding = { left: 50, right: 30, top: 30, bottom: 40 };
const plotW = W - padding.left - padding.right;
const plotH = H - padding.top - padding.bottom;
const minC = Math.min(...chrono);
const maxC = Math.max(...chrono);
const minCl = Math.min(...climate);
const maxCl = Math.max(...climate);
const rangeC = Math.max(0.01, maxC - minC);
const rangeCl = Math.max(0.01, maxCl - minCl);
// Scatter points
chrono.forEach((c, i) => {
const x = padding.left + ((climate[i] - minCl) / rangeCl) * plotW;
const y = H - padding.bottom - ((c - minC) / rangeC) * plotH;
ctx.fillStyle = 'rgba(196, 149, 106, 0.5)';
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
});
// Regression line
const meanX = mean(climate);
const meanY = mean(chrono);
const stdX = std(climate);
const stdY = std(chrono);
const slope = r * (stdY / stdX);
const intercept = meanY - slope * meanX;
const x1 = minCl;
const x2 = maxCl;
const y1 = slope * x1 + intercept;
const y2 = slope * x2 + intercept;
const px1 = padding.left + ((x1 - minCl) / rangeCl) * plotW;
const py1 = H - padding.bottom - ((y1 - minC) / rangeC) * plotH;
const px2 = padding.left + ((x2 - minCl) / rangeCl) * plotW;
const py2 = H - padding.bottom - ((y2 - minC) / rangeC) * plotH;
ctx.strokeStyle = '#6b9b7a';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(px1, py1);
ctx.lineTo(px2, py2);
ctx.stroke();
// Axes
ctx.strokeStyle = '#3d3835';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(padding.left, padding.top);
ctx.lineTo(padding.left, H - padding.bottom);
ctx.lineTo(W - padding.right, H - padding.bottom);
ctx.stroke();
ctx.fillStyle = '#9a938c';
ctx.font = '9px IBM Plex Mono';
ctx.textAlign = 'center';
ctx.fillText('Climate Variable', W/2, H - 5);
ctx.save();
ctx.translate(12, H/2);
ctx.rotate(-Math.PI/2);
ctx.fillText('Ring Width Index', 0, 0);
ctx.restore();
}
function drawMonthlyResponse() {
const canvas = document.getElementById('monthlyResponseCanvas');
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
ctx.fillStyle = '#1a1714';
ctx.fillRect(0, 0, W, H);
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
// Simulate monthly correlations (strongest in growing season)
const correlations = months.map((_, i) => {
const month = i % 12;
// Peak in May-July for Northern Hemisphere
const seasonal = Math.exp(-Math.pow((month - 5.5) / 2.5, 2)) * 0.5;
return seasonal + (Math.random() - 0.5) * 0.3;
});
const padding = { left: 40, right: 30, top: 30, bottom: 40 };
const plotW = W - padding.left - padding.right;
const plotH = H - padding.top - padding.bottom;
const barW = plotW / months.length;
const maxR = 0.6;
// Zero line
const zeroY = padding.top + plotH / 2;
ctx.strokeStyle = '#3d3835';
ctx.setLineDash([4, 4]);
ctx.beginPath();
ctx.moveTo(padding.left, zeroY);
ctx.lineTo(W - padding.right, zeroY);
ctx.stroke();
ctx.setLineDash([]);
// Significance threshold
const thresh = 0.23;
const threshY = padding.top + plotH * (0.5 - thresh / maxR);
ctx.strokeStyle = 'rgba(107, 155, 122, 0.3)';
ctx.beginPath();
ctx.moveTo(padding.left, threshY);
ctx.lineTo(W - padding.right, threshY);
ctx.moveTo(padding.left, H - padding.bottom - (threshY - padding.top));
ctx.lineTo(W - padding.right, H - padding.bottom - (threshY - padding.top));
ctx.stroke();
// Bars
correlations.forEach((r, i) => {
const x = padding.left + i * barW;
const barH = Math.abs(r) / maxR * (plotH / 2);
ctx.fillStyle = i < 12 ?
(r > thresh ? '#6b9b7a' : r < -thresh ? '#b87a6b' : '#4a4542') :
(r > thresh ? 'rgba(107, 155, 122, 0.5)' : r < -thresh ? 'rgba(184, 122, 107, 0.5)' : '#3a3532');
if (r >= 0) {
ctx.fillRect(x + 2, zeroY - barH, barW - 4, barH);
} else {
ctx.fillRect(x + 2, zeroY, barW - 4, barH);
}
});
// Year separator
ctx.strokeStyle = '#c4956a';
ctx.setLineDash([2, 2]);
ctx.beginPath();
ctx.moveTo(padding.left + 12 * barW, padding.top);
ctx.lineTo(padding.left + 12 * barW, H - padding.bottom);
ctx.stroke();
ctx.setLineDash([]);
// Labels
ctx.fillStyle = '#9a938c';
ctx.font = '8px IBM Plex Mono';
ctx.textAlign = 'center';
months.forEach((m, i) => {
const x = padding.left + i * barW + barW / 2;
ctx.fillText(m, x, H - padding.bottom + 12);
});
ctx.fillText('Previous Year', padding.left + 6 * barW, H - 5);
ctx.fillText('Current Year', padding.left + 15 * barW, H - 5);
// Y-axis
ctx.textAlign = 'right';
ctx.fillText(maxR.toFixed(1), padding.left - 5, padding.top + 5);
ctx.fillText('0', padding.left - 5, zeroY + 3);
ctx.fillText((-maxR).toFixed(1), padding.left - 5, H - padding.bottom);
}
// ============================================
// VALIDATION
// ============================================
function runValidation() {
if (!state.chronology || !state.climateData) {
updateStatus('Build chronology and load climate data first');
return;
}
const method = document.getElementById('validationMethod').value;
const calibStart = parseInt(document.getElementById('calibStart').value);
const calibEnd = parseInt(document.getElementById('calibEnd').value);
const { years, values } = state.chronology;
const climate = state.climateData.temp;
// Split data
const calibChrono = [];
const calibClimate = [];
const verifChrono = [];
const verifClimate = [];
years.forEach((y, i) => {
const climateIdx = state.climateData.years.indexOf(y);
if (climateIdx >= 0 && values[i] !== null) {
if (y >= calibStart && y <= calibEnd) {
calibChrono.push(values[i]);
calibClimate.push(climate[climateIdx]);
} else {
verifChrono.push(values[i]);
verifClimate.push(climate[climateIdx]);
}
}
});
if (calibChrono.length < 15 || verifChrono.length < 10) {
updateStatus('Insufficient data for split-sample validation');
return;
}
// Calibration statistics
const rCalib = pearson(calibChrono, calibClimate);
const r2Calib = rCalib * rCalib;
// Verification statistics
const rVerif = pearson(verifChrono, verifClimate);
const r2Verif = rVerif * rVerif;
// RE (Reduction of Error)
const meanCalib = mean(calibChrono);
const verifMean = mean(verifClimate);
let sumSqTotal = 0;
let sumSqError = 0;
// Regression on calibration
const meanX = mean(calibClimate);
const meanY = mean(calibChrono);
const stdX = std(calibClimate);
const stdY = std(calibChrono);
const slope = rCalib * (stdY / stdX);
const intercept = meanY - slope * meanX;
verifChrono.forEach((v, i) => {
const predicted = slope * verifClimate[i] + intercept;
sumSqError += Math.pow(v - predicted, 2);
sumSqTotal += Math.pow(v - meanCalib, 2);
});
const re = 1 - sumSqError / sumSqTotal;
// CE (using verification mean)
sumSqTotal = 0;
verifChrono.forEach((v, i) => {
sumSqTotal += Math.pow(v - verifMean, 2);
});
const ce = 1 - sumSqError / sumSqTotal;
// Update UI
document.getElementById('r2Calib').textContent = r2Calib.toFixed(3);
document.getElementById('r2Verif').textContent = r2Verif.toFixed(3);
document.getElementById('reStat').textContent = re.toFixed(3);
document.getElementById('ceStat').textContent = ce.toFixed(3);
// Quality assessment
const quality = assessQuality(r2Calib, r2Verif, re, ce);
document.getElementById('qualityAssessment').innerHTML = `
<span class="text-2xl">${quality.emoji}</span>
<div>
<p class="text-sm font-semibold" style="color: ${quality.color}">${quality.label}</p>
<p class="text-xs text-[var(--fg-muted)]">${quality.description}</p>
</div>
`;
drawValidationPlot(calibChrono, calibClimate, verifChrono, verifClimate, slope, intercept);
updateStatus('Validation complete');
}
function assessQuality(r2Cal, r2Ver, re, ce) {
if (re > 0 && ce > 0 && r2Ver > 0.3) {
return {
emoji: '●',
color: 'var(--positive)',
label: 'Excellent',
description: 'Strong predictive skill, suitable for reconstruction'
};
} else if (re > 0 && ce > -0.5) {
return {
emoji: '◐',
color: 'var(--accent)',
label: 'Acceptable',
description: 'Moderate skill, use with caution'
};
} else {
return {
emoji: '○',
color: 'var(--negative)',
label: 'Poor',
description: 'Weak signal, not suitable for reconstruction'
};
}
}
function drawValidationPlot(calibC, calibCl, verifC, verifCl, slope, intercept) {
const canvas = document.getElementById('validationCanvas');
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
ctx.fillStyle = '#1a1714';
ctx.fillRect(0, 0, W, H);
const padding = { left: 50, right: 30, top: 30, bottom: 40 };
const plotW = W - padding.left - padding.right;
const plotH = H - padding.top - padding.bottom;
const allClimate = [...calibCl, ...verifCl];
const allChrono = [...calibC, ...verifC];
const minCl = Math.min(...allClimate);
const maxCl = Math.max(...allClimate);
const minC = Math.min(...allChrono);
const maxC = Math.max(...allChrono);
const rangeCl = Math.max(0.01, maxCl - minCl);
const rangeC = Math.max(0.01, maxC - minC);
// Calibration points
calibC.forEach((c, i) => {
const x = padding.left + ((calibCl[i] - minCl) / rangeCl) * plotW;
const y = H - padding.bottom - ((c - minC) / rangeC) * plotH;
ctx.fillStyle = 'rgba(196, 149, 106, 0.6)';
ctx.beginPath();
ctx.arc(x, y, 4, 0, Math.PI * 2);
ctx.fill();
});
// Verification points
verifC.forEach((c, i) => {
const x = padding.left + ((verifCl[i] - minCl) / rangeCl) * plotW;
const y = H - padding.bottom - ((c - minC) / rangeC) * plotH;
ctx.fillStyle = 'rgba(107, 155, 122, 0.7)';
ctx.beginPath();
ctx.arc(x, y, 4, 0, Math.PI * 2);
ctx.fill();
});
// Regression line
const y1 = slope * minCl + intercept;
const y2 = slope * maxCl + intercept;
const py1 = H - padding.bottom - ((y1 - minC) / rangeC) * plotH;
const py2 = H - padding.bottom - ((y2 - minC) / rangeC) * plotH;
ctx.strokeStyle = '#c4956a';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(padding.left, py1);
ctx.lineTo(W - padding.right, py2);
ctx.stroke();
// Axes
ctx.strokeStyle = '#3d3835';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(padding.left, padding.top);
ctx.lineTo(padding.left, H - padding.bottom);
ctx.lineTo(W - padding.right, H - padding.bottom);
ctx.stroke();
// Legend
ctx.fillStyle = 'rgba(196, 149, 106, 0.6)';
ctx.beginPath();
ctx.arc(W - 100, padding.top + 10, 4, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#9a938c';
ctx.font = '9px IBM Plex Mono';
ctx.textAlign = 'left';
ctx.fillText('Calibration', W - 90, padding.top + 13);
ctx.fillStyle = 'rgba(107, 155, 122, 0.7)';
ctx.beginPath();
ctx.arc(W - 100, padding.top + 25, 4, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#9a938c';
ctx.fillText('Verification', W - 90, padding.top + 28);
}
function calculateValidationMetrics() {
if (!state.chronology) return;
const { values, depths, standardized } = state.chronology;
const validValues = values.filter(v => v !== null);
// EPS
const rbar = calculateIntercorrelation(standardized);
const meanDepth = mean(depths.filter(d => d > 0));
const eps = (meanDepth * rbar) / ((meanDepth - 1) * rbar + 1);
// SSS (Subsample Signal Strength)
const targetR = 0.85;
const sss = (targetR * (1 - rbar)) / (rbar * (1 - targetR));
// AC1
const ac1 = autocorrelation(validValues, 1);
// Mean Sensitivity
const ms = meanSensitivity(validValues);
// Update table
updateMetricRow('eps', eps, 0.85, v => v >= 0.85);
updateMetricRow('rbar', rbar, 0.30, v => v >= 0.30);
updateMetricRow('sss', Math.min(meanDepth / sss, 1), 0.75, v => v >= 0.75);
updateMetricRow('ac1', ac1, 0.70, v => v < 0.70);
updateMetricRow('ms', ms, [0.15, 0.40], v => v >= 0.15 && v <= 0.40);
}
function updateMetricRow(metric, value, threshold, checkFn) {
const valueEl = document.getElementById(`${metric}Value`);
const statusEl = document.getElementById(`${metric}Status`);
if (isNaN(value)) {
valueEl.textContent = '—';
statusEl.textContent = '—';
return;
}
valueEl.textContent = value.toFixed(3);
const passed = checkFn(value);
statusEl.innerHTML = passed ?
'<span class="text-[var(--positive)]">● Pass</span>' :
'<span class="text-[var(--negative)]">○ Fail</span>';
}
// ============================================
// STATISTICAL UTILITIES
// ============================================
function mean(arr) {
if (!arr || arr.length === 0) return 0;
return arr.reduce((a, b) => a + b, 0) / arr.length;
}
function std(arr) {
if (!arr || arr.length < 2) return 0;
const m = mean(arr);
return Math.sqrt(arr.reduce((sum, v) => sum + Math.pow(v - m, 2), 0) / (arr.length - 1));
}
function pearson(x, y) {
const n = Math.min(x.length, y.length);
if (n < 3) return 0;
const meanX = mean(x.slice(0, n));
const meanY = mean(y.slice(0, n));
let sumXY = 0, sumX2 = 0, sumY2 = 0;
for (let i = 0; i < n; i++) {
const dx = x[i] - meanX;
const dy = y[i] - meanY;
sumXY += dx * dy;
sumX2 += dx * dx;
sumY2 += dy * dy;
}
const denom = Math.sqrt(sumX2 * sumY2);
return denom > 0 ? sumXY / denom : 0;
}
function autocorrelation(arr, lag) {
if (arr.length < lag + 2) return 0;
const n = arr.length - lag;
const mean1 = mean(arr.slice(0, n));
const mean2 = mean(arr.slice(lag));
let sum = 0, sum1 = 0, sum2 = 0;
for (let i = 0; i < n; i++) {
const d1 = arr[i] - mean1;
const d2 = arr[i + lag] - mean2;
sum += d1 * d2;
sum1 += d1 * d1;
sum2 += d2 * d2;
}
const denom = Math.sqrt(sum1 * sum2);
return denom > 0 ? sum / denom : 0;
}
function meanSensitivity(arr) {
if (arr.length < 2) return 0;
let sum = 0;
for (let i = 1; i < arr.length; i++) {
sum += Math.abs(2 * (arr[i] - arr[i-1]) / (arr[i] + arr[i-1]));
}
return sum / (arr.length - 1);
}
function tDistribution(t, df) {
// Approximation of t-distribution CDF
const x = df / (df + t * t);
return incompleteBeta(df / 2, 0.5, x) / 2;
}
function incompleteBeta(a, b, x) {
// Simple approximation
if (x === 0) return 0;
if (x === 1) return 1;
const maxIter = 100;
const eps = 1e-10;
let sum = 1;
let term = 1;
for (let i = 0; i < maxIter; i++) {
term *= x * (a + b + i - 1) / (a + i);
sum += term;
if (Math.abs(term) < eps) break;
}
return Math.pow(x, a) * sum;
}
// ============================================
// UI HELPERS
// ============================================
function updateStatus(message) {
document.getElementById('statusText').textContent = message;
}
function toggleView(view) {
document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));
document.querySelector(`[data-view="${view}"]`).classList.add('active');
}
function showHelp() {
document.getElementById('helpModal').classList.remove('hidden');
}
function closeHelp() {
document.getElementById('helpModal').classList.add('hidden');
}
// Close modal on escape
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') closeHelp();
});
// Standardization method change
document.getElementById('stdMethod').addEventListener('change', (e) => {
const splineOptions = document.getElementById('splineOptions');
splineOptions.classList.toggle('hidden', e.target.value !== 'spline');
});
// ============================================
// INITIALIZATION
// ============================================
function init() {
updateSampleList();
updateStatus('Ready - load or generate sample data');
}
init();
</script>
</body>
</html>