Files
radiacode/web/static/js/spectrum.js
Jacquin Antoine 0847a3fc80 Fix: CsI(Tl) non-linear response correction + detector calibration overhaul
Root cause of Am-241 misidentification: the Radiacode 103's CsI(Tl) crystal
shifts low-energy peaks upward (59.5 keV → 71.6 keV for Am-241) due to
non-proportional scintillation response. The model was trained on theoretical
peak positions and couldn't match the shifted real peaks.

Changes:
- Add inverse CsI(Tl) non-linear correction to inference pipeline
  (radiacode_monitor.py, web/config.py, test_detection.py)
  E_apparent = E_true * (1 + 0.37 * exp(-E_true/100))
  Corrects channel mapping so peaks appear at theoretical energies
- Fix energy calibration: DetectorConfig now uses E = 0.33 + 2.97*ch
  with 1023 channels, matching the real detector (was energy_min=20,
  skip_first_channel=True, different channel width)
- Add K-escape peaks for CsI(Tl) iodine X-ray escape (E - 28.5 keV)
- Add asymmetric peak shapes for low-energy tails (< 200 keV)
- Add log1p normalization in dataset and inference (replaces max-norm)
- Add background-subtracted training mode (subtract_background flag)
- Add low-signal augmentation (0.01-5 Bq activities, 30-300s durations)
- Update docker-compose.yml: batch_size=32, duration=30-300s,
  CSI_NONLINEAR_ALPHA/BETA env vars for detect and web
- Web dashboard: apply CsI correction to displayed spectra
- Various UI fixes (Chart.js width, zoom/pan, isotope lines)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 17:35:22 +02:00

207 lines
8.0 KiB
JavaScript

