Background réaliste CsI(Tl) + hybridation mesuré/synthétique + dashboard continuum

- Remplace le continuum exponentiel par un modèle réaliste CsI(Tl) dans
  l'entraînement (bosse asymétrique ~110 keV + queue Compton)
- Ajoute l'injection de background mesuré (70% mesuré / 30% synthétique)
  via --measured_background et MEASURED_BACKGROUND_PATH
- Ajoute l'endpoint /api/background/continuum et le toggle "Continuum CsI"
  sur le dashboard background
- Exclut le canal 1023 (overflow bin) de l'affichage web (NUM_CHANNELS=1023)
- Corrige le lissage Gaussien du background (normalisation locale aux bords)
- Met à jour README.md, CLAUDE.md, TUTORIEL.md, TOTO.md, vega_ml/README.md

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Jacquin Antoine
2026-05-19 18:14:00 +02:00
parent 1e0c1a5ea5
commit 75d271c696
17 changed files with 917 additions and 224 deletions

View File

@ -1,24 +1,41 @@
import json
from fastapi import APIRouter, HTTPException
from app.config import BACKGROUND_SNAPSHOT_PATH, BACKGROUND_PATH, energy_axis, NUM_CHANNELS
from app.theoretical_bg import generate_theoretical_bg, generate_continuum_only
import numpy as np
router = APIRouter()
@router.get("")
async def get_background_info():
"""Background metadata: elapsed time, CPS, top peaks."""
def _load_snapshot():
"""Load the live snapshot file, or raise 404."""
if not BACKGROUND_SNAPSHOT_PATH.exists():
raise HTTPException(status_code=404, detail="Background capture not available yet")
try:
with open(BACKGROUND_SNAPSHOT_PATH) as f:
snapshot = json.load(f)
return json.load(f)
except (json.JSONDecodeError, OSError):
raise HTTPException(status_code=500, detail="Background snapshot file corrupt")
# Check if full background is available
def _load_reference():
"""Load the 24h reference background, or return None."""
if not BACKGROUND_PATH.exists():
return None
try:
bg_data = np.load(str(BACKGROUND_PATH), allow_pickle=True).item()
return {
"counts": [round(float(c), 1) for c in bg_data["counts"][:NUM_CHANNELS]],
"live_time_s": round(float(bg_data["duration"]), 1),
}
except Exception:
return None
@router.get("")
async def get_background_info():
"""Background metadata: elapsed time, CPS, top peaks."""
snapshot = _load_snapshot()
full_available = BACKGROUND_PATH.exists()
return {
@ -33,34 +50,46 @@ async def get_background_info():
@router.get("/spectrum")
async def get_background_spectrum():
"""Full background spectrum with energy axis."""
if not BACKGROUND_SNAPSHOT_PATH.exists():
raise HTTPException(status_code=404, detail="Background capture not available yet")
try:
with open(BACKGROUND_SNAPSHOT_PATH) as f:
snapshot = json.load(f)
except (json.JSONDecodeError, OSError):
raise HTTPException(status_code=500, detail="Background snapshot file corrupt")
counts = snapshot.get("spectrum", [0] * NUM_CHANNELS)
# If full background file exists, use it for better data
if BACKGROUND_PATH.exists():
try:
bg_data = np.load(str(BACKGROUND_PATH), allow_pickle=True).item()
counts = [round(float(c), 1) for c in bg_data["counts"]]
live_time = float(bg_data["duration"])
except Exception:
live_time = snapshot.get("live_time_s", 0)
else:
live_time = snapshot.get("live_time_s", 0)
"""Live background spectrum (from snapshot) with energy axis."""
snapshot = _load_snapshot()
live_time = snapshot.get("live_time_s", 0)
return {
"channels": list(range(NUM_CHANNELS)),
"energy_kev": energy_axis(),
"counts": counts,
"counts": snapshot.get("spectrum", [0] * 1024)[:NUM_CHANNELS],
"live_time_s": live_time,
"cps": snapshot.get("cps", 0),
"top_peaks": snapshot.get("top_peaks", []),
}
"reference_available": BACKGROUND_PATH.exists(),
}
@router.get("/reference")
async def get_background_reference():
"""24h reference background spectrum for overlay comparison."""
ref = _load_reference()
if ref is None:
raise HTTPException(status_code=404, detail="No 24h reference background available")
return {
"channels": list(range(NUM_CHANNELS)),
"energy_kev": energy_axis(),
"counts": ref["counts"],
"live_time_s": ref["live_time_s"],
}
@router.get("/theoretical")
async def get_theoretical_bg(cps: float = 6.0, live_time_s: float = 3600.0):
"""Theoretical natural background spectrum (K-40, U-238 chain, Th-232 chain)."""
return generate_theoretical_bg(cps=cps, live_time_s=live_time_s)
@router.get("/continuum")
async def get_continuum(cps: float = 6.0, live_time_s: float = 3600.0):
"""CsI(Tl) continuum shape only (hump + Compton tail, no photopeaks, no noise).
Matches the model used in training (generate_realistic_continuum).
"""
return generate_continuum_only(cps=cps, live_time_s=live_time_s)

View File

@ -29,7 +29,7 @@ async def get_current_spectrum():
"isotopes_detected": state.get("isotopes_detected", []),
"channels": list(range(NUM_CHANNELS)),
"energy_kev": energy_axis(),
"counts": state.get("counts", [0] * NUM_CHANNELS),
"counts": state.get("counts", [0] * 1024)[:NUM_CHANNELS],
}
@ -45,7 +45,7 @@ async def get_difference_spectrum():
except (json.JSONDecodeError, OSError):
raise HTTPException(status_code=503, detail="Monitor state file corrupt")
counts = np.array(state.get("counts", [0] * NUM_CHANNELS), dtype=np.float64)
counts = np.array(state.get("counts", [0] * 1024), dtype=np.float64)[:NUM_CHANNELS]
live_time = state.get("cumulated_live_time_s", 0)
if live_time <= 0:
@ -55,7 +55,7 @@ async def get_difference_spectrum():
if BACKGROUND_PATH.exists():
bg_data = np.load(str(BACKGROUND_PATH), allow_pickle=True).item()
bg_counts = bg_data["counts"].astype(np.float64)
bg_counts = bg_data["counts"].astype(np.float64)[:NUM_CHANNELS]
bg_live_time = float(bg_data["duration"])
bg_rate = bg_counts / bg_live_time
net_rate = np.clip(rate - bg_rate, 0, None)
@ -72,5 +72,5 @@ async def get_difference_spectrum():
"channels": list(range(NUM_CHANNELS)),
"energy_kev": energy_axis(),
"counts": [round(float(c), 1) for c in net_counts],
"raw_counts": state.get("counts", []),
"raw_counts": state.get("counts", [])[:NUM_CHANNELS],
}