let spectrumChart = null;
let currentSpectrumData = null;
async function refreshSpectrum() {
const showDiff = document.getElementById('show-difference').checked;
const endpoint = showDiff ? '/api/spectrum/difference' : '/api/spectrum/current';
try {
const resp = await fetch(`${API_BASE}${endpoint}`);
if (!resp.ok) return;
const data = await resp.json();
currentSpectrumData = data;
updateSpectrumChart(data);
updateIsotopesTable(data.isotopes_detected || []);
} catch {}
}
function updateSpectrumChart(data) {
const logScale = document.getElementById('log-scale').checked;
const showLines = document.getElementById('show-isotope-lines').checked;
const detectedOnly = document.getElementById('lines-detected-only').checked;
const showBgOverlay = document.getElementById('show-bg-overlay').checked;
const ctx = document.getElementById('spectrum-chart').getContext('2d');
const toData = (counts, energies) => counts.map((v, i) => ({ x: energies[i], y: v }));
const energy = data.energy_kev;
const datasets = [{
label: data.background_subtracted ? 'Spectre (background soustrait)' : 'Spectre cumulé',
data: toData(data.counts, energy),
borderColor: '#4fc3f7',
backgroundColor: 'rgba(79, 195, 247, 0.1)',
borderWidth: 1,
pointRadius: 0,
fill: logScale ? 'origin' : true,
tension: 0.1,
}];
// Overlay background if requested and available, scaled to match spectrum max
if (showBgOverlay && bgOverlayData) {
const specMax = Math.max(...data.counts);
const bgMax = Math.max(...bgOverlayData.counts);
const bgScale = bgMax > 0 ? specMax / bgMax : 1;
const bgEnergy = bgOverlayData.energy_kev || energy;
datasets.push({
label: 'Background',
data: bgOverlayData.counts.map((v, i) => ({ x: bgEnergy[i] ?? energy[i], y: v * bgScale })),
borderColor: 'rgba(255, 152, 0, 0.6)',
backgroundColor: 'rgba(255, 152, 0, 0.05)',
borderWidth: 1,
pointRadius: 0,
fill: true,
tension: 0.1,
});
}
const chartData = {
datasets: datasets,
};
// Annotations
let annotations = {};
if (showLines) {
annotations = buildIsotopeAnnotations(detectedOnly, (data.isotopes_detected || []).map(i => i.isotope));
}
const firstPt = datasets[0].data[0];
const lastPt = datasets[0].data[datasets[0].data.length - 1];
const panRange = spectrumChart?._panRange;
const xMin = panRange ? panRange[0] : (firstPt?.x ?? 0);
const xMax = panRange ? panRange[1] : (lastPt?.x ?? 3000);
const options = {
responsive: true,
maintainAspectRatio: false,
animation: { duration: 300 },
interaction: { mode: 'index', intersect: false },
plugins: {
legend: { labels: { color: '#e0e0e0' } },
tooltip: {
enabled: true,
mode: 'index',
intersect: false,
filter: (item) => item.parsed.y != null,
callbacks: {
title: (items) => `${items[0].parsed.x.toFixed(1)} keV`,
label: (item) => `${item.dataset.label}: ${item.parsed.y.toFixed(1)} counts`
}
},
annotation: {
annotations: annotations
},
zoom: {
zoom: {
wheel: { enabled: true },
pinch: { enabled: true },
drag: { enabled: false },
mode: 'x',
onZoomComplete: () => {
document.getElementById('reset-zoom-spectrum').style.display = 'inline-block';
}
}
}
},
scales: {
x: {
type: 'linear',
min: xMin,
max: xMax,
title: { display: true, text: 'Énergie (keV)', color: '#888' },
ticks: { color: '#888', maxTicksLimit: 20 },
grid: { color: '#333' },
},
y: {
type: logScale ? 'logarithmic' : 'linear',
min: logScale ? 0.5 : undefined,
title: { display: true, text: logScale ? 'Comptages (log)' : 'Comptages', color: '#888' },
ticks: { color: '#888' },
grid: { color: '#333' },
}
}
};
if (spectrumChart) {
spectrumChart.data = chartData;
spectrumChart.options = options;
spectrumChart.update();
} else {
spectrumChart = new Chart(ctx, { type: 'line', data: chartData, ...options });
const panMin = firstPt?.x ?? 0;
const panMax = lastPt?.x ?? 3000;
enablePan(spectrumChart, 'reset-zoom-spectrum', panMin, panMax);
// Fix: Chart.js may read wrong canvas dimensions on first render;
// resize on next frame ensures layout is fully computed.
requestAnimationFrame(() => spectrumChart.resize());
}
}
function updateIsotopesTable(isotopes) {
const container = document.getElementById('isotopes-table');
if (!isotopes || isotopes.length === 0) {
container.innerHTML = '<p style="color:#888;text-align:center;padding:8px;">Aucun isotope détecté (background uniquement)</p>';
return;
}
let html = '<h3 style="margin-bottom:8px;color:#4fc3f7;">Isotopes détectés</h3>';
isotopes.forEach(iso => {
const probColor = iso.probability > 0.9 ? '#4caf50' : iso.probability > 0.7 ? '#ff9800' : '#f44336';
html += `<div class="isotope-row">
<span class="isotope-name">${iso.isotope}</span>
<span class="isotope-prob" style="color:${probColor}">${(iso.probability * 100).toFixed(1)}%</span>
<span class="isotope-activity">${iso.activity_bq.toFixed(1)} Bq</span>
</div>`;
});
container.innerHTML = html;
}
let bgOverlayData = null;
async function loadBgOverlay() {
if (bgOverlayData) return;
try {
const resp = await fetch(`${API_BASE}/api/background/spectrum`);
if (!resp.ok) return;
bgOverlayData = await resp.json();
} catch {}
}
// Event listeners
document.getElementById('show-difference').addEventListener('change', refreshSpectrum);
document.getElementById('log-scale').addEventListener('change', refreshSpectrum);
document.getElementById('show-isotope-lines').addEventListener('change', refreshSpectrum);
document.getElementById('lines-detected-only').addEventListener('change', refreshSpectrum);
document.getElementById('show-bg-overlay').addEventListener('change', async (e) => {
if (e.target.checked) await loadBgOverlay();
refreshSpectrum();
});
// Reset zoom — restore full energy range
document.getElementById('reset-zoom-spectrum')?.addEventListener('click', () => {
if (spectrumChart) {
spectrumChart.resetZoom();
delete spectrumChart._panRange;
const firstPt = spectrumChart.data.datasets[0]?.data?.[0];
const lastPt = spectrumChart.data.datasets[0]?.data?.[spectrumChart.data.datasets[0].data.length - 1];
spectrumChart.options.scales.x.min = firstPt?.x ?? 0;
spectrumChart.options.scales.x.max = lastPt?.x ?? 3000;
spectrumChart.update();
document.getElementById('reset-zoom-spectrum').style.display = 'none';
}
});
// Download CSV
document.getElementById('download-csv').addEventListener('click', () => {
if (!currentSpectrumData) return;
const header = 'energy_keV,counts';
const rows = currentSpectrumData.energy_kev.map((e, i) =>
`${e},${currentSpectrumData.counts[i]}`
);
const csv = [header, ...rows].join('\n');
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `spectrum_${new Date().toISOString().slice(0, 19).replace(/[T:]/g, '-')}.csv`;
a.click();
URL.revokeObjectURL(url);
});