diff --git a/.gitignore b/.gitignore index ef2beeb..5e74eaa 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,6 @@ tests/golden/data/ # Docs build artifacts (mkdocs site + mkdocs-jupyter execution cache) site/ .cache/ + +# example run outputs +examples/*/outputs/ diff --git a/README.md b/README.md index 5b08add..5ee6b09 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ JAXTPC/ ├── viewer/ # Interactive 3D/2D HTML viewer + GIF/MP4 export ├── scripts/ # Standalone utilities (e.g. wire-geometry export) ├── slurm/ # SLURM array drivers for batch production -├── closure/ # Differentiable reconstruction / closure studies +├── examples/ # Differentiable reconstruction examples (muon, segments, MCS) └── notebooks/ # Themed example notebooks (getting_started, physics, readout, gradients, reco, calibration, production) ``` diff --git a/closure/archive/README.md b/closure/archive/README.md deleted file mode 100644 index 58d6950..0000000 --- a/closure/archive/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# Closure Archive - -Read-only reference for old/superseded experiments. These files have broken APIs -against the current `tools/` code and are kept only for historical reference. - -## Contents - -### `slides/` -Presentation figure scripts from `closure_analysis_muon/slides_plots/`. 8 of 13 -scripts depend on scan-based muon generator functions that were never promoted -to `tools/`. The remaining 5 are standalone numpy/matplotlib scripts. - -### `closure_analysis_original/` -The original closure prototype (Feb 24-26). Point deposits, Sliced Wasserstein -loss, SGLD/MCMC exploration. Fully superseded by `closure/muon/` and -`closure/segments/`. - -### `gradient_test/` -Early gradient validation (Dec 21). Contains a forked copy of `tools/` from -that era. Proved differentiability works; superseded by the closure tests -that actually converge. - -### `muon_intermediate/` -Superseded muon optimization scripts. The evolution: -- `muon_full_optimization.py` (sobolev_geomean, LR=0.015, 300 steps) -- `run_optimization_save.py` (same + NPZ saving) -- `run_multi_optimization.py` (4 inits, 1000 steps) -- `run_single_test.py` (test log1p variant) -- → `closure/muon/run.py` (terminal: log1p, LR=0.01, 600 steps, CLI) - -Also includes `diff_muon_generator.py` (scan-based generators, canonical -CSDA parts now in `tools/particle_generator.py`) and completed studies -(angle optimization, energy segment study, SW diagnostics). - -### `segments_intermediate/` -Superseded sweep runners. The evolution across 4 phases: -1. 10k segs on mpvmpr_20.h5, s=1.5 (run_sweep, run_best_steps, run_noise) -2. Scale to 20k segs (run_20k, run_s1_20k) -3. Switch to out.h5, 50k segs, s=1.0 (run_out_50k*, run_track_jitter*) -4. → `closure/segments/run_final.py` (terminal: best config, power-law checkpoints) diff --git a/closure/archive/closure_analysis_original/closure_analysis/3DGS_MCMC_PAPER_SUMMARY.md b/closure/archive/closure_analysis_original/closure_analysis/3DGS_MCMC_PAPER_SUMMARY.md deleted file mode 100644 index 57254e5..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/3DGS_MCMC_PAPER_SUMMARY.md +++ /dev/null @@ -1,187 +0,0 @@ -# 3D Gaussian Splatting as Markov Chain Monte Carlo — Paper Summary - -**Paper**: Kheradmand et al., NeurIPS 2024 (Spotlight) -**arXiv**: [2404.09591](https://arxiv.org/abs/2404.09591) -**Code**: [github.com/ubc-vision/3dgs-mcmc](https://github.com/ubc-vision/3dgs-mcmc) - ---- - -## 1. Core Idea - -Standard 3DGS treats Gaussians as deterministic parameters optimized via Adam. The paper reinterprets them as **samples from a probability distribution** over scene representations. Under this view, optimization becomes **MCMC sampling**, and adding noise to gradients converts SGD into **Stochastic Gradient Langevin Dynamics (SGLD)**. - -The key observation: the standard 3DGS gradient update is already SGLD **minus the noise term**: - -``` -Standard: g <- g - lr * grad L(g) -SGLD: g <- g - lr * grad L(g) + noise * epsilon -``` - -Adding appropriately scaled noise turns exploitation-only optimization into exploration+exploitation sampling. - ---- - -## 2. Why MCMC Instead of Pure Optimization - -1. **Local minima trapping**: Pure Adam can only descend — no mechanism to escape poor basins -2. **Heuristic fragility**: Vanilla 3DGS uses ad-hoc clone/split/prune thresholds with no principled justification -3. **Initialization sensitivity**: Without exploration, bad initial placement is unrecoverable -4. **No count control**: Original 3DGS lets Gaussian count grow unboundedly - ---- - -## 3. The SGLD Update Rule - -Full update for Gaussian positions: - -``` -mu <- mu - lr * grad_mu L_total + noise_term -``` - -where the **noise term** (Eq. 8 in paper) is: - -``` -noise_term = lr * sigma(-k * (o_i - t)) * Sigma_i * eta, eta ~ N(0, I) -``` - -### Noise design choices: - -| Component | Formula | Purpose | -|-----------|---------|---------| -| **Isotropic base** | `eta ~ N(0, I)` | Random exploration direction | -| **Covariance scaling** | `Sigma_i * eta` | Anisotropic noise aligned with Gaussian's shape — perturb along natural axes | -| **Sigmoid gating** | `sigma(-k * (o_i - t))` | Suppress noise for high-opacity (useful) Gaussians; allow noise for low-opacity (underutilized) ones | -| **LR coupling** | `lr * ...` | Noise decays naturally with learning rate schedule | - -### Critical hyperparameters: -- `k = 100` (sigmoid steepness — effectively a sharp step function) -- `t = 0.995` (opacity threshold — noise only when opacity < 0.995) -- `lambda_noise = 5e-5` (noise magnitude) -- **Position-only**: Noise applied ONLY to positions `mu`, NOT to opacity, scale, rotation, or color - ---- - -## 4. Loss Function - -``` -L_total = (1 - lambda_SSIM) * L1 + lambda_SSIM * L_D-SSIM + lambda_o * mean(|o_i|) + lambda_Sigma * mean(|sqrt(eig(Sigma_i))|) -``` - -| Term | Weight | Purpose | -|------|--------|---------| -| L1 pixel loss | 0.8 | Reconstruction accuracy | -| D-SSIM loss | 0.2 | Structural similarity | -| **L1 on opacity** | **0.01** | Push unused Gaussians toward zero opacity → creates "dead" pool for relocation | -| **L1 on scale** | **0.01** | Encourage compact Gaussians, prevent degenerate large ones | - -### The opacity regularization is essential - -It serves as a **Laplace (sparsity) prior** in the MCMC framework. Without it, there is no mechanism to create dead Gaussians for relocation. The ablation shows: -- **With regularization, without noise**: 27.41 PSNR (decent) -- **With noise, without regularization**: 17.60 PSNR (catastrophic failure) -- **With both**: 29.72 PSNR (best) - ---- - -## 5. Relocation Strategy (Birth/Death) - -### Philosophy -Rather than creating/destroying Gaussians (variable count), the paper keeps a **fixed budget** and **teleports** dead Gaussians to useful locations. This is grounded in MCMC: samples move through space, they are not created or destroyed. - -### Death criterion -``` -o_i < 0.005 (opacity below 0.5%) -``` - -The L1 regularization naturally pushes unused Gaussians toward zero opacity, creating dead candidates. - -### Target selection -Dead Gaussians are relocated to alive Gaussians via **multinomial sampling proportional to opacity**. High-opacity (important) Gaussians are more likely to receive copies. - -### Probability-preserving split formulas - -When duplicating a Gaussian into N copies, the opacity is updated to preserve rendering: - -``` -(1 - o_new)^N = 1 - o_old -→ o_new = 1 - (1 - o_old)^{1/N} -``` - -The covariance is also updated via a complex formula involving binomial coefficients to match integrated color contribution. - -### Schedule -- **Warmup**: 500 iterations (no relocation) -- **Frequency**: Every 100 iterations after warmup -- **Growth**: Add 5% of current count per step until cap reached -- **Moment reset**: Adam moments are **reset for the source** (donor) Gaussian but **retained for the relocated** (dead→new) Gaussian - ---- - -## 6. Fixed Gaussian Budget - -A `cap_max` parameter sets the maximum number of Gaussians. This is a **feature, not a limitation**: -- Eliminates unbounded growth -- Forces efficient resource allocation via relocation -- Makes memory usage predictable - ---- - -## 7. Ablation Study Results - -| Configuration | PSNR | Key takeaway | -|---|---|---| -| Vanilla 3DGS | 27.89 | Baseline | -| + L1 regularization only | 23.84 | Regularization alone **hurts** — kills useful Gaussians with no way to replace them | -| Full method, no noise | 27.41 | Relocation works somewhat without noise, but Gaussians still get trapped | -| Full method, no regularization | 17.60 | **Catastrophic** — without regularization, no dead Gaussians are created, relocation never triggers | -| Full method, noise on ALL params | 29.11 | Slightly worse than position-only noise | -| **Full method, position-only noise** | **29.72** | **Best** — spatial exploration is the key bottleneck | - -### Key ablation insight -**Noise and regularization are co-dependent**. Noise provides exploration to escape local minima. Regularization creates the dead pool that enables relocation. Relocation redistributes capacity to where it's needed. Remove any one component and the system degrades. - ---- - -## 8. Initialization Robustness - -| Method | SfM Init | Random Init | Drop | -|---|---|---|---| -| Vanilla 3DGS | 27.89 | 22.72 | -5.17 | -| 3DGS-MCMC | 29.72 | 29.64 | **-0.08** | - -The SGLD exploration makes the method nearly initialization-independent. - ---- - -## 9. Theoretical Caveats - -The MCMC connection is a **productive conceptual framework**, not a rigorous proof: - -1. **Not true SGLD**: The sigmoid gating, covariance scaling, and separate `lambda_noise` break standard SGLD convergence conditions -2. **Adam breaks SGLD**: Adam's adaptive LR and momentum destroy theoretical guarantees (standard SGLD assumes vanilla SGD) -3. **No detailed balance**: Relocation moves preserve rendering approximately, not MCMC-rigorously -4. **No temperature annealing**: Effective temperature is implicitly `lambda_noise / lr`, which increases as lr decays — not formally analyzed - -Despite these gaps, the framework **motivates the right algorithmic choices**: noise for exploration, regularization for sparsity, relocation for resource reallocation. - ---- - -## 10. Complete Hyperparameter Table - -| Parameter | Value | Notes | -|-----------|-------|-------| -| Position LR (start) | 1.6e-4 | Exponential decay | -| Position LR (end) | 1.6e-6 | Over 30k iterations | -| lambda_noise | 5e-5 | SGLD noise magnitude | -| Sigmoid k | 100 | Sharp gating | -| Sigmoid threshold t | 0.995 | Noise only for low-opacity | -| lambda_o (opacity reg) | 0.01 | L1 on opacity | -| lambda_Sigma (scale reg) | 0.01 | L1 on covariance eigenvalues | -| Dead threshold | 0.005 | Opacity below this = dead | -| Relocation interval | 100 steps | How often to relocate | -| Warmup | 500 steps | No relocation during warmup | -| Growth rate | 5% per step | Until cap_max reached | -| cap_max | Dataset-dependent | Fixed Gaussian budget | -| Adam beta1 | 0.9 | Standard | -| Adam beta2 | 0.999 | Standard | -| SSIM weight | 0.2 | Standard 3DGS value | diff --git a/closure/archive/closure_analysis_original/closure_analysis/OVERCOMPLETE_OPTIMIZATION_FINDINGS.md b/closure/archive/closure_analysis_original/closure_analysis/OVERCOMPLETE_OPTIMIZATION_FINDINGS.md deleted file mode 100644 index 09919f9..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/OVERCOMPLETE_OPTIMIZATION_FINDINGS.md +++ /dev/null @@ -1,178 +0,0 @@ -# Overcomplete MCMC Closure Optimization — Findings - -## Goal - -Reconstruct N_truth=5 point-charge segments from simulated wire signals using N_seg=10 optimizer segments (overcomplete). The extra 5 segments should be identified as unnecessary and either drain to minimal energy or get relocated. Based on the 3DGS-MCMC paper adapted for TPC simulation. - -Init offset: [+30, -30, +30, +0.05] mm/MeV (~52mm Euclidean distance). Extra segments initialized randomly within detector bounds at median truth energy. - ---- - -## Phase 1: 5-Seg Base Optimizer Tuning (no noise, no L1, no relocation) - -Systematic sweep to find the optimal Adam + schedule configuration before adding MCMC components. - -### Schedule Comparison (LR=0.3, lr_e_mult=0.03) - -| Schedule | Pos (mm) | Loss | Step<3mm | -|----------|----------|------|----------| -| Cosine α=0.01 | 1.58 | 0.000165 | 450 | -| Exp d=0.999 | 1.22 | 0.000090 | 450 | -| Exp d=0.9995 | 1.21 | 0.000236 | 430 | -| Constant | 0.95 | 0.000374 | 380 | - -### LR Sweep (exp d=0.9995, lr_e_mult=0.01) - -| LR | Pos (mm) | Loss | Step<3mm | -|----|----------|------|----------| -| 0.5 | 1.09 | 0.000147 | 340 | -| **0.7** | **0.42** | **0.000058** | **260** | -| 1.0 | 0.64 | 0.000166 | 300 | - -### Decay Rate Sweep (LR=0.5, lr_e_mult=0.01) - -| Decay Rate | Pos (mm) | Loss | -|------------|----------|------| -| 0.999 | 1.28 | 0.000138 | -| 0.9995 | 1.09 | 0.000147 | -| 0.9998 | 0.75 | 0.000062 | - -### lr_e_mult — Critical Phase Transition (LR=0.7, d=0.9995) - -| lr_e_mult | Pos (mm) | Max (mm) | Loss | Notes | -|-----------|----------|----------|------|-------| -| 0.003 | 6.25 | 15.4 | 0.000651 | Energy too slow — stuck | -| 0.008 | 6.00 | 15.0 | 0.000560 | Still stuck | -| 0.01 | 6.38 | 16.4 | 0.000746 | Below threshold | -| **0.015** | **0.80** | **1.68** | **0.000054** | Above threshold | -| **0.02** | **0.52±0.24** | **0.98** | **0.000047** | **Robust (3 runs: 0.21, 0.78, 0.46)** | -| **0.025** | **1.14±0.80** | **1.90** | **0.000106** | Less stable (3 runs: 0.63, 0.72, 2.08) | -| 0.03 | 6.38 | 15.4 | 0.000712 | Above threshold — wraps around? | - -**Key finding**: Sharp phase transition at lr_e_mult ≈ 0.015. Below this, energy learns too slowly to support position convergence. Above ~0.025, variance increases. **lr_e_mult=0.02 is the robust optimum.** - -### Scaling to 8 Segments (8=8 equal, lr_e_mult=0.03/0.05) - -| Config | Pos (mm) | Max (mm) | Loss | -|--------|----------|----------|------| -| 8=8, e=0.03 | 31.1–32.3 | 59–64 | 0.032 | -| 8=8, e=0.05 | 30.8–33.1 | 58–61 | 0.031 | - -**8 segments completely stuck at ~31mm** — barely moved from 52mm init. The 5-seg hyperparams don't transfer. More segments = much harder loss landscape. - -### Optimal 5-Seg Base Config - -``` -Schedule: Exponential decay, LR=0.7, decay_rate=0.9995 -lr_e_mult=0.02, b1=0.95, b2=0.999 -No noise, no L1, no relocation -Result: 0.52mm mean (0.21–0.78 range), 1000 steps -``` - ---- - -## Phase 1b: Noise on 5-Seg Base - -Tested on the optimal base config (LR=0.7, d=0.9995, lr_e_mult=0.02). - -### Quadratic Coupling (noise ∝ lr²) — TOO AGGRESSIVE - -| NOISE_LR | Pos (mm) | Notes | -|----------|----------|-------| -| 0.5 | 2.00 | 4x worse than baseline | -| 1.0 | 2.58 | | -| 2.0 | 4.59 | | -| 5.0 | 122.7 | Catastrophic | - -**Quadratic coupling decays too fast with exp schedule** — noise is too strong early, dies too quickly late. Not suitable. - -### Constant Noise (fixed mm/step/dim) - -| Noise (mm) | Pos (mm) | Max (mm) | Loss | -|------------|----------|----------|------| -| 0.02 | **0.39** | 0.90 | 0.000074 | -| 0.05 | 1.07 | 1.84 | 0.000094 | -| 0.1 | 1.07 | 1.88 | 0.000170 | - -### Linear LR-Coupled (noise = lr × NOISE_LR) - -| NOISE_LR | Init→Final (mm) | Pos (mm) | Max (mm) | Loss | -|----------|-----------------|----------|----------|------| -| 0.05 | 0.035→0.021 | **0.72** | 0.95 | 0.000056 | -| 0.1 | 0.070→0.043 | 1.17 | 1.94 | 0.000116 | -| 0.2 | 0.140→0.085 | 1.18 | 1.66 | 0.000100 | - -**For 5=5 equal, noise doesn't help** — pure Adam already reaches the global minimum. Small noise (constant=0.02mm or linear=0.05) is tolerable but not beneficial. Larger noise monotonically degrades performance. - -**For overcomplete, noise will be essential** to break symmetry and escape local minima. Safe starting values: constant=0.02mm or linear NOISE_LR=0.05. - ---- - -## Phase 2: Overcomplete Runs (10 opt / 5 truth) — Previous Session - -All runs used cosine or exponential schedule with LR=0.3–0.5, lr_e_mult=0.01–0.03. - -| # | LR Schedule | LR | Noise | L1 | DT | Split | WU | Steps | Loss | Pos (mm) | dE (keV) | Extras Dead | Relocs | -|---|-------------|-----|-------|-----|------|-------|-----|-------|------|----------|----------|-------------|--------| -| 1 | Cosine α=0.01 | 0.3 | 5 linear | 5e-5 fixed | 0.01 | 50/50 | 500 | 1500 | 0.001 | 6.6 | 82.3 | 0/5 | 11 | -| 2 | Cosine α=0.01 | 0.3 | 3 linear | 2e-4 fixed | 0.01 | 50/50 | 500 | 1500 | 0.011 | 28 | — | 0/5 | — | -| 3 | Cosine α=0.01 | 0.3 | 5 linear | 1e-3 coupled | 0.01 | 50/50 | 500 | 1500 | 0.004 | 18 | 83.8 | 0/5 | 16 | -| 4 | Cosine α=0.01 | 0.3 | 15 linear | 3e-3 coupled | 0.01 | 50/50 | 500 | 1500 | 0.025 | 44 | 73.1 | 0/5 | — | -| 5 | Cosine α=0.01 | 0.3 | 5 linear | 5e-5 fixed | 0.03 | 50/50 | 500 | 1500 | 0.007 | 14 | 99.1 | 1/5 | 18 | -| 6 | Cosine α=0.01 | 0.3 | 5 linear | 5e-5 fixed | 0.02 | 50/50 | 500 | 1500 | 0.004 | 11.4 | 67.4 | 0/5 | 14 | -| 7 | Cosine α=0.01 | 0.3 | 5 linear | 5e-5 fixed | 0.001 | 50/50 | 500 | 1500 | 0.006 | 18.3 | **1.4** | **5/5** | 0 | -| 8 | Cosine α=0.01 | 0.3 | 3 linear | 5e-5 fixed | 0.001 | 50/50 | 500 | 1500 | 0.006 | 20.8 | 1.0 | 5/5 | 0 | -| 9 | Cosine α=0.01 | 0.3 | 8 linear | 5e-5 fixed | 0.001 | 50/50 | 500 | 1500 | 0.018 | 52 | 91 | 3/5 | 0 | -| 10 | Cosine α=0.01 | 0.3 | 5 linear | 5e-5 fixed | 0.005 | 50/50 | 500 | 2500 | 0.0009 | 6.9 | 49.6 | 0/5 | 47 | -| 11 | Cosine α=0.01 | 0.3 | 5 linear | 5e-5 fixed | 0.005 | 50/50 | 50 | 1000 | 0.005 | 15 | 68.7 | 0/5 | 17 | -| 12 | Cosine α=0.01 | 0.3 | 3 linear | 5e-4 coupled | 0.005 | 50/50 | 50 | 1000 | 0.004 | 16 | 88 | 0/5 | 15 | -| 13 | Cosine α=0.01 | 0.3 | 5 linear | 5e-4 coupled | 0.005 | 50/50 | 50 | 1000 | 0.007 | 19 | — | 0/5 | — | -| 14 | Cosine α=0.01 | 0.3 | 5 linear | 5e-5 fixed | 0.005 | 90/10 | 50 | 1000 | 0.004 | 18 | 102.4 | 0/5 | 29 | -| 15 | Cosine α=0.01 | 0.3 | 5 linear | 1e-3 coupled | 0.005 | 80/20 | 50 | 1000 | 0.015 | 62 | 75 | 0/5 | 27 | -| 16 | Cosine α=0.01 | 0.3 | 5 linear | 5e-5 fixed | 0.005 | 50/50 | 500 | 4000 | **0.0003** | **2.96** | 82.6 | 0/5 | 82 | -| 17 | Constant | 0.05 | 5 const | 5e-5 fixed | 0.005 | 50/50 | 500 | 2000 | 0.005 | 20.8 | 48.5 | 0/5 | 7 | -| 18 | Constant | 0.1 | 5 const | 5e-5 fixed | 0.005 | 50/50 | 500 | 2000 | 0.006 | 11.9 | 48.3 | 0/5 | 13 | -| 19 | Constant | 0.2 | 5 const | 5e-5 fixed | 0.005 | 50/50 | 500 | 2000 | 0.007 | 13.5 | 33.3 | 0/5 | 29 | -| 20 | Constant | 0.2 | 5 const | 2e-4 fixed | 0.005 | 70/30 | 500 | 2000 | 0.010 | 17 | 53.7 | 0/5 | 29 | -| 21 | Exp d=0.998 | 0.3 | 2 linear | 5e-5 fixed | 0.005 | 50/50 | 500 | 2000 | 0.006 | 22 | 33.4 | 0/5 | 5 | -| 22 | Exp d=0.9995 | 0.5 | 2 linear | 5e-5 fixed | 0.005 | 50/50 | 500 | 2000 | 0.001 | 4.5 | 44.9 | 0/5 | 16 | -| 23 | Exp d=0.9995 | 0.5 | 5 lr² | 5e-5 fixed | 0.005 | 50/50 | 500 | 2000 | 0.001 | 3.5 | 55.1 | 0/5 | 28 | - -### Key Findings from Overcomplete Runs - -**Settled parameters** (consistent across all runs): -- **L1**: Fixed 5e-5 MeV/step always best. Coupled or stronger always worse. -- **Death threshold**: 0.005 best balance. Lower = better energy, worse positions. -- **Split ratio**: 50/50 best. 90/10, 80/20, 70/30 all worse. -- **Warmup**: 500 always better than 50. - -**Fundamental limitations**: -- SW loss doesn't incentivize sparsity — extras never fully die -- Two-regime tradeoff: more relocations = better positions, worse energy -- Top-K gradient masking can leave weak segments with zero gradient - ---- - -## Summary: What We Know - -### Locked-In Base Config -``` -Schedule: Exponential decay, LR=0.7, decay_rate=0.9995 -b1=0.95, b2=0.999 -lr_e_mult=0.02 -``` - -### Locked-In MCMC Components (from Phase 2) -``` -L1: Fixed rate (not coupled) -Death threshold: 0.005 -Split ratio: 50/50 -Warmup: 500 -Relocation: Continuous (every step after warmup) -Donor selection: Energy-proportional multinomial -``` - -### To Be Tuned for Overcomplete with New Base Config -- **L1 rate**: Was 5e-5 with old LR=0.3 config. May need adjustment with LR=0.7 / lr_e_mult=0.02 since energy dynamics are different. -- **Noise**: Essential for overcomplete (breaks symmetry, escapes local minima). Constant or linear coupling — NOT quadratic. Start with constant=0.02mm or linear=0.05. -- **Warmup**: Was 500 with slow LR=0.3 cosine. With faster LR=0.7 exp, positions converge by ~260 steps. Could try 200–300. diff --git a/closure/archive/closure_analysis_original/closure_analysis/PAPER_VS_IMPLEMENTATION_ANALYSIS.md b/closure/archive/closure_analysis_original/closure_analysis/PAPER_VS_IMPLEMENTATION_ANALYSIS.md deleted file mode 100644 index 1c7c24e..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/PAPER_VS_IMPLEMENTATION_ANALYSIS.md +++ /dev/null @@ -1,243 +0,0 @@ -# 3DGS-MCMC → JAXTPC Closure: Gap Analysis - -This document compares the 3DGS-MCMC paper's approach with the current `sgld_closure.py` implementation, identifies fundamental mismatches, and proposes corrections. - ---- - -## Analogy Mapping - -| 3DGS Concept | JAXTPC Equivalent | -|---|---| -| 3D Gaussian | Point-charge segment (position + energy) | -| Opacity `o_i` | Segment energy `dE_i` | -| Gaussian covariance `Sigma_i` | No direct analog (segments are points, not extended objects) | -| Rendered image | Wire signals on U/V/Y planes | -| L1 + D-SSIM pixel loss | Sliced Wasserstein distance on (wire, time) pointclouds | -| L1 opacity regularization | L1 energy regularization (attempted) | -| Dead Gaussian (opacity < 0.005) | Dead segment (energy < 0.05 MeV) | - ---- - -## Issue 1: Noise Gating Is Inverted - -### Paper -Noise gate: `sigma(-k * (o_i - t))` with `t = 0.995` -- High opacity (useful, converged) → gate ≈ 0 → **no noise** (protect converged) -- Low opacity (useless, candidate for death) → gate ≈ 1 → **full noise** (explore freely) -- The idea: converged Gaussians should not be perturbed; dying Gaussians should explore aggressively before being relocated - -### Current implementation -Noise gate: `sigmoid(-K_GATE * (energy - GATE_THRESHOLD))` with `GATE_THRESHOLD = 0.2 MeV` -- High energy (useful, alive) → gate ≈ 0 → no noise -- Low energy (dying) → gate ≈ 1 → full noise - -### The problem -This is **directionally correct** (noise for weak segments, protection for strong ones), but the **threshold is wrong relative to the operating regime**. In the paper, t=0.995 means noise is suppressed only for the top 0.5% of opacity. Nearly all Gaussians receive some noise. In the implementation, GATE_THRESHOLD=0.2 MeV means noise only activates when a segment has lost 87% of its initial energy (1.6 MeV). As documented in SGLD_FINDINGS.md, segment energies **never fall below 0.5 MeV** in the 10-segment case, so **noise never activates**. - -### Fix -The gate threshold should be set relative to the operating energy range, not at an absolute low value. If segments operate at 0.5–2.0 MeV, a threshold like 1.5 MeV would gate noise for most segments while protecting only the highest-energy (best-converged) ones. Alternatively, use a **relative threshold** (e.g., top 10% of current energies are protected). - ---- - -## Issue 2: Regularization and Noise Are Decoupled - -### Paper (the critical co-dependency) -The paper's central mechanism is a **three-part cycle**: -1. **L1 opacity regularization** continuously pushes unused Gaussians toward zero → creates dead candidates -2. **SGLD noise** lets those low-opacity Gaussians explore before dying -3. **Relocation** teleports dead Gaussians to high-opacity locations - -All three are co-dependent. The ablation shows removing ANY one causes failure: -- No regularization → no dead Gaussians → relocation never triggers → **catastrophic (17.60 PSNR)** -- No noise → Gaussians trapped in local minima → regularization kills useful ones → **degraded (23.84 PSNR when added to vanilla 3DGS)** -- No relocation → dead Gaussians are wasted → capacity shrinks over time - -### Current implementation -- L1 regularization on energy was tested (`test_l1_drain.py`) and found **completely ineffective** because: - - L1 gradient is negligible vs. simulation gradients (0.001 vs 100) - - Adam normalizes gradients, so absolute magnitude doesn't matter - - SW loss distributes energy uniformly — no sparsity incentive -- Without effective regularization, segments never die -- Without dead segments, relocation never triggers -- Without relocation, capacity is never redistributed - -### Root cause -The L1 regularization failure is **not a hyperparameter problem** — it's a fundamental difference between the two domains: - -In 3DGS: opacity ∈ [0, 1] (sigmoid-bounded). An unused Gaussian can have its opacity pushed to ~0 by the regularizer while having minimal effect on the rendered image (opacity 0 = fully transparent = contributes nothing). - -In JAXTPC: energy dE > 0, and every segment with nonzero energy produces a wire signal that contributes to the total. There is no "transparent" state — a segment at 0.1 MeV still generates a physical signal that the SW loss must account for. The sim gradients from matching this signal overwhelm any L1 pressure. - -### Fix options -1. **Add an explicit opacity-like parameter**: Give each segment an opacity `o_i ∈ [0, 1]` that **multiplicatively scales its energy contribution**: `effective_energy = o_i * dE_i`. The L1 regularizer acts on `o_i`, not `dE_i`. When `o_i → 0`, the segment effectively vanishes regardless of its energy. This directly mirrors the paper's mechanism. - -2. **Use energy fraction as opacity proxy**: Define `o_i = dE_i / sum(dE_j)`. Regularize this fraction. But this couples all segments and may create gradient issues. - -3. **Stuck-segment detection instead of energy thresholds**: Monitor position/energy change rates over a window. If a segment hasn't moved in N steps, declare it dead and relocate. This sidesteps the regularization problem entirely (already suggested in SGLD_FINDINGS.md). - ---- - -## Issue 3: No Covariance Scaling on Noise - -### Paper -Noise is scaled by `Sigma_i * eta` — each Gaussian's covariance matrix. This makes noise **anisotropic**, aligned with the Gaussian's natural shape. A thin elongated Gaussian explores preferentially along its long axis. - -### Current implementation -Noise is isotropic: `NOISE_LR * gate * random_normal` applied equally to x, y, z. - -### Why this matters less for JAXTPC -Segments are point charges, not extended objects — there is no natural covariance/shape to align noise with. However, the **detector geometry** creates anisotropy: x is the drift direction (most sensitive), while y and z are along the wire planes. Noise could be scaled by detector-geometry-aware factors rather than per-segment covariance. - -### Possible fix -Use anisotropic noise with detector-informed scales: e.g., less noise in x (drift direction, where signals are most sensitive) and more in y/z (along wire planes, where the loss landscape may be flatter). - ---- - -## Issue 4: The Loss Function Difference - -### Paper -- L1 + D-SSIM pixel-level loss: **dense, per-pixel gradients** -- Every Gaussian that contributes to any pixel gets a gradient -- The alpha-blending rendering equation provides smooth gradient flow through opacity - -### Current implementation -- Sliced Wasserstein distance on pointclouds extracted via **top-K** selection -- **Top-K creates a hard gradient mask**: only the K brightest (wire, time) points contribute to the loss -- When 10 segments overlap, weaker segments fall below the K threshold and receive **zero gradient** -- This is the "gradient desert" problem documented in SGLD_FINDINGS.md - -### Why this is the fundamental bottleneck -In 3DGS, even a nearly-transparent Gaussian (opacity 0.01) still contributes to the rendered pixel color and receives a gradient proportional to its contribution. The gradient is small but nonzero. This allows the L1 regularizer to gradually push it to zero opacity. - -In JAXTPC with top-K, a weak segment that falls below the K threshold gets **exactly zero gradient** — not small, but zero. There is no gradient signal to push it toward death, and no gradient signal for noise to perturb. This creates the circular failure mode: no gradient → no energy change → thresholds never reached → no relocation → segment stays stuck. - -### Fix options -1. **Soft top-K (differentiable relaxation)**: Replace hard top-K with a differentiable approximation (e.g., softmax weighting with temperature). All points contribute, but brighter ones contribute more. - -2. **Use all points**: Remove top-K entirely and use the full (wire, time, weight) signal. This may be expensive but eliminates the gradient masking problem. - -3. **Stratified sampling**: Instead of global top-K, divide the (wire, time) plane into spatial regions and sample K/R points from each region. This guarantees all spatial regions (and hence all segments) contribute to the loss. - -4. **Dense loss instead of SW**: Use a direct L1/L2 loss on the wire signals (as 2D arrays, wires × time) instead of converting to pointclouds. This is more analogous to the paper's pixel-level loss and provides gradients to every segment that contributes to any wire/time bin. - ---- - -## Issue 5: Energy Splitting During Relocation - -### Paper -When relocating a dead Gaussian to a source Gaussian, the opacity is split via: -``` -o_new = 1 - (1 - o_old)^{1/N} -``` -This ensures N copies with `o_new` render identically to one copy with `o_old`. The covariance is also adjusted. - -### Current implementation -Energy is split 50/50: -```python -params['dE'] = params['dE'].at[dead_idx].set(alive_energy * 0.5) -params['dE'] = params['dE'].at[alive_idx].set(alive_energy * 0.5) -``` - -### The problem -The 50/50 energy split is **physically correct for additive signals** (two segments each at half energy produce the same total wire signal as one at full energy, if at the same position). This is actually more appropriate than the paper's formula because: -- In 3DGS, opacity combines via alpha-blending (multiplicative): `(1-o)^N` -- In JAXTPC, energy combines additively: `E1 + E2 = E_total` - -So the 50/50 split is the right analog. **This is one thing the implementation gets correct.** - -### Minor improvement -Consider splitting **unequally** (e.g., 70/30) to give the relocated segment less energy initially, allowing it to explore without creating a large immediate signal disturbance. The paper's N-th root formula effectively does this for opacity. - ---- - -## Issue 6: Adam Moment Reset Direction Is Inverted - -### Paper -- Adam moments are **reset for the source** (donor) Gaussian: "The optimizer state is reset for the target sample to take large steps and encourage further optimization" -- Adam moments are **retained for the relocated** (dead → new) Gaussian: it inherits the new position but keeps its own optimizer momentum - -### Current implementation (sgld_closure.py) -- Adam moments are **reset for the donor** segment (correct direction) -- Dead segment moments are **kept** (correct direction) - -This actually matches the paper. No change needed. - ---- - -## Issue 7: Temperature and Noise Schedule - -### Paper -- `lambda_noise = 5e-5` is a fixed constant -- Noise naturally decays because it's multiplied by `lr`, which decays exponentially -- Effective temperature `~ lambda_noise / lr` **increases** over training (noise decays slower than lr) -- No explicit temperature annealing - -### Current implementation -- Noise decays via its own exponential: `lr * exp(-step/noise_tau) * NOISE_LR` -- `noise_tau = total_steps / ln(100)` → noise drops by 100x over training -- Learning rate also decays via cosine schedule -- Combined effect: noise decays **much faster** than in the paper - -### Fix -The paper couples noise to the learning rate only. The additional `exp(-step/noise_tau)` decay is overly aggressive and kills exploration too early. Remove the separate noise decay and let the noise inherit the learning rate schedule: -```python -noise = lr_current * NOISE_LR * gate * random_normal -``` -where `lr_current` already decays via the cosine schedule. - ---- - -## Issue 8: Warmup Period - -### Paper -- 500 iterations warmup before relocation or densification -- Noise is applied from the start (no warmup for noise) - -### Current implementation -- 500 steps warmup before both noise AND relocation - -### Fix -Apply noise from step 0 (or very early). The warmup should only gate relocation, not exploration noise. Early noise helps segments escape bad initial positions before they get stuck. - ---- - -## Summary: Priority-Ordered Fixes - -| Priority | Issue | Impact | Difficulty | -|----------|-------|--------|------------| -| **1** | Top-K gradient masking (Issue 4) | Fundamental — blocks all other mechanisms | Medium (try dense loss or soft top-K) | -| **2** | Regularization mechanism (Issue 2) | Without it, no dead segments, no relocation | Medium (add opacity parameter or stuck-detection) | -| **3** | Noise gate threshold (Issue 1) | Noise never activates in practice | Easy (raise threshold to operating regime) | -| **4** | Noise schedule (Issue 7) | Exploration dies too fast | Easy (remove separate decay) | -| **5** | Warmup for noise (Issue 8) | Delays early exploration | Easy (remove noise warmup) | -| **6** | Anisotropic noise (Issue 3) | Minor improvement for detector geometry | Low priority | -| **7** | Energy split ratio (Issue 5) | 50/50 is already correct for additive physics | No change needed | -| **8** | Moment reset (Issue 6) | Already correct | No change needed | - ---- - -## Recommended Implementation Order - -### Phase 1: Fix the gradient flow -Replace top-K pointcloud extraction with either: -- (a) Dense L1/L2 loss directly on wire signal arrays, or -- (b) Soft top-K with differentiable weighting, or -- (c) Full pointcloud (no top-K) with SW loss - -This alone may fix N=10 because all segments will receive gradients. - -### Phase 2: Fix the noise mechanism -- Remove noise warmup (apply from step 0) -- Raise gate threshold to ~80th percentile of energy range -- Remove separate noise exponential decay (couple to LR schedule only) - -### Phase 3: Fix the death/relocation cycle -- Add explicit opacity parameter `o_i ∈ [0,1]` multiplying energy, OR -- Implement stuck-segment detection (position/energy change rate monitoring) -- L1 regularize the opacity (not the energy directly) -- Tune death threshold relative to the new opacity parameter - -### Phase 4: Tune and validate -- Run N=10 closure test with all fixes -- Compare to baseline Adam at N=5 to ensure no regression -- Ablation: remove each component individually to verify co-dependency diff --git a/closure/archive/closure_analysis_original/closure_analysis/SGLD_FINDINGS.md b/closure/archive/closure_analysis_original/closure_analysis/SGLD_FINDINGS.md deleted file mode 100644 index 75f3bdb..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/SGLD_FINDINGS.md +++ /dev/null @@ -1,108 +0,0 @@ -# SGLD Closure Optimizer — Findings & Status - -## Goal -Reconstruct N point-charge segments (position + energy) from simulated wire signals using differentiable simulation + optimal transport loss. Adam works well for N=1–5 but fails at N=10 due to local minima. The SGLD-inspired optimizer adds noise injection, segment relocation, and L1 regularization to escape these minima. - -## What Works - -### Baseline Adam (5 segments, N_seg = N_truth) -- **Settings**: lr=0.3, b1=0.95, cosine schedule (alpha=0.01), LR_ENERGY_MULT=0.1, K=10000, N_PROJ=200 -- **Result**: Loss < 10^-3 by step ~320, mean pos error 1.1mm, max 2.7mm at 1200 steps -- **Key**: Cosine schedule is critical — exponential decay (100x) spends the learning budget too early (lr=0.03 at midpoint vs cosine's 0.15). Exponential only reached loss=0.004 at 1200 steps. -- **File**: `closure_analysis/sgld_closure.py --mode baseline` - -### Noise injection (5 segments) -- Mode `--mode noise`, 1500 steps: loss=0.002, mean pos error 2.9mm -- Noise gating works correctly: gate opens smoothly at GATE_THRESHOLD=0.2 MeV -- Noise doesn't destabilize converged segments (0 dead throughout) - -## What Fails - -### 10-segment equal (N_seg = N_truth = 10) - -**Baseline** (3000 steps): loss=0.126 (stuck from step ~500), mean pos error 30.5mm. Energy and positions freeze early. Seg 6 doesn't move at all from init (energy exactly 1.600 for all 3000 steps). - -**Full SGLD** (noise + relocation, 3000 steps): loss=0.017 (7x better), 5/10 segments within 5mm. BUT Seg 6 still completely stuck, and Seg 1 absorbed energy (grew to 4.4 MeV). - -**Why SGLD mechanisms didn't trigger**: All segment energies stayed above 0.5 MeV (DEAD_THRESHOLD=0.05, GATE_THRESHOLD=0.2). Zero dead segments throughout. The noise gate never opened and relocation never activated. - -**Root cause of stuck segments**: Seg 6 gets zero sim gradients. Its signal is masked out by the top-K=10000 pointcloud extraction when 10 overlapping segments compete for the brightest points. With no gradient, energy can't change, so thresholds are never reached. - -### Overcomplete (N_seg > N_truth) — Does NOT work - -Tested with 3 segments, 2 truths. The hypothesis was that extra segments would be L1-drained to zero, triggering relocation. This fails for two reasons: - -#### 1. L1 is negligible against sim gradients -- Sim gradients on energy: ~100 (at init) -- L1 gradient at λ=0.001: 0.001 (ratio: 0.00001x) -- L1 gradient at λ=50: 50 (still <1x) -- Even λ=50 produces identical energy distributions to λ=0 - -#### 2. Extra segments don't naturally drain -The SW loss distributes energy uniformly across all segments rather than concentrating it in the correct ones: - -| | E_seg0 (truth=1.0) | E_seg1 (truth=1.0) | E_seg2 (EXTRA) | -|---|---|---|---| -| No L1, 800 steps | 0.589 | 0.407 | 0.391 | -| L1=10 | 0.551 | 0.417 | 0.409 | -| L1=50 | 0.470 | 0.443 | 0.452 | - -All three segments converge to similar energies (~0.4–0.6 MeV). The extra segment is indistinguishable from truth segments. The SW loss on the combined signal can be minimized by distributing energy across many segments at wrong positions. - -**Positions don't converge either**: After 1200 steps in the overcomplete test, Seg 0 is at [-70, +20, +132] vs truth [-100, +50, +100] — barely moved from init. The extra segment's signal confuses the loss landscape for truth segments. - -#### 3. Energy learning rate sweep -- LR_ENERGY_MULT=0.1: Best separation (0.20 MeV gap between truth and extra), but slow -- LR_ENERGY_MULT=0.5: Less separation (0.12 MeV gap) -- LR_ENERGY_MULT=1.0: Separation REVERSES — extra ends up with MORE energy than truth seg 0. Chaotic oscillations. - -## Key Insights - -1. **Adam normalization**: Adam normalizes gradients, so the effective step is ~lr regardless of gradient magnitude. This means L1's absolute value doesn't matter for the update magnitude — only the direction matters. But since sim gradients and L1 push in the same direction (both positive = both push energy down), L1 doesn't change behavior. - -2. **SW loss doesn't incentivize sparsity**: The fundamental issue is that the Sliced Wasserstein distance on the combined (W,T) signal treats all segment contributions additively. More segments at lower energy can match a target as well as fewer segments at correct energy. There's no mechanism to prefer concentrated solutions. - -3. **Top-K masking kills gradients for weak segments**: With K=10000 points from a (W,T) signal containing 10 overlapping segments, weaker segments' contributions may fall below the K-th largest value. They get zero gradient and become permanently stuck. - -4. **Cosine schedule >> exponential for Adam convergence**: Cosine maintains higher lr through the middle of training. Exponential drops too fast. For SGLD noise, a separate exponential decay (`noise_tau`) controls noise amplitude independently. - -## Hyperparameters (current best) - -```python -LR_POSITION = 0.3 -B1 = 0.95 -B2 = 0.999 -LR_ENERGY_MULT = 0.1 -K = 10000 -N_PROJ = 200 -DEAD_THRESHOLD = 0.05 # MeV -GATE_THRESHOLD = 0.2 # MeV -K_GATE = 100 -NOISE_LR = 40.0 -NOISE_DECAY_FACTOR = 100 -RELOCATION_INTERVAL = 100 -WARMUP = 500 -``` - -Schedule: `optax.cosine_decay_schedule(init_value=0.3, decay_steps=total_steps, alpha=0.01)` - -## Files - -- `closure_analysis/sgld_closure.py` — Main optimizer with `--mode baseline|noise|full` -- `closure_analysis/test_l1_drain.py` — Diagnostic tests for L1/overcomplete/energy learning rate -- `closure_analysis/optimization_closure.py` — Original Adam baseline (reference) - -## Open Questions / Next Directions - -1. **Alternative loss functions**: There is a simpler projection-based loss in `ott_test/` (not yet investigated) that projects along a line rather than full SW. This might have different gradient properties that better separate segments. - -2. **Per-segment gradient flow**: The top-K masking problem could potentially be addressed by: - - Lowering K so weaker segments enter the pointcloud - - Using a soft top-K (differentiable relaxation) - - Stratified pointcloud extraction (guaranteed points per spatial region) - -3. **Stuck-segment detection**: Instead of energy-based thresholds (which fail when sim gradients prevent energy drain), detect stuck segments by monitoring position/energy change rate over a window. - -4. **Two-phase optimization**: Phase 1 — fix energies equal, optimize positions only. Phase 2 — unfreeze energies. This separates the permutation problem from the amplitude problem. - -5. **N_seg = N_truth remains the viable path**: The overcomplete approach fails because SW loss doesn't incentivize sparsity. Focus should be on making N=N_truth=10 work by solving the stuck-segment problem directly. diff --git a/closure/archive/closure_analysis_original/closure_analysis/benchmark_diffq_vs_interp.py b/closure/archive/closure_analysis_original/closure_analysis/benchmark_diffq_vs_interp.py deleted file mode 100644 index 53c1abe..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/benchmark_diffq_vs_interp.py +++ /dev/null @@ -1,271 +0,0 @@ -""" -Benchmark: adaptive grid vs diff_q vs normalized interp Huber SW timing. - -Sweeps K, n_proj, n_grid independently. Times value_and_grad through -the full closure pipeline (sim → pointcloud → Huber SW summed over 3 planes). - -Uses n_seg=5 segments. - -Run: python3 closure_analysis/benchmark_diffq_vs_interp.py -""" -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import time - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from closure_analysis.optimization_closure import TRUTH_BANK, INIT_OFFSET - -PLANES = [0, 1, 2] -DELTA = 0.01 - -# Defaults -K_DEFAULT = 10000 -GRID_DEFAULT = 500 -PROJ_DEFAULT = 200 - - -# ── Adaptive grid Huber (interp speed, correct weight grads) ──────────────── - -def make_huber_adaptive(n_proj, delta, n_grid): - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - base_grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - sum_a = jnp.sum(wts_a) - sum_b = jnp.sum(wts_b) - max_mass = jnp.maximum(sum_a, sum_b) - grid = base_grid * max_mass - - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - quant_a = jnp.interp(grid, cdf_a, proj_a_i[sort_a]) - quant_b = jnp.interp(grid, cdf_b, proj_b_i[sort_b]) - diff = quant_a - quant_b - abs_diff = jnp.abs(diff) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.mean(huber) - - spatial = jnp.mean(jax.vmap(w1d)(proj_a.T, proj_b.T)) - return spatial * max_mass - return sw - - -# ── Normalized interp Huber (old baseline) ────────────────────────────────── - -def make_huber_interp(n_proj, delta, n_grid): - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - wts_a = wts_a / jnp.sum(wts_a) - wts_b = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - quant_a = jnp.interp(grid, cdf_a, proj_a_i[sort_a]) - quant_b = jnp.interp(grid, cdf_b, proj_b_i[sort_b]) - diff = quant_a - quant_b - abs_diff = jnp.abs(diff) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.mean(huber) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - return sw - - -# ── diff_q-based Huber (OTT-style) ───────────────────────────────────────── - -def make_huber_diffq(n_proj, delta, n_pts): - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - n = pts_a.shape[0] - - def w1d(pa, pb): - i_a = jnp.argsort(pa) - i_b = jnp.argsort(pb) - sorted_a = pa[i_a] - sorted_b = pb[i_b] - - all_values = jnp.concatenate([sorted_a, sorted_b]) - all_sorter = jnp.argsort(all_values) - all_sorted = all_values[all_sorter] - - a_pdf = jnp.concatenate([wts_a[i_a], jnp.zeros(n)]) - a_pdf = a_pdf[all_sorter] - b_pdf = jnp.concatenate([jnp.zeros(n), wts_b[i_b]]) - b_pdf = b_pdf[all_sorter] - - a_cdf = jnp.cumsum(a_pdf) - b_cdf = jnp.cumsum(b_pdf) - - all_cdfs = jnp.concatenate([a_cdf, b_cdf]) - quantile_levels = jnp.sort(all_cdfs) - - i_a_inv = jnp.searchsorted(a_cdf, quantile_levels) - i_b_inv = jnp.searchsorted(b_cdf, quantile_levels) - qa = all_sorted[i_a_inv] - qb = all_sorted[i_b_inv] - - diff_q = jnp.diff(quantile_levels) - diff_pos = qa[1:] - qb[1:] - abs_diff = jnp.abs(diff_pos) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff_pos ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.sum(huber * diff_q) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - return sw - - -# ── Benchmark harness ──────────────────────────────────────────────────────── - -def build_loss(forward, target_clouds, kernel, k): - def loss_fn(params): - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], k) - tp, tw = target_clouds[p] - loss = loss + kernel(pts, w, tp, tw) - return loss - return loss_fn - - -def time_vg(vg_fn, params, n_trials=20): - times = [] - for _ in range(n_trials): - t0 = time.time() - loss, grads = vg_fn(params) - jax.block_until_ready(grads) - times.append(time.time() - t0) - times = np.array(times) * 1000 - return np.median(times), np.std(times) - - -def main(): - n_seg = 5 - truth_params = TRUTH_BANK[:n_seg] - init_params = jnp.array(truth_params + INIT_OFFSET) - - print("Building simulator...") - config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(config, differentiable=True, n_segments=n_seg) - forward = sim.build_forward() - - truth_seg = SegmentData( - positions_mm=jnp.array(truth_params[:, :3]), - de=jnp.array(truth_params[:, 3]), - ) - target_signals = forward(truth_seg) - sig_shape = target_signals[0].shape - max_pixels = sig_shape[0] * sig_shape[1] - print(f"Signal shape: {sig_shape} = {max_pixels} pixels per plane\n") - - methods_label = ["adaptive", "interp", "diff_q"] - - def run_sweep(sweep_name, sweep_values, make_k, make_nproj, make_ngrid): - print(f"\n{'='*80}") - print(f"SWEEP {sweep_name}") - print(f"{'='*80}") - print(f" {sweep_name:>8s} {'Method':>10s} {'JIT (s)':>8s} " - f"{'vg med (ms)':>12s} {'std (ms)':>10s}") - - for val in sweep_values: - k = make_k(val) - np_ = make_nproj(val) - ng = make_ngrid(val) - - if k > max_pixels: - continue - - tc = {} - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], k) - tc[p] = (pts, w) - - makers = [ - ("adaptive", lambda: make_huber_adaptive(np_, DELTA, ng)), - ("interp", lambda: make_huber_interp(np_, DELTA, ng)), - ("diff_q", lambda: make_huber_diffq(np_, DELTA, k)), - ] - - for method_name, make_kernel in makers: - kernel = make_kernel() - loss_fn = build_loss(forward, tc, kernel, k) - vg_fn = jax.value_and_grad(loss_fn) - - t0 = time.time() - loss, grads = vg_fn(init_params) - jax.block_until_ready(grads) - jit_time = time.time() - t0 - - med, std = time_vg(vg_fn, init_params) - print(f" {val:>8} {method_name:>10s} {jit_time:>8.1f} " - f"{med:>12.1f} {std:>10.1f}") - - # ── Sweep K ────────────────────────────────────────────────────────── - k_values = [1000, 5000, 10000, 25000, 50000, 100000] - run_sweep("K", - k_values, - make_k=lambda v: v, - make_nproj=lambda v: PROJ_DEFAULT, - make_ngrid=lambda v: GRID_DEFAULT) - - # ── Sweep n_proj ───────────────────────────────────────────────────── - proj_values = [10, 25, 50, 100, 200, 500] - run_sweep("n_proj", - proj_values, - make_k=lambda v: K_DEFAULT, - make_nproj=lambda v: v, - make_ngrid=lambda v: GRID_DEFAULT) - - # ── Sweep n_grid ───────────────────────────────────────────────────── - grid_values = [50, 100, 250, 500, 1000, 2000, 5000] - run_sweep("n_grid", - grid_values, - make_k=lambda v: K_DEFAULT, - make_nproj=lambda v: PROJ_DEFAULT, - make_ngrid=lambda v: v) - - print("\nNote: diff_q does NOT use n_grid (resolution = 4*K from CDF union).") - print("Note: adaptive uses n_grid for its base grid (same as interp).") - print("\nDone!") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/closure_analysis_original/closure_analysis/benchmark_huber_scaling.py b/closure/archive/closure_analysis_original/closure_analysis/benchmark_huber_scaling.py deleted file mode 100644 index e4d6a56..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/benchmark_huber_scaling.py +++ /dev/null @@ -1,195 +0,0 @@ -""" -Benchmark Huber uniform SW timing as a function of K, n_grid, n_proj. - -Varies one parameter at a time while holding the other two at defaults. -Times both forward and backward (value_and_grad) passes on the full -closure pipeline (sim → pointcloud → Huber SW summed over 3 planes). - -Uses n_seg=5 segments to match the proven closure baseline. - -Run: python3 closure_analysis/benchmark_huber_scaling.py -""" -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import time - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from closure_analysis.optimization_closure import TRUTH_BANK, INIT_OFFSET - -PLANES = [0, 1, 2] -DELTA = 0.01 - -# Defaults -K_DEFAULT = 10000 -GRID_DEFAULT = 500 -PROJ_DEFAULT = 200 - - -def make_huber_sw(n_proj, delta, n_grid): - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - wts_a = wts_a / jnp.sum(wts_a) - wts_b = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - quant_a = jnp.interp(grid, cdf_a, proj_a_i[sort_a]) - quant_b = jnp.interp(grid, cdf_b, proj_b_i[sort_b]) - diff = quant_a - quant_b - abs_diff = jnp.abs(diff) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.mean(huber) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - return sw - - -def build_closure_loss(forward, target_clouds, k, n_proj, n_grid): - """Build full closure loss: sim → pointcloud → Huber SW over 3 planes.""" - kernel = make_huber_sw(n_proj, DELTA, n_grid) - - def loss_fn(params): - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], k) - tp, tw = target_clouds[p] - loss = loss + kernel(pts, w, tp, tw) - return loss - return loss_fn - - -def time_vg(vg_fn, params, n_trials=20): - """Time value_and_grad over n_trials, return median ms.""" - times = [] - for _ in range(n_trials): - t0 = time.time() - loss, grads = vg_fn(params) - jax.block_until_ready(grads) - times.append(time.time() - t0) - times = np.array(times) * 1000 - return np.median(times), np.std(times) - - -def main(): - n_seg = 5 - truth_params = TRUTH_BANK[:n_seg] - init_params = jnp.array(truth_params + INIT_OFFSET) - - # Check signal shape to know max K - print("Building simulator...") - config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(config, differentiable=True, n_segments=n_seg) - forward = sim.build_forward() - - truth_seg = SegmentData( - positions_mm=jnp.array(truth_params[:, :3]), - de=jnp.array(truth_params[:, 3]), - ) - target_signals = forward(truth_seg) - sig_shape = target_signals[0].shape - max_pixels = sig_shape[0] * sig_shape[1] - print(f"Signal shape: {sig_shape} = {max_pixels} pixels per plane") - - # ── Sweep K ────────────────────────────────────────────────────────── - k_values = [1000, 5000, 10000, 25000, 50000, 100000] - k_values = [k for k in k_values if k <= max_pixels] - - print(f"\n{'='*70}") - print(f"SWEEP K (n_proj={PROJ_DEFAULT}, n_grid={GRID_DEFAULT})") - print(f"{'='*70}") - print(f" {'K':>8s} {'JIT (s)':>8s} {'vg median (ms)':>15s} {'std (ms)':>10s}") - - for k in k_values: - # Build target clouds at this K - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], k) - target_clouds[p] = (pts, w) - - loss_fn = build_closure_loss(forward, target_clouds, k, - PROJ_DEFAULT, GRID_DEFAULT) - vg_fn = jax.value_and_grad(loss_fn) - - # JIT warmup - t0 = time.time() - loss, grads = vg_fn(init_params) - jax.block_until_ready(grads) - jit_time = time.time() - t0 - - med, std = time_vg(vg_fn, init_params) - print(f" {k:>8d} {jit_time:>8.1f} {med:>15.1f} {std:>10.1f}") - - # ── Sweep n_grid ───────────────────────────────────────────────────── - grid_values = [50, 100, 250, 500, 1000, 2000, 5000] - - # Build target clouds once at K_DEFAULT - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K_DEFAULT) - target_clouds[p] = (pts, w) - - print(f"\n{'='*70}") - print(f"SWEEP n_grid (K={K_DEFAULT}, n_proj={PROJ_DEFAULT})") - print(f"{'='*70}") - print(f" {'n_grid':>8s} {'JIT (s)':>8s} {'vg median (ms)':>15s} {'std (ms)':>10s}") - - for ng in grid_values: - loss_fn = build_closure_loss(forward, target_clouds, K_DEFAULT, - PROJ_DEFAULT, ng) - vg_fn = jax.value_and_grad(loss_fn) - - t0 = time.time() - loss, grads = vg_fn(init_params) - jax.block_until_ready(grads) - jit_time = time.time() - t0 - - med, std = time_vg(vg_fn, init_params) - print(f" {ng:>8d} {jit_time:>8.1f} {med:>15.1f} {std:>10.1f}") - - # ── Sweep n_proj ───────────────────────────────────────────────────── - proj_values = [2, 10, 25, 50, 100, 200, 500, 1000] - - print(f"\n{'='*70}") - print(f"SWEEP n_proj (K={K_DEFAULT}, n_grid={GRID_DEFAULT})") - print(f"{'='*70}") - print(f" {'n_proj':>8s} {'JIT (s)':>8s} {'vg median (ms)':>15s} {'std (ms)':>10s}") - - for np_ in proj_values: - loss_fn = build_closure_loss(forward, target_clouds, K_DEFAULT, - np_, GRID_DEFAULT) - vg_fn = jax.value_and_grad(loss_fn) - - t0 = time.time() - loss, grads = vg_fn(init_params) - jax.block_until_ready(grads) - jit_time = time.time() - t0 - - med, std = time_vg(vg_fn, init_params) - print(f" {np_:>8d} {jit_time:>8.1f} {med:>15.1f} {std:>10.1f}") - - print("\nDone!") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/closure_analysis_original/closure_analysis/closure_10seg.png b/closure/archive/closure_analysis_original/closure_analysis/closure_10seg.png deleted file mode 100644 index 5194a8c..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/closure_10seg.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/closure_1seg.png b/closure/archive/closure_analysis_original/closure_analysis/closure_1seg.png deleted file mode 100644 index 9edb13e..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/closure_1seg.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/closure_2seg.png b/closure/archive/closure_analysis_original/closure_analysis/closure_2seg.png deleted file mode 100644 index 59e53c9..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/closure_2seg.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/closure_3seg.png b/closure/archive/closure_analysis_original/closure_analysis/closure_3seg.png deleted file mode 100644 index 34cd9cd..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/closure_3seg.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/closure_5seg.png b/closure/archive/closure_analysis_original/closure_analysis/closure_5seg.png deleted file mode 100644 index 2ed1198..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/closure_5seg.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/compare_sw_gradient_paths.py b/closure/archive/closure_analysis_original/closure_analysis/compare_sw_gradient_paths.py deleted file mode 100644 index aca6d12..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/compare_sw_gradient_paths.py +++ /dev/null @@ -1,1281 +0,0 @@ -""" -Methodical comparison: WHY does OTT SW get correct weight gradients -but our jnp.interp-based Huber SW does not? - -Isolates the exact gradient failure by testing each component: - -1. jnp.interp gradient w.r.t. xp (CDF breakpoints) — the suspect -2. OTT-style diff_q weighting — the working alternative -3. Full 1D Wasserstein: interp-based vs OTT-style - -Uses simple synthetic 1D data (no simulation) to eliminate confounders. - -Run: python3 closure_analysis/compare_sw_gradient_paths.py -""" - -import jax -import jax.numpy as jnp -import numpy as np - -np.set_printoptions(precision=6, suppress=False) - - -# ============================================================================= -# Test 1: jnp.interp gradient w.r.t. xp -# ============================================================================= - -def test_interp_xp_gradient(): - """Does jnp.interp propagate gradients through xp (breakpoints)?""" - print("=" * 70) - print("TEST 1: jnp.interp gradient w.r.t. xp (CDF breakpoints)") - print("=" * 70) - - # Fixed grid and values (fp), vary breakpoints (xp) via a scale factor - grid = jnp.linspace(0.01, 0.99, 100) - fp = jnp.linspace(0.0, 1.0, 50) # 50 sorted position values - - def loss_via_interp(scale): - """Scale the CDF breakpoints by `scale` and interpolate.""" - xp = jnp.linspace(0.0, scale, 50) # CDF goes from 0 to `scale` - quantiles = jnp.interp(grid, xp, fp) - return jnp.mean(quantiles ** 2) - - # At scale=1.0, CDF and grid are matched - scale = 1.0 - ad_grad = float(jax.grad(loss_via_interp)(scale)) - eps = 1e-4 - fd_grad = (float(loss_via_interp(scale + eps)) - - float(loss_via_interp(scale - eps))) / (2 * eps) - - print(f" scale=1.0: AD grad = {ad_grad:.6e}, FD grad = {fd_grad:.6e}") - print(f" ratio AD/FD = {ad_grad / (fd_grad + 1e-30):.4f}") - - # At scale=2.0, CDF extends beyond grid - scale = 2.0 - ad_grad = float(jax.grad(loss_via_interp)(scale)) - fd_grad = (float(loss_via_interp(scale + eps)) - - float(loss_via_interp(scale - eps))) / (2 * eps) - - print(f" scale=2.0: AD grad = {ad_grad:.6e}, FD grad = {fd_grad:.6e}") - print(f" ratio AD/FD = {ad_grad / (fd_grad + 1e-30):.4f}") - - # At scale=0.5, CDF compressed - scale = 0.5 - ad_grad = float(jax.grad(loss_via_interp)(scale)) - fd_grad = (float(loss_via_interp(scale + eps)) - - float(loss_via_interp(scale - eps))) / (2 * eps) - - print(f" scale=0.5: AD grad = {ad_grad:.6e}, FD grad = {fd_grad:.6e}") - print(f" ratio AD/FD = {ad_grad / (fd_grad + 1e-30):.4f}") - print() - - -# ============================================================================= -# Test 2: Our interp-based 1D Wasserstein -# ============================================================================= - -def test_interp_w1d(): - """Our approach: sort, cumsum → CDF, interp(grid, CDF, sorted_vals).""" - print("=" * 70) - print("TEST 2: Interp-based 1D quantile distance (our approach)") - print("=" * 70) - - # Two sets of positions (fixed) - key = jax.random.PRNGKey(0) - n = 200 - pos_a = jax.random.uniform(key, (n,), minval=0.0, maxval=1.0) - pos_b = jax.random.uniform(jax.random.PRNGKey(1), (n,), minval=0.0, maxval=1.0) - - grid = jnp.linspace(1e-6, 1.0 - 1e-6, 500) - - def w1d_interp(wts_a, wts_b): - """Our interp-based approach — weights NOT normalized.""" - sort_a = jnp.argsort(pos_a) - sort_b = jnp.argsort(pos_b) - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - quant_a = jnp.interp(grid, cdf_a, pos_a[sort_a]) - quant_b = jnp.interp(grid, cdf_b, pos_b[sort_b]) - return jnp.mean((quant_a - quant_b) ** 2) - - def w1d_interp_normalized(wts_a, wts_b): - """Our interp-based approach — weights normalized.""" - wts_an = wts_a / jnp.sum(wts_a) - wts_bn = wts_b / jnp.sum(wts_b) - sort_a = jnp.argsort(pos_a) - sort_b = jnp.argsort(pos_b) - cdf_a = jnp.cumsum(wts_an[sort_a]) - cdf_b = jnp.cumsum(wts_bn[sort_b]) - quant_a = jnp.interp(grid, cdf_a, pos_a[sort_a]) - quant_b = jnp.interp(grid, cdf_b, pos_b[sort_b]) - return jnp.mean((quant_a - quant_b) ** 2) - - # Base weights - wts_a = jnp.ones(n) - wts_b = jnp.ones(n) - - # Test: scale wts_a by alpha - def loss_unnorm(alpha): - return w1d_interp(alpha * wts_a, wts_b) - - def loss_norm(alpha): - return w1d_interp_normalized(alpha * wts_a, wts_b) - - alpha = 1.0 - eps = 1e-4 - - ad_unnorm = float(jax.grad(loss_unnorm)(alpha)) - fd_unnorm = (float(loss_unnorm(alpha + eps)) - - float(loss_unnorm(alpha - eps))) / (2 * eps) - - ad_norm = float(jax.grad(loss_norm)(alpha)) - fd_norm = (float(loss_norm(alpha + eps)) - - float(loss_norm(alpha - eps))) / (2 * eps) - - print(f" Unnormalized weights:") - print(f" AD grad = {ad_unnorm:.6e}, FD grad = {fd_unnorm:.6e}") - print(f" ratio AD/FD = {ad_unnorm / (fd_unnorm + 1e-30):.4f}") - print(f" Normalized weights:") - print(f" AD grad = {ad_norm:.6e}, FD grad = {fd_norm:.6e}") - print(f" ratio AD/FD = {ad_norm / (fd_norm + 1e-30):.4f}") - - # Test at alpha=2.0 (energy doubled) - alpha = 2.0 - ad_unnorm = float(jax.grad(loss_unnorm)(alpha)) - fd_unnorm = (float(loss_unnorm(alpha + eps)) - - float(loss_unnorm(alpha - eps))) / (2 * eps) - - print(f" Unnormalized at alpha=2.0:") - print(f" AD grad = {ad_unnorm:.6e}, FD grad = {fd_unnorm:.6e}") - print(f" ratio AD/FD = {ad_unnorm / (fd_unnorm + 1e-30):.4f}") - print() - - -# ============================================================================= -# Test 3: OTT-style 1D Wasserstein (diff_q weighting) -# ============================================================================= - -def test_ott_style_w1d(): - """OTT approach: merge CDFs → quantile_levels → diff_q → weighted cost.""" - print("=" * 70) - print("TEST 3: OTT-style 1D distance (diff_q weighting)") - print("=" * 70) - - key = jax.random.PRNGKey(0) - n = 200 - pos_a = jax.random.uniform(key, (n,), minval=0.0, maxval=1.0) - pos_b = jax.random.uniform(jax.random.PRNGKey(1), (n,), minval=0.0, maxval=1.0) - - def w1d_ott_style(wts_a, wts_b): - """OTT-style: merge, sort, CDF union, diff_q weighting.""" - # Sort each distribution - i_a = jnp.argsort(pos_a) - i_b = jnp.argsort(pos_b) - sorted_a = pos_a[i_a] - sorted_b = pos_b[i_b] - - # Merge all values - all_values = jnp.concatenate([sorted_a, sorted_b]) - all_sorter = jnp.argsort(all_values) - all_sorted = all_values[all_sorter] - - # Build PDFs in merged order - a_pdf = jnp.concatenate([wts_a[i_a], jnp.zeros(n)]) - a_pdf = a_pdf[all_sorter] - b_pdf = jnp.concatenate([jnp.zeros(n), wts_b[i_b]]) - b_pdf = b_pdf[all_sorter] - - # CDFs - a_cdf = jnp.cumsum(a_pdf) - b_cdf = jnp.cumsum(b_pdf) - - # Quantile levels = sorted union of both CDFs - all_cdfs = jnp.concatenate([a_cdf, b_cdf]) - quantile_levels = jnp.sort(all_cdfs) - - # Inverse CDFs via searchsorted - i_a_inv = jnp.searchsorted(a_cdf, quantile_levels) - i_b_inv = jnp.searchsorted(b_cdf, quantile_levels) - qa = all_sorted[i_a_inv] - qb = all_sorted[i_b_inv] - - # Weighted cost - diff_q = jnp.diff(quantile_levels) - costs = (qa[1:] - qb[1:]) ** 2 - return jnp.sum(costs * diff_q) - - # Base weights - wts_a = jnp.ones(n) - wts_b = jnp.ones(n) - - def loss_ott(alpha): - return w1d_ott_style(alpha * wts_a, wts_b) - - eps = 1e-4 - - for alpha in [1.0, 2.0, 0.5]: - ad = float(jax.grad(loss_ott)(alpha)) - fd = (float(loss_ott(alpha + eps)) - - float(loss_ott(alpha - eps))) / (2 * eps) - print(f" alpha={alpha}: AD = {ad:.6e}, FD = {fd:.6e}, " - f"ratio = {ad / (fd + 1e-30):.4f}") - print() - - -# ============================================================================= -# Test 4: Isolate jnp.interp xp gradient vs diff_q gradient -# ============================================================================= - -def test_gradient_paths_isolated(): - """Directly compare the two gradient mechanisms for weight sensitivity.""" - print("=" * 70) - print("TEST 4: Isolated gradient paths — interp(xp) vs diff_q") - print("=" * 70) - - n = 100 - positions = jnp.linspace(0.0, 1.0, n) # fixed sorted positions - grid = jnp.linspace(1e-6, 1.0 - 1e-6, 500) - base_weights = jnp.ones(n) - - # Path A: weights → CDF → interp(grid, CDF, positions) - def path_interp(alpha): - wts = alpha * base_weights - cdf = jnp.cumsum(wts) - quantiles = jnp.interp(grid, cdf, positions) - return jnp.mean(quantiles ** 2) - - # Path B: weights → CDF → diff(CDF) → weighted sum - def path_diff_q(alpha): - wts = alpha * base_weights - cdf = jnp.cumsum(wts) - # Use quantile levels from CDF - quantile_levels = jnp.sort(cdf) - diff_q = jnp.diff(quantile_levels) - # searchsorted to get position values at each quantile - indices = jnp.searchsorted(cdf, quantile_levels) - q_vals = positions[indices] - costs = q_vals[1:] ** 2 - return jnp.sum(costs * diff_q) - - eps = 1e-4 - - print(" Path A: weights → cumsum → CDF as xp in jnp.interp") - for alpha in [0.5, 1.0, 2.0, 5.0]: - ad = float(jax.grad(path_interp)(alpha)) - fd = (float(path_interp(alpha + eps)) - - float(path_interp(alpha - eps))) / (2 * eps) - print(f" alpha={alpha:.1f}: AD = {ad:+.6e}, FD = {fd:+.6e}, " - f"ratio = {ad / (fd + 1e-30):.4f}") - - print(" Path B: weights → cumsum → CDF → diff_q multiplier") - for alpha in [0.5, 1.0, 2.0, 5.0]: - ad = float(jax.grad(path_diff_q)(alpha)) - fd = (float(path_diff_q(alpha + eps)) - - float(path_diff_q(alpha - eps))) / (2 * eps) - print(f" alpha={alpha:.1f}: AD = {ad:+.6e}, FD = {fd:+.6e}, " - f"ratio = {ad / (fd + 1e-30):.4f}") - print() - - -# ============================================================================= -# Test 5: Full pipeline comparison with actual OTT -# ============================================================================= - -def test_full_comparison(): - """Full pipeline: sim-like pointclouds, compare OTT vs Huber for dE grad.""" - print("=" * 70) - print("TEST 5: Full comparison — OTT SW vs Huber (unnormalized) vs Huber (normalized)") - print("=" * 70) - - from ott.tools import sliced - - key = jax.random.PRNGKey(42) - n = 500 - - # Two 2D pointclouds - pts_a = jax.random.uniform(key, (n, 2)) - pts_b = jax.random.uniform(jax.random.PRNGKey(1), (n, 2)) - base_wts_a = jax.random.uniform(jax.random.PRNGKey(2), (n,)) + 0.1 - wts_b = jax.random.uniform(jax.random.PRNGKey(3), (n,)) + 0.1 - - n_proj = 50 - delta = 0.01 - - # Huber interp-based (unnormalized) - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, 500) - - def huber_unnorm(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - sa = jnp.argsort(pa) - sb = jnp.argsort(pb) - cdf_a = jnp.cumsum(wts_a[sa]) - cdf_b = jnp.cumsum(wts_b[sb]) - qa = jnp.interp(grid, cdf_a, pa[sa]) - qb = jnp.interp(grid, cdf_b, pb[sb]) - diff = qa - qb - ad = jnp.abs(diff) - return jnp.mean(jnp.where(ad <= delta, 0.5 * diff**2, - delta * (ad - 0.5 * delta))) - return jnp.mean(jax.vmap(w1d)(proj_a.T, proj_b.T)) - - # Huber interp-based (normalized) - def huber_norm(alpha): - wts_a = alpha * base_wts_a - wa = wts_a / jnp.sum(wts_a) - wb = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - sa = jnp.argsort(pa) - sb = jnp.argsort(pb) - cdf_a = jnp.cumsum(wa[sa]) - cdf_b = jnp.cumsum(wb[sb]) - qa = jnp.interp(grid, cdf_a, pa[sa]) - qb = jnp.interp(grid, cdf_b, pb[sb]) - diff = qa - qb - ad = jnp.abs(diff) - return jnp.mean(jnp.where(ad <= delta, 0.5 * diff**2, - delta * (ad - 0.5 * delta))) - return jnp.mean(jax.vmap(w1d)(proj_a.T, proj_b.T)) - - # OTT SW - def ott_sw(alpha): - wts_a = alpha * base_wts_a - loss, _ = sliced.sliced_wasserstein( - x=pts_a, y=pts_b, a=wts_a, b=wts_b, - n_proj=n_proj, rng=key) - return loss - - eps = 1e-4 - - # JIT compile all - _ = jax.grad(huber_unnorm)(1.0) - _ = jax.grad(huber_norm)(1.0) - _ = jax.grad(ott_sw)(1.0) - - print(f" Varying weight scale alpha (simulates energy change):\n") - print(f" {'alpha':>6s} {'Method':>20s} {'AD grad':>12s} {'FD grad':>12s} {'ratio':>8s}") - print(f" {'-'*64}") - - for alpha in [0.5, 1.0, 1.5, 2.0]: - for name, fn in [("Huber unnorm", huber_unnorm), - ("Huber norm", huber_norm), - ("OTT SW", ott_sw)]: - ad = float(jax.grad(fn)(alpha)) - fd = (float(fn(alpha + eps)) - float(fn(alpha - eps))) / (2 * eps) - ratio = ad / (fd + 1e-30) if abs(fd) > 1e-12 else float('inf') - print(f" {alpha:>6.1f} {name:>20s} {ad:>+12.6e} {fd:>+12.6e} {ratio:>8.3f}") - print() - - -# ============================================================================= -# Test 6: OTT-style Huber (diff_q path) — the proposed fix -# ============================================================================= - -def test_huber_diff_q(): - """Huber SW using OTT-style diff_q weighting instead of jnp.interp.""" - print("=" * 70) - print("TEST 6: Huber with diff_q path (proposed fix) vs OTT vs interp") - print("=" * 70) - - from ott.tools import sliced - - key = jax.random.PRNGKey(42) - n = 500 - - pts_a = jax.random.uniform(key, (n, 2)) - pts_b = jax.random.uniform(jax.random.PRNGKey(1), (n, 2)) - base_wts_a = jax.random.uniform(jax.random.PRNGKey(2), (n,)) + 0.1 - wts_b = jax.random.uniform(jax.random.PRNGKey(3), (n,)) + 0.1 - - n_proj = 50 - delta = 0.01 - - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - - # NEW: Huber with diff_q path (OTT-style gradient flow) - def huber_diff_q(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T # (n, n_proj) - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - # Sort each distribution - i_a = jnp.argsort(pa) - i_b = jnp.argsort(pb) - sorted_a = pa[i_a] - sorted_b = pb[i_b] - - # Merge all position values - all_values = jnp.concatenate([sorted_a, sorted_b]) - all_sorter = jnp.argsort(all_values) - all_sorted = all_values[all_sorter] - - # Build PDFs in merged order - a_pdf = jnp.concatenate([wts_a[i_a], jnp.zeros(n)]) - a_pdf = a_pdf[all_sorter] - b_pdf = jnp.concatenate([jnp.zeros(n), wts_b[i_b]]) - b_pdf = b_pdf[all_sorter] - - # CDFs - a_cdf = jnp.cumsum(a_pdf) - b_cdf = jnp.cumsum(b_pdf) - - # Quantile levels = sorted union of both CDFs - all_cdfs = jnp.concatenate([a_cdf, b_cdf]) - quantile_levels = jnp.sort(all_cdfs) - - # Inverse CDFs via searchsorted → gather positions - i_a_inv = jnp.searchsorted(a_cdf, quantile_levels) - i_b_inv = jnp.searchsorted(b_cdf, quantile_levels) - qa = all_sorted[i_a_inv] - qb = all_sorted[i_b_inv] - - # Huber cost weighted by quantile spacing - diff_q = jnp.diff(quantile_levels) - diff_pos = qa[1:] - qb[1:] - abs_diff = jnp.abs(diff_pos) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff_pos ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.sum(huber * diff_q) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - # Old interp-based (unnormalized) for comparison - grid = jnp.linspace(1e-6, 1.0 - 1e-6, 500) - - def huber_interp(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - sa = jnp.argsort(pa) - sb = jnp.argsort(pb) - cdf_a = jnp.cumsum(wts_a[sa]) - cdf_b = jnp.cumsum(wts_b[sb]) - qa = jnp.interp(grid, cdf_a, pa[sa]) - qb = jnp.interp(grid, cdf_b, pb[sb]) - diff = qa - qb - ad = jnp.abs(diff) - return jnp.mean(jnp.where(ad <= delta, 0.5 * diff**2, - delta * (ad - 0.5 * delta))) - return jnp.mean(jax.vmap(w1d)(proj_a.T, proj_b.T)) - - # OTT SW - def ott_sw(alpha): - wts_a = alpha * base_wts_a - loss, _ = sliced.sliced_wasserstein( - x=pts_a, y=pts_b, a=wts_a, b=wts_b, - n_proj=n_proj, rng=key) - return loss - - eps = 1e-4 - - # JIT warmup - _ = jax.grad(huber_diff_q)(1.0) - _ = jax.grad(huber_interp)(1.0) - _ = jax.grad(ott_sw)(1.0) - - print(f"\n {'alpha':>6s} {'Method':>22s} {'Loss':>12s} {'AD grad':>12s} " - f"{'FD grad':>12s} {'ratio':>8s}") - print(f" {'-'*78}") - - for alpha in [0.5, 1.0, 1.5, 2.0]: - for name, fn in [("Huber diff_q (NEW)", huber_diff_q), - ("Huber interp (OLD)", huber_interp), - ("OTT SW", ott_sw)]: - loss_val = float(fn(alpha)) - ad = float(jax.grad(fn)(alpha)) - fd = (float(fn(alpha + eps)) - float(fn(alpha - eps))) / (2 * eps) - ratio = ad / (fd + 1e-30) if abs(fd) > 1e-12 else float('inf') - print(f" {alpha:>6.1f} {name:>22s} {loss_val:>12.6e} " - f"{ad:>+12.6e} {fd:>+12.6e} {ratio:>8.3f}") - print() - - -# ============================================================================= -# Test 7: Adaptive grid interp — can we keep interp speed + get weight grads? -# ============================================================================= - -def test_adaptive_grid(): - """Test interp with adaptive grid that scales with total mass. - - Idea: instead of fixed grid on [0,1] with normalized CDFs, use - unnormalized CDFs and scale the grid to [0, max_mass]. Weight - sensitivity enters through: - 1. grid = base_grid * max_mass → interp's x argument (O(1) grad) - 2. loss = mean(huber) * max_mass → multiplicative factor - """ - print("=" * 70) - print("TEST 7: Adaptive grid interp vs diff_q vs fixed interp") - print("=" * 70) - - from ott.tools import sliced - - key = jax.random.PRNGKey(42) - n = 500 - - pts_a = jax.random.uniform(key, (n, 2)) - pts_b = jax.random.uniform(jax.random.PRNGKey(1), (n, 2)) - base_wts_a = jax.random.uniform(jax.random.PRNGKey(2), (n,)) + 0.1 - wts_b = jax.random.uniform(jax.random.PRNGKey(3), (n,)) + 0.1 - - n_proj = 50 - n_grid = 500 - delta = 0.01 - - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - base_grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - # ── Method A: Adaptive grid (unnormalized CDF, grid scales with mass) ── - - def huber_adaptive(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - sum_a = jnp.sum(wts_a) - sum_b = jnp.sum(wts_b) - max_mass = jnp.maximum(sum_a, sum_b) - - # Grid covers [0, max_mass] - grid = base_grid * max_mass - - def w1d(pa, pb): - sa = jnp.argsort(pa) - sb = jnp.argsort(pb) - cdf_a = jnp.cumsum(wts_a[sa]) - cdf_b = jnp.cumsum(wts_b[sb]) - qa = jnp.interp(grid, cdf_a, pa[sa]) - qb = jnp.interp(grid, cdf_b, pb[sb]) - diff = qa - qb - ad = jnp.abs(diff) - huber = jnp.where(ad <= delta, 0.5 * diff**2, - delta * (ad - 0.5 * delta)) - return jnp.mean(huber) - - spatial = jnp.mean(jax.vmap(w1d)(proj_a.T, proj_b.T)) - # Integral over [0, max_mass] = max_mass * mean - return spatial * max_mass - - # ── Method B: Normalized interp × average mass ── - - def huber_norm_scaled(alpha): - wts_a = alpha * base_wts_a - sum_a = jnp.sum(wts_a) - sum_b = jnp.sum(wts_b) - wa = wts_a / sum_a - wb = wts_b / sum_b - - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - sa = jnp.argsort(pa) - sb = jnp.argsort(pb) - cdf_a = jnp.cumsum(wa[sa]) - cdf_b = jnp.cumsum(wb[sb]) - qa = jnp.interp(base_grid, cdf_a, pa[sa]) - qb = jnp.interp(base_grid, cdf_b, pb[sb]) - diff = qa - qb - ad = jnp.abs(diff) - huber = jnp.where(ad <= delta, 0.5 * diff**2, - delta * (ad - 0.5 * delta)) - return jnp.mean(huber) - - spatial = jnp.mean(jax.vmap(w1d)(proj_a.T, proj_b.T)) - return spatial * (sum_a + sum_b) / 2.0 - - # ── Method C: diff_q (OTT-style, known working) ── - - def huber_diff_q(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - i_a = jnp.argsort(pa) - i_b = jnp.argsort(pb) - sorted_a = pa[i_a] - sorted_b = pb[i_b] - - all_values = jnp.concatenate([sorted_a, sorted_b]) - all_sorter = jnp.argsort(all_values) - all_sorted = all_values[all_sorter] - - a_pdf = jnp.concatenate([wts_a[i_a], jnp.zeros(n)]) - a_pdf = a_pdf[all_sorter] - b_pdf = jnp.concatenate([jnp.zeros(n), wts_b[i_b]]) - b_pdf = b_pdf[all_sorter] - - a_cdf = jnp.cumsum(a_pdf) - b_cdf = jnp.cumsum(b_pdf) - - all_cdfs = jnp.concatenate([a_cdf, b_cdf]) - quantile_levels = jnp.sort(all_cdfs) - - i_a_inv = jnp.searchsorted(a_cdf, quantile_levels) - i_b_inv = jnp.searchsorted(b_cdf, quantile_levels) - qa = all_sorted[i_a_inv] - qb = all_sorted[i_b_inv] - - diff_q = jnp.diff(quantile_levels) - diff_pos = qa[1:] - qb[1:] - abs_diff = jnp.abs(diff_pos) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff_pos ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.sum(huber * diff_q) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - # ── Method D: Fixed grid interp unnormalized (old, broken) ── - - def huber_fixed(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - sa = jnp.argsort(pa) - sb = jnp.argsort(pb) - cdf_a = jnp.cumsum(wts_a[sa]) - cdf_b = jnp.cumsum(wts_b[sb]) - qa = jnp.interp(base_grid, cdf_a, pa[sa]) - qb = jnp.interp(base_grid, cdf_b, pb[sb]) - diff = qa - qb - ad = jnp.abs(diff) - return jnp.mean(jnp.where(ad <= delta, 0.5 * diff**2, - delta * (ad - 0.5 * delta))) - return jnp.mean(jax.vmap(w1d)(proj_a.T, proj_b.T)) - - # ── OTT SW ── - - def ott_sw(alpha): - wts_a = alpha * base_wts_a - loss, _ = sliced.sliced_wasserstein( - x=pts_a, y=pts_b, a=wts_a, b=wts_b, - n_proj=n_proj, rng=key) - return loss - - eps = 1e-4 - - methods = [ - ("Adaptive grid", huber_adaptive), - ("Norm × mass", huber_norm_scaled), - ("diff_q (OTT-style)", huber_diff_q), - ("Fixed grid (OLD)", huber_fixed), - ("OTT SW", ott_sw), - ] - - # JIT warmup - for name, fn in methods: - _ = jax.grad(fn)(1.0) - - print(f"\n {'alpha':>6s} {'Method':>22s} {'Loss':>12s} {'AD grad':>12s} " - f"{'FD grad':>12s} {'AD/FD':>8s}") - print(f" {'-'*82}") - - for alpha in [0.5, 1.0, 1.5, 2.0]: - for name, fn in methods: - loss_val = float(fn(alpha)) - ad = float(jax.grad(fn)(alpha)) - fd = (float(fn(alpha + eps)) - float(fn(alpha - eps))) / (2 * eps) - ratio = ad / (fd + 1e-30) if abs(fd) > 1e-12 else float('inf') - print(f" {alpha:>6.1f} {name:>22s} {loss_val:>12.6e} " - f"{ad:>+12.6e} {fd:>+12.6e} {ratio:>8.3f}") - print() - - -# ============================================================================= -# Test 8: CDF-based interp — flip the interpolation -# ============================================================================= - -def test_cdf_interp(): - """Flip the interp: interpolate CDF at positions instead of positions at CDF. - - Quantile approach: interp(cdf_grid, CDF_breakpoints, positions) - weights → xp (weak), positions → fp (strong) - - CDF approach: interp(position_grid, sorted_positions, CDF_values) - weights → fp (STRONG), positions → xp (weak but irrelevant) - - Loss = mean(Huber(F_a(x) - F_b(x))) — a robust Cramér-type distance. - """ - print("=" * 70) - print("TEST 8: CDF-based interp (flip: weights in fp, not xp)") - print("=" * 70) - - from ott.tools import sliced - - key = jax.random.PRNGKey(42) - n = 500 - - pts_a = jax.random.uniform(key, (n, 2)) - pts_b = jax.random.uniform(jax.random.PRNGKey(1), (n, 2)) - base_wts_a = jax.random.uniform(jax.random.PRNGKey(2), (n,)) + 0.1 - wts_b = jax.random.uniform(jax.random.PRNGKey(3), (n,)) + 0.1 - - n_proj = 50 - n_grid = 500 - delta_cdf = 1.0 # CDF differences can be O(100), so delta is larger - - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - - # Position grid: fixed on [0, 1] since pointcloud coords are normalized - pos_grid = jnp.linspace(0.0, 1.0, n_grid) - - # ── CDF-based interp (NEW) ── - - def huber_cdf(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T # (n, n_proj) - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - # Sort each distribution by projected position - sa = jnp.argsort(pa) - sb = jnp.argsort(pb) - - # Evaluate CDFs at position grid using interp - # interp(x, xp, fp): xp = sorted positions, fp = CDF values - # Weights flow through fp → STRONG gradient - cdf_a = jnp.cumsum(wts_a[sa]) - cdf_b = jnp.cumsum(wts_b[sb]) - - F_a = jnp.interp(pos_grid, pa[sa], cdf_a) - F_b = jnp.interp(pos_grid, pb[sb], cdf_b) - - cdf_diff = F_a - F_b - abs_diff = jnp.abs(cdf_diff) - huber = jnp.where(abs_diff <= delta_cdf, - 0.5 * cdf_diff ** 2, - delta_cdf * (abs_diff - 0.5 * delta_cdf)) - return jnp.mean(huber) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - # ── Quantile-based normalized interp (OLD) ── - - base_grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - delta_quant = 0.01 - - def huber_quantile_norm(alpha): - wts_a = alpha * base_wts_a - wa = wts_a / jnp.sum(wts_a) - wb = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - sa = jnp.argsort(pa) - sb = jnp.argsort(pb) - cdf_a = jnp.cumsum(wa[sa]) - cdf_b = jnp.cumsum(wb[sb]) - qa = jnp.interp(base_grid, cdf_a, pa[sa]) - qb = jnp.interp(base_grid, cdf_b, pb[sb]) - diff = qa - qb - ad = jnp.abs(diff) - return jnp.mean(jnp.where(ad <= delta_quant, 0.5 * diff**2, - delta_quant * (ad - 0.5 * delta_quant))) - return jnp.mean(jax.vmap(w1d)(proj_a.T, proj_b.T)) - - # ── diff_q (known working reference) ── - - def huber_diff_q(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - i_a = jnp.argsort(pa) - i_b = jnp.argsort(pb) - sorted_a = pa[i_a] - sorted_b = pb[i_b] - - all_values = jnp.concatenate([sorted_a, sorted_b]) - all_sorter = jnp.argsort(all_values) - all_sorted = all_values[all_sorter] - - a_pdf = jnp.concatenate([wts_a[i_a], jnp.zeros(n)]) - a_pdf = a_pdf[all_sorter] - b_pdf = jnp.concatenate([jnp.zeros(n), wts_b[i_b]]) - b_pdf = b_pdf[all_sorter] - - a_cdf = jnp.cumsum(a_pdf) - b_cdf = jnp.cumsum(b_pdf) - - all_cdfs = jnp.concatenate([a_cdf, b_cdf]) - quantile_levels = jnp.sort(all_cdfs) - - i_a_inv = jnp.searchsorted(a_cdf, quantile_levels) - i_b_inv = jnp.searchsorted(b_cdf, quantile_levels) - qa = all_sorted[i_a_inv] - qb = all_sorted[i_b_inv] - - diff_q = jnp.diff(quantile_levels) - diff_pos = qa[1:] - qb[1:] - abs_diff = jnp.abs(diff_pos) - huber = jnp.where(abs_diff <= 0.01, - 0.5 * diff_pos ** 2, - 0.01 * (abs_diff - 0.5 * 0.01)) - return jnp.sum(huber * diff_q) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - # ── OTT SW ── - - def ott_sw(alpha): - wts_a = alpha * base_wts_a - loss, _ = sliced.sliced_wasserstein( - x=pts_a, y=pts_b, a=wts_a, b=wts_b, - n_proj=n_proj, rng=key) - return loss - - eps = 1e-4 - - methods = [ - ("CDF interp (NEW)", huber_cdf), - ("Quantile norm (OLD)", huber_quantile_norm), - ("diff_q", huber_diff_q), - ("OTT SW", ott_sw), - ] - - # JIT warmup - for name, fn in methods: - _ = jax.grad(fn)(1.0) - - print(f"\n {'alpha':>6s} {'Method':>22s} {'Loss':>12s} {'AD grad':>12s} " - f"{'FD grad':>12s} {'AD/FD':>8s}") - print(f" {'-'*82}") - - for alpha in [0.5, 1.0, 1.5, 2.0]: - for name, fn in methods: - loss_val = float(fn(alpha)) - ad = float(jax.grad(fn)(alpha)) - fd = (float(fn(alpha + eps)) - float(fn(alpha - eps))) / (2 * eps) - ratio = ad / (fd + 1e-30) if abs(fd) > 1e-12 else float('inf') - print(f" {alpha:>6.1f} {name:>22s} {loss_val:>12.6e} " - f"{ad:>+12.6e} {fd:>+12.6e} {ratio:>8.3f}") - print() - - -# ============================================================================= -# Test 9: Riemann-sum Wasserstein — weights multiply the cost directly -# ============================================================================= - -def test_riemann_sum(): - """Riemann-sum approach: evaluate b's quantile at a's CDF levels, - weight each cost by a's weights. - - loss = sum_i H(pos_a[i] - Q_b(CDF_a[i])) * w_a[i] - - Weight gradients: - - w_a multiplicative in sum → O(1) STRONG - - w_a → cumsum → cdf_a as query x of interp → O(1) via slope - Position gradients: - - pos_a direct in subtraction → O(1) STRONG - - pos_b in fp of interp → O(1) STRONG - """ - print("=" * 70) - print("TEST 9: Riemann-sum Wasserstein (weights multiply cost)") - print("=" * 70) - - from ott.tools import sliced - - key = jax.random.PRNGKey(42) - n = 500 - - pts_a = jax.random.uniform(key, (n, 2)) - pts_b = jax.random.uniform(jax.random.PRNGKey(1), (n, 2)) - base_wts_a = jax.random.uniform(jax.random.PRNGKey(2), (n,)) + 0.1 - wts_b = jax.random.uniform(jax.random.PRNGKey(3), (n,)) + 0.1 - - n_proj = 50 - delta = 0.01 - - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - - # ── Riemann-sum: weights enter multiplicatively ── - - def huber_riemann(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - sort_a = jnp.argsort(pa) - sort_b = jnp.argsort(pb) - - pos_a_sorted = pa[sort_a] - pos_b_sorted = pb[sort_b] - wts_a_sorted = wts_a[sort_a] - - cdf_a = jnp.cumsum(wts_a_sorted) - cdf_b = jnp.cumsum(wts_b[sort_b]) - - # b's quantile at a's CDF levels - Q_b = jnp.interp(cdf_a, cdf_b, pos_b_sorted) - - # Weighted Huber transport cost - diff = pos_a_sorted - Q_b - abs_diff = jnp.abs(diff) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.sum(huber * wts_a_sorted) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - # ── diff_q (reference) ── - - def huber_diff_q(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - i_a = jnp.argsort(pa) - i_b = jnp.argsort(pb) - sorted_a = pa[i_a] - sorted_b = pb[i_b] - - all_values = jnp.concatenate([sorted_a, sorted_b]) - all_sorter = jnp.argsort(all_values) - all_sorted = all_values[all_sorter] - - a_pdf = jnp.concatenate([wts_a[i_a], jnp.zeros(n)]) - a_pdf = a_pdf[all_sorter] - b_pdf = jnp.concatenate([jnp.zeros(n), wts_b[i_b]]) - b_pdf = b_pdf[all_sorter] - - a_cdf = jnp.cumsum(a_pdf) - b_cdf = jnp.cumsum(b_pdf) - - all_cdfs = jnp.concatenate([a_cdf, b_cdf]) - quantile_levels = jnp.sort(all_cdfs) - - i_a_inv = jnp.searchsorted(a_cdf, quantile_levels) - i_b_inv = jnp.searchsorted(b_cdf, quantile_levels) - qa = all_sorted[i_a_inv] - qb = all_sorted[i_b_inv] - - diff_q = jnp.diff(quantile_levels) - diff_pos = qa[1:] - qb[1:] - abs_diff = jnp.abs(diff_pos) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff_pos ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.sum(huber * diff_q) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - # ── Normalized quantile interp (old, broken for weights) ── - - grid = jnp.linspace(1e-6, 1.0 - 1e-6, 500) - - def huber_interp_norm(alpha): - wts_a = alpha * base_wts_a - wa = wts_a / jnp.sum(wts_a) - wb = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - sa = jnp.argsort(pa) - sb = jnp.argsort(pb) - cdf_a = jnp.cumsum(wa[sa]) - cdf_b = jnp.cumsum(wb[sb]) - qa = jnp.interp(grid, cdf_a, pa[sa]) - qb = jnp.interp(grid, cdf_b, pb[sb]) - diff = qa - qb - ad = jnp.abs(diff) - return jnp.mean(jnp.where(ad <= delta, 0.5 * diff**2, - delta * (ad - 0.5 * delta))) - return jnp.mean(jax.vmap(w1d)(proj_a.T, proj_b.T)) - - # ── OTT SW ── - - def ott_sw(alpha): - wts_a = alpha * base_wts_a - loss, _ = sliced.sliced_wasserstein( - x=pts_a, y=pts_b, a=wts_a, b=wts_b, - n_proj=n_proj, rng=key) - return loss - - eps = 1e-4 - - methods = [ - ("Riemann-sum (NEW)", huber_riemann), - ("diff_q (reference)", huber_diff_q), - ("Interp norm (OLD)", huber_interp_norm), - ("OTT SW", ott_sw), - ] - - # JIT warmup - for name, fn in methods: - _ = jax.grad(fn)(1.0) - - print(f"\n {'alpha':>6s} {'Method':>22s} {'Loss':>12s} {'AD grad':>12s} " - f"{'FD grad':>12s} {'AD/FD':>8s}") - print(f" {'-'*82}") - - for alpha in [0.5, 1.0, 1.5, 2.0]: - for name, fn in methods: - loss_val = float(fn(alpha)) - ad = float(jax.grad(fn)(alpha)) - fd = (float(fn(alpha + eps)) - float(fn(alpha - eps))) / (2 * eps) - ratio = ad / (fd + 1e-30) if abs(fd) > 1e-12 else float('inf') - print(f" {alpha:>6.1f} {name:>22s} {loss_val:>12.6e} " - f"{ad:>+12.6e} {fd:>+12.6e} {ratio:>8.3f}") - print() - - -# ============================================================================= -# Test 10: Position-space Wasserstein — interp(CDF in fp) + diff → integration weights -# ============================================================================= - -def test_posspace(): - """Position-space Wasserstein integral. - - W = ∫ H(x - T(x)) × f_a(x) dx - - where: - - f_a(x) = diff(F_a) where F_a = interp(pos_grid, pos_sorted, CDF) - → CDF in fp of interp → STRONG weight gradient - → diff preserves gradient (linear) - → multiplies cost → weight gradient via multiplication - - T(x) = Q_b(F_a(x)) = interp(SG(F_a), CDF_b, pos_b) - → stop_gradient decouples cost from weights (like searchsorted in diff_q) - - H(x - T(x)) = Huber spatial cost, no weight gradient through SG - - Key: uses interp with CDF in fp + diff to get strong weight gradients, - while computing the correct Wasserstein-Huber distance. - """ - print("=" * 70) - print("TEST 10: Position-space Wasserstein (interp fp + diff)") - print("=" * 70) - - from ott.tools import sliced - - key = jax.random.PRNGKey(42) - n = 500 - - pts_a = jax.random.uniform(key, (n, 2)) - pts_b = jax.random.uniform(jax.random.PRNGKey(1), (n, 2)) - base_wts_a = jax.random.uniform(jax.random.PRNGKey(2), (n,)) + 0.1 - wts_b = jax.random.uniform(jax.random.PRNGKey(3), (n,)) + 0.1 - - n_proj = 50 - n_grid = 500 - delta = 0.01 - - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - pos_grid = jnp.linspace(0.0, 1.0, n_grid) - - # ── Position-space with stop_gradient ── - - def huber_posspace_sg(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - sort_a = jnp.argsort(pa) - sort_b = jnp.argsort(pb) - - pos_a_sorted = pa[sort_a] - pos_b_sorted = pb[sort_b] - - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - - # CDF of a at position grid — weights in fp → STRONG gradient - F_a = jnp.interp(pos_grid, pos_a_sorted, cdf_a) - - # Transport map T(x) = Q_b(F_a(x)) - # stop_gradient on F_a: decouple cost from weights (like searchsorted) - T = jnp.interp(jax.lax.stop_gradient(F_a), cdf_b, pos_b_sorted) - - # Spatial Huber cost - diff_val = pos_grid - T - abs_diff = jnp.abs(diff_val) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff_val ** 2, - delta * (abs_diff - 0.5 * delta)) - - # Integration weight = mass of a per grid bin (via diff of CDF) - mass_a = jnp.diff(F_a) # (n_grid-1,) - - return jnp.sum(huber[:-1] * mass_a) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - # ── Position-space WITHOUT stop_gradient ── - - def huber_posspace_nosg(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - sort_a = jnp.argsort(pa) - sort_b = jnp.argsort(pb) - - pos_a_sorted = pa[sort_a] - pos_b_sorted = pb[sort_b] - - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - - F_a = jnp.interp(pos_grid, pos_a_sorted, cdf_a) - # NO stop_gradient — cost also carries weight gradient - T = jnp.interp(F_a, cdf_b, pos_b_sorted) - - diff_val = pos_grid - T - abs_diff = jnp.abs(diff_val) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff_val ** 2, - delta * (abs_diff - 0.5 * delta)) - - mass_a = jnp.diff(F_a) - return jnp.sum(huber[:-1] * mass_a) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - # ── diff_q (reference) ── - - def huber_diff_q(alpha): - wts_a = alpha * base_wts_a - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - i_a = jnp.argsort(pa) - i_b = jnp.argsort(pb) - sorted_a = pa[i_a] - sorted_b = pb[i_b] - - all_values = jnp.concatenate([sorted_a, sorted_b]) - all_sorter = jnp.argsort(all_values) - all_sorted = all_values[all_sorter] - - a_pdf = jnp.concatenate([wts_a[i_a], jnp.zeros(n)]) - a_pdf = a_pdf[all_sorter] - b_pdf = jnp.concatenate([jnp.zeros(n), wts_b[i_b]]) - b_pdf = b_pdf[all_sorter] - - a_cdf = jnp.cumsum(a_pdf) - b_cdf = jnp.cumsum(b_pdf) - - all_cdfs = jnp.concatenate([a_cdf, b_cdf]) - quantile_levels = jnp.sort(all_cdfs) - - i_a_inv = jnp.searchsorted(a_cdf, quantile_levels) - i_b_inv = jnp.searchsorted(b_cdf, quantile_levels) - qa = all_sorted[i_a_inv] - qb = all_sorted[i_b_inv] - - diff_q = jnp.diff(quantile_levels) - diff_pos = qa[1:] - qb[1:] - abs_diff = jnp.abs(diff_pos) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff_pos ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.sum(huber * diff_q) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - # ── Normalized quantile interp (old, broken) ── - - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - def huber_interp_norm(alpha): - wts_a = alpha * base_wts_a - wa = wts_a / jnp.sum(wts_a) - wb = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(pa, pb): - sa = jnp.argsort(pa) - sb = jnp.argsort(pb) - cdf_a = jnp.cumsum(wa[sa]) - cdf_b = jnp.cumsum(wb[sb]) - qa = jnp.interp(grid, cdf_a, pa[sa]) - qb = jnp.interp(grid, cdf_b, pb[sb]) - diff = qa - qb - ad = jnp.abs(diff) - return jnp.mean(jnp.where(ad <= delta, 0.5 * diff**2, - delta * (ad - 0.5 * delta))) - return jnp.mean(jax.vmap(w1d)(proj_a.T, proj_b.T)) - - # ── OTT SW ── - - def ott_sw(alpha): - wts_a = alpha * base_wts_a - loss, _ = sliced.sliced_wasserstein( - x=pts_a, y=pts_b, a=wts_a, b=wts_b, - n_proj=n_proj, rng=key) - return loss - - eps = 1e-4 - - methods = [ - ("Posspace+SG (NEW)", huber_posspace_sg), - ("Posspace noSG", huber_posspace_nosg), - ("diff_q (reference)", huber_diff_q), - ("Interp norm (OLD)", huber_interp_norm), - ("OTT SW", ott_sw), - ] - - # JIT warmup - for name, fn in methods: - _ = jax.grad(fn)(1.0) - - print(f"\n {'alpha':>6s} {'Method':>22s} {'Loss':>12s} {'AD grad':>12s} " - f"{'FD grad':>12s} {'AD/FD':>8s}") - print(f" {'-'*82}") - - for alpha in [0.5, 1.0, 1.5, 2.0]: - for name, fn in methods: - loss_val = float(fn(alpha)) - ad = float(jax.grad(fn)(alpha)) - fd = (float(fn(alpha + eps)) - float(fn(alpha - eps))) / (2 * eps) - ratio = ad / (fd + 1e-30) if abs(fd) > 1e-12 else float('inf') - print(f" {alpha:>6.1f} {name:>22s} {loss_val:>12.6e} " - f"{ad:>+12.6e} {fd:>+12.6e} {ratio:>8.3f}") - print() - - -# ============================================================================= - -if __name__ == '__main__': - test_posspace() - - print("=" * 70) - print("SUMMARY") - print("=" * 70) diff --git a/closure/archive/closure_analysis_original/closure_analysis/dE_distribution.png b/closure/archive/closure_analysis_original/closure_analysis/dE_distribution.png deleted file mode 100644 index d967eb3..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/dE_distribution.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/diagnostic_mcmc.py b/closure/archive/closure_analysis_original/closure_analysis/diagnostic_mcmc.py deleted file mode 100644 index f805ee2..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/diagnostic_mcmc.py +++ /dev/null @@ -1,242 +0,0 @@ -""" -Diagnostic script for MCMC closure optimizer. - -Checks magnitudes of signals, gradients, L1 drain, noise, and top-K -membership at the 0.5mm segment energy scale (0.05-0.20 MeV) with K=10000. - -Run from project root: - python3 closure_analysis/diagnostic_mcmc.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import optax - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit - -from closure_analysis.sgld_closure import ( - TRUTH_BANK, INIT_OFFSET, PLANES, K, N_PROJ, - LR_POSITION, LR_ENERGY_MULT, LR_L1, MIN_ENERGY, - B1, B2, NOISE_LR, TOTAL_STEPS, - build_loss_fn, -) - - -def section(title): - print(f"\n{'=' * 70}") - print(f" {title}") - print(f"{'=' * 70}") - - -def main(): - N_SEG = 5 - config = generate_detector('config/cubic_wireplane_config.yaml') - - truth_params = TRUTH_BANK[:N_SEG] - init_params = jnp.array(truth_params + INIT_OFFSET) - - print("Truth energies (MeV):", truth_params[:, 3]) - print("Init energies (MeV):", np.array(init_params[:, 3])) - - # ========================================================================= - section("1. SIGNAL MAGNITUDE — single segment at 0.10 MeV") - # ========================================================================= - - sim1 = DetectorSimulator(config, differentiable=True, n_segments=1) - fwd1 = sim1.build_forward() - - seg1 = SegmentData( - positions_mm=jnp.array([[-100.0, 50.0, 100.0]]), - de=jnp.array([0.10]), - ) - sigs1 = fwd1(seg1) - jax.block_until_ready(sigs1) - - for p in PLANES: - s = sigs1[p] - abs_s = jnp.abs(s) - nonzero = int((abs_s > 1e-10).sum()) - print(f" Plane {p}: shape={s.shape}, max={float(abs_s.max()):.6f}, " - f"mean(nonzero)={float(abs_s.sum()) / max(nonzero, 1):.6f}, " - f"nonzero_bins={nonzero}, total_bins={s.size}") - - # ========================================================================= - section("2. TOP-K MEMBERSHIP — 5 segments combined vs individual") - # ========================================================================= - - sim5 = DetectorSimulator(config, differentiable=True, n_segments=N_SEG) - fwd5 = sim5.build_forward() - - truth_seg = SegmentData( - positions_mm=jnp.array(truth_params[:, :3]), - de=jnp.array(truth_params[:, 3]), - ) - combined_sigs = fwd5(truth_seg) - jax.block_until_ready(combined_sigs) - - # Get top-K indices from combined signal - for p in PLANES: - comb = combined_sigs[p] - flat_comb = jnp.abs(comb.ravel()) - topk_vals, topk_idx = jax.lax.top_k(flat_comb, K) - topk_set = set(np.array(topk_idx)) - - min_topk_val = float(topk_vals[-1]) - print(f"\n Plane {p}: top-K threshold = {min_topk_val:.8f}") - - # Check each segment's individual signal - for s in range(N_SEG): - seg_s = SegmentData( - positions_mm=jnp.array(truth_params[s:s+1, :3]), - de=jnp.array(truth_params[s:s+1, 3]), - ) - sig_s = fwd1(seg_s) - flat_s = jnp.abs(sig_s[p].ravel()) - - # How many of this segment's nonzero bins are in the top-K? - nonzero_mask = flat_s > 1e-10 - nonzero_idx = np.where(np.array(nonzero_mask))[0] - in_topk = sum(1 for idx in nonzero_idx if idx in topk_set) - - # What fraction of this segment's signal energy is in top-K? - seg_vals_in_topk = float(flat_s[np.array(list(topk_set & set(nonzero_idx)))].sum()) \ - if len(topk_set & set(nonzero_idx)) > 0 else 0.0 - seg_total = float(flat_s.sum()) - frac = seg_vals_in_topk / seg_total if seg_total > 0 else 0.0 - - print(f" Seg {s} (dE={truth_params[s, 3]:.2f}): " - f"nonzero={len(nonzero_idx)}, in_topK={in_topk}/{len(nonzero_idx)}, " - f"signal_frac_in_topK={frac:.3f}") - - # ========================================================================= - section("3. GRADIENT MAGNITUDES at init") - # ========================================================================= - - # Build loss for 5 segments - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(combined_sigs[p], K) - target_clouds[p] = (pts, w) - - key = jax.random.PRNGKey(42) - loss_fn = build_loss_fn(fwd5, target_clouds, key) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - print("\n Warming up JIT...") - (loss0, _), grads0 = grad_fn(init_params) - print(f" Initial loss: {float(loss0):.6f}") - - print(f"\n {'Seg':>3s} {'|grad_pos|':>10s} {'|grad_x|':>10s} {'|grad_y|':>10s} " - f"{'|grad_z|':>10s} {'grad_dE':>10s}") - print(f" {'---':>3s} {'----------':>10s} {'----------':>10s} {'----------':>10s} " - f"{'----------':>10s} {'----------':>10s}") - for s in range(N_SEG): - gp = np.array(grads0[s, :3]) - ge = float(grads0[s, 3]) - print(f" {s:3d} {np.linalg.norm(gp):10.4f} {gp[0]:10.4f} {gp[1]:10.4f} " - f"{gp[2]:10.4f} {ge:10.4f}") - - # ========================================================================= - section("4. ADAM UPDATE vs DECOUPLED L1") - # ========================================================================= - - schedule = optax.cosine_decay_schedule( - init_value=LR_POSITION, decay_steps=TOTAL_STEPS, alpha=0.01) - optimizer = optax.adam(schedule, b1=B1, b2=B2) - opt_state = optimizer.init(init_params) - - # One Adam step - updates, _ = optimizer.update(grads0, opt_state, init_params) - updates_scaled = updates.at[:, 3].multiply(LR_ENERGY_MULT) - - print(f"\n After 1 Adam step:") - print(f" {'Seg':>3s} {'Adam_pos (mm)':>14s} {'Adam_dE (MeV)':>14s} " - f"{'L1_dE (MeV)':>12s} {'Ratio (Adam/L1)':>16s}") - print(f" {'---':>3s} {'--------------':>14s} {'--------------':>14s} " - f"{'------------':>12s} {'----------------':>16s}") - for s in range(N_SEG): - adam_pos = float(jnp.linalg.norm(updates_scaled[s, :3])) - adam_de = float(updates_scaled[s, 3]) - ratio = abs(adam_de) / LR_L1 if LR_L1 > 0 else float('inf') - print(f" {s:3d} {adam_pos:14.6f} {adam_de:14.6f} {-LR_L1:12.6f} {ratio:16.2f}") - - # ========================================================================= - section("5. NOISE MAGNITUDE at different steps") - # ========================================================================= - - for step in [0, 500, 1500, 2500, 2999]: - lr = float(schedule(step)) - noise_mag = lr * NOISE_LR - print(f" Step {step:4d}: lr={lr:.6f}, noise_std={noise_mag:.4f} mm " - f"(~{noise_mag / 3.0:.2f} wire pitches)") - - # ========================================================================= - section("6. L1 DRAIN TIMELINE") - # ========================================================================= - - print(f"\n LR_L1 = {LR_L1} MeV/step") - print(f" MIN_ENERGY = {MIN_ENERGY} MeV") - print(f" DEATH_THRESH = {MIN_ENERGY * 10:.3f} MeV") - for e0 in [0.05, 0.10, 0.15, 0.20]: - # Steps to reach death threshold (pure drain, no reconstruction gradient) - steps_to_death = max(0, (e0 - MIN_ENERGY * 10) / LR_L1) - print(f" dE={e0:.2f} MeV -> death in {steps_to_death:.0f} pure-drain steps " - f"({steps_to_death / 100:.1f} relocation intervals)") - - # ========================================================================= - section("7. SHORT OPTIMIZATION RUN (50 steps) — all modes") - # ========================================================================= - - for mode_label, apply_l1, apply_noise in [ - ("Adam only", False, False), - ("Adam + noise", False, True), - ("Adam + noise + L1", True, True), - ]: - print(f"\n --- {mode_label} ---") - params = init_params.copy() - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(99) - grad_ema = jnp.zeros(N_SEG) - - for step in range(50): - (loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(LR_ENERGY_MULT) - params = optax.apply_updates(params, updates) - - if apply_l1: - params = params.at[:, 3].add(-LR_L1) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], MIN_ENERGY)) - - if apply_noise: - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - nv = jax.random.normal(nk, shape=(N_SEG, 3)) - params = params.at[:, :3].add(lr_cur * NOISE_LR * nv) - - grad_pos_norm = jnp.linalg.norm(grads[:, :3], axis=-1) - grad_ema = 0.95 * grad_ema + 0.05 * grad_pos_norm - - if step % 10 == 0 or step == 49: - e_str = ", ".join(f"{float(params[i, 3]):.4f}" for i in range(N_SEG)) - g_str = ", ".join(f"{float(grad_ema[i]):.2f}" for i in range(N_SEG)) - print(f" Step {step:3d}: loss={float(loss):.6f} E=[{e_str}]") - if step % 20 == 0: - g_str_sci = ", ".join(f"{float(grad_ema[i]):.2e}" for i in range(N_SEG)) - print(f" grad_ema=[{g_str_sci}]") - - print(f"\n{'=' * 70}") - print(" Diagnostics complete.") - print(f"{'=' * 70}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_dE.png b/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_dE.png deleted file mode 100644 index 07757f4..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_dE.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_x.png b/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_x.png deleted file mode 100644 index f5f34e0..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_x.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_y.png b/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_y.png deleted file mode 100644 index fd81532..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_y.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_z.png b/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_z.png deleted file mode 100644 index b506b21..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_adaptive_surface_z.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_dE.png b/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_dE.png deleted file mode 100644 index 58243a4..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_dE.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_x.png b/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_x.png deleted file mode 100644 index 68272fc..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_x.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_y.png b/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_y.png deleted file mode 100644 index 82b2d4d..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_y.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_z.png b/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_z.png deleted file mode 100644 index 614a335..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_cdf_surface_z.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_closure.py b/closure/archive/closure_analysis_original/closure_analysis/huber_closure.py deleted file mode 100644 index 97e5c2f..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/huber_closure.py +++ /dev/null @@ -1,376 +0,0 @@ -""" -Closure test with Adam optimization using Huber SW + mass matching loss. - -Uses uniform-direction Huber sliced Wasserstein (normalized quantiles for -spatial term, mass ratio penalty for energy) summed over 3 east-side planes. - -Run from project root: - python3 closure_analysis/huber_closure.py N -where N is the number of segments (default 5). -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import optax -import time - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from closure_analysis.optimization_closure import ( - TRUTH_BANK, INIT_OFFSET, best_permutation, -) - -PLANES = [0, 1, 2] -K = 10000 -N_PROJ = 200 -N_GRID = 500 -DELTA = 0.01 -LAMBDA_MASS = 1e-4 - -LR = 0.3 -B1 = 0.95 -DE_SCALE = 1.0 -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -# ── Huber SW + mass matching kernel ───────────────────────────────────────── - -def make_huber_sw_mass(n_proj, delta, n_grid, lambda_mass): - """Huber uniform SW with normalized quantiles + mass matching. - - spatial = mean Huber(quantile_a - quantile_b) over projections - mass = (sum(wts_a)/sum(wts_b) - 1)^2 - loss = spatial + lambda_mass * mass - """ - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - total_a = jnp.sum(wts_a) - total_b = jnp.sum(wts_b) - wts_a_norm = wts_a / total_a - wts_b_norm = wts_b / total_b - - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - cdf_a = jnp.cumsum(wts_a_norm[sort_a]) - cdf_b = jnp.cumsum(wts_b_norm[sort_b]) - quant_a = jnp.interp(grid, cdf_a, proj_a_i[sort_a]) - quant_b = jnp.interp(grid, cdf_b, proj_b_i[sort_b]) - diff = quant_a - quant_b - abs_diff = jnp.abs(diff) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.mean(huber) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - spatial = jnp.mean(costs) - - mass_ratio = total_a / total_b - mass_term = (mass_ratio - 1.0) ** 2 - - return spatial + lambda_mass * mass_term - - return sw - - -# ── Loss builder ───────────────────────────────────────────────────────────── - -def build_huber_loss(forward, target_clouds, kernel): - """Build Huber SW loss: params (N,4) -> scalar, summed over 3 planes.""" - def loss_fn(params): - if params.ndim == 1: - seg = SegmentData(positions_mm=params[:3][None], de=params[3:4]) - else: - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + kernel(pts, w, target_clouds[p][0], target_clouds[p][1]) - return loss - return loss_fn - - -# ── Adam optimizer ─────────────────────────────────────────────────────────── - -def run_adam(loss_fn, init_params, lr, n_steps, b1=0.9, de_scale=1.0, - print_every=20): - schedule = optax.cosine_decay_schedule( - init_value=lr, decay_steps=n_steps, alpha=0.01) - optimizer = optax.adam(schedule, b1=b1) - params = init_params - opt_state = optimizer.init(params) - grad_fn = jax.value_and_grad(loss_fn) - - losses = [] - param_history = [] - - for step in range(n_steps): - loss, grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - if updates.ndim == 1: - updates = updates.at[3].multiply(de_scale) - else: - updates = updates.at[:, 3].multiply(de_scale) - params = optax.apply_updates(params, updates) - - loss_val = float(loss) - losses.append(loss_val) - param_history.append(np.array(params)) - - if step % print_every == 0 or step == n_steps - 1: - print(f" Step {step:4d}: loss = {loss_val:.8e}") - - return np.array(losses), np.array(param_history), params - - -# ── Plotting ───────────────────────────────────────────────────────────────── - -def _plot_closure(n_seg, losses, param_history, assignment, errors): - seg_colors = plt.cm.tab10(np.linspace(0, 1, max(n_seg, 3))) - - if n_seg <= 3: - _plot_per_component(n_seg, losses, param_history, assignment, seg_colors) - else: - _plot_total_error(n_seg, losses, param_history, assignment, seg_colors) - - -def _plot_per_component(n_seg, losses, param_history, assignment, seg_colors): - pos_labels = ['x', 'y', 'z'] - pos_colors = ['#1f77b4', '#ff7f0e', '#2ca02c'] - seg_de_colors = ['#d62728', '#9467bd', '#8c564b'] - - if n_seg == 1: - fig, axes = plt.subplots(1, 3, figsize=(16, 5)) - axes[0].semilogy(losses, 'b-', lw=1.2) - axes[0].set_xlabel('Step'); axes[0].set_ylabel('Huber SW Loss') - axes[0].set_title('Loss Convergence'); axes[0].grid(True, alpha=0.3) - - truth = assignment[0] - for i, (lbl, clr) in enumerate(zip(pos_labels, pos_colors)): - axes[1].plot(param_history[:, 0, i] - truth[i], color=clr, - lw=1.2, label=lbl) - axes[1].axhline(0, color='k', ls='--', lw=0.8) - axes[1].set_xlabel('Step'); axes[1].set_ylabel('Error (mm)') - axes[1].set_title('Position Errors') - axes[1].legend(); axes[1].grid(True, alpha=0.3) - - axes[2].plot((param_history[:, 0, 3] - truth[3]) * 1000, - color='#d62728', lw=1.2) - axes[2].axhline(0, color='k', ls='--', lw=0.8) - axes[2].set_xlabel('Step'); axes[2].set_ylabel('Error (keV)') - axes[2].set_title('Energy Error'); axes[2].grid(True, alpha=0.3) - - elif n_seg == 2: - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - axes[0, 0].semilogy(losses, 'b-', lw=1.2) - axes[0, 0].set_xlabel('Step'); axes[0, 0].set_ylabel('Huber SW Loss') - axes[0, 0].set_title('Loss Convergence'); axes[0, 0].grid(True, alpha=0.3) - - for s in range(2): - axes[0, 1].plot(param_history[:, s, 3] * 1000, - color=seg_de_colors[s], lw=1.2, label=f'Seg {s}') - axes[0, 1].axhline(assignment[s, 3] * 1000, - color=seg_de_colors[s], ls=':', lw=1.0, alpha=0.6) - axes[0, 1].set_xlabel('Step'); axes[0, 1].set_ylabel('dE (keV)') - axes[0, 1].set_title('Energy Trajectories (dotted = truth)') - axes[0, 1].legend(); axes[0, 1].grid(True, alpha=0.3) - - for s in range(2): - ax = axes[1, s] - for i, (lbl, clr) in enumerate(zip(pos_labels, pos_colors)): - ax.plot(param_history[:, s, i], color=clr, lw=1.2, label=lbl) - ax.axhline(assignment[s, i], color=clr, ls=':', lw=1.0, alpha=0.6) - ax.set_xlabel('Step'); ax.set_ylabel('Position (mm)') - ax.set_title(f'Segment {s} Positions (dotted = truth)') - ax.legend(); ax.grid(True, alpha=0.3) - - else: # n_seg == 3 - fig = plt.figure(figsize=(18, 10)) - gs = fig.add_gridspec(2, 3, hspace=0.3, wspace=0.3) - - ax_loss = fig.add_subplot(gs[0, 0]) - ax_loss.semilogy(losses, 'b-', lw=1.2) - ax_loss.set_xlabel('Step'); ax_loss.set_ylabel('Huber SW Loss') - ax_loss.set_title('Loss Convergence'); ax_loss.grid(True, alpha=0.3) - - ax_de = fig.add_subplot(gs[0, 1:]) - for s in range(3): - ax_de.plot(param_history[:, s, 3] * 1000, - color=seg_de_colors[s], lw=1.2, label=f'Seg {s}') - ax_de.axhline(assignment[s, 3] * 1000, color=seg_de_colors[s], - ls=':', lw=1.0, alpha=0.6) - ax_de.set_xlabel('Step'); ax_de.set_ylabel('dE (keV)') - ax_de.set_title('Energy Trajectories (dotted = truth)') - ax_de.legend(); ax_de.grid(True, alpha=0.3) - - for s in range(3): - ax = fig.add_subplot(gs[1, s]) - for i, (lbl, clr) in enumerate(zip(pos_labels, pos_colors)): - ax.plot(param_history[:, s, i], color=clr, lw=1.2, label=lbl) - ax.axhline(assignment[s, i], color=clr, ls=':', lw=1.0, alpha=0.6) - ax.set_xlabel('Step'); ax.set_ylabel('Position (mm)') - ax.set_title(f'Segment {s} Positions (dotted = truth)') - ax.legend(); ax.grid(True, alpha=0.3) - - fig.suptitle( - f'{n_seg}-Segment Huber SW Closure (Adam, lr={LR}, b1={B1}, ' - f'K={K}, n_proj={N_PROJ})', - fontsize=13, fontweight='bold') - if n_seg <= 2: - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'huber_closure_{n_seg}seg.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - -def _plot_total_error(n_seg, losses, param_history, assignment, seg_colors): - fig, axes = plt.subplots(1, 3, figsize=(18, 5)) - - axes[0].semilogy(losses, 'b-', lw=1.2) - axes[0].set_xlabel('Step'); axes[0].set_ylabel('Huber SW Loss') - axes[0].set_title('Loss Convergence'); axes[0].grid(True, alpha=0.3) - - for s in range(n_seg): - pos_err = np.sqrt(np.sum( - (param_history[:, s, :3] - assignment[s, :3]) ** 2, axis=1)) - axes[1].plot(pos_err, color=seg_colors[s], lw=1.2, label=f'Seg {s}') - axes[1].axhline(0, color='k', ls='--', lw=0.8) - axes[1].set_xlabel('Step'); axes[1].set_ylabel('||pos error|| (mm)') - axes[1].set_title('Position Error per Segment') - axes[1].legend(fontsize=7, ncol=2); axes[1].grid(True, alpha=0.3) - - for s in range(n_seg): - axes[2].plot(param_history[:, s, 3] * 1000, color=seg_colors[s], - lw=1.2, label=f'Seg {s}') - axes[2].axhline(assignment[s, 3] * 1000, color=seg_colors[s], - ls=':', lw=1.0, alpha=0.5) - axes[2].set_xlabel('Step'); axes[2].set_ylabel('dE (keV)') - axes[2].set_title('Energy Trajectories (dotted = truth)') - axes[2].legend(fontsize=7, ncol=2); axes[2].grid(True, alpha=0.3) - - fig.suptitle( - f'{n_seg}-Segment Huber SW Closure (Adam, lr={LR}, b1={B1}, ' - f'K={K}, n_proj={N_PROJ})', - fontsize=13, fontweight='bold') - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'huber_closure_{n_seg}seg.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - -# ── Main closure ───────────────────────────────────────────────────────────── - -def run_closure(n_seg): - assert n_seg <= len(TRUTH_BANK), f"Only {len(TRUTH_BANK)} truth segments defined" - - n_steps = 300 + 100 * (n_seg - 1) - print_every = max(20, n_steps // 15) - - print(f"\n{'=' * 70}") - print(f"{n_seg}-SEGMENT HUBER SW CLOSURE TEST") - print(f"{'=' * 70}") - print(f"Hyperparams: lr={LR}, b1={B1}, de_scale={DE_SCALE}, steps={n_steps}") - print(f"Loss: Huber SW + mass matching (K={K}, n_proj={N_PROJ}, " - f"n_grid={N_GRID}, delta={DELTA}, lambda_mass={LAMBDA_MASS})") - - truth_params = TRUTH_BANK[:n_seg] - init_params = jnp.array(truth_params + INIT_OFFSET) - - for i in range(n_seg): - print(f" Seg {i}: truth={truth_params[i]} init={np.array(init_params[i])}") - - print("Building simulator...") - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg) - forward = sim.build_forward() - - # Generate target signals and pointclouds - truth_seg = SegmentData( - positions_mm=jnp.array(truth_params[:, :3]), - de=jnp.array(truth_params[:, 3]), - ) - target_signals = forward(truth_seg) - - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_clouds[p] = (pts, w) - - kernel = make_huber_sw_mass(N_PROJ, DELTA, N_GRID, LAMBDA_MASS) - loss_fn = build_huber_loss(forward, target_clouds, kernel) - - if n_seg == 1: - init_flat = init_params[0] # (4,) - else: - init_flat = init_params # (N, 4) - - # Warm up JIT - print("Warming up JIT...") - t0 = time.time() - _ = loss_fn(init_flat) - jax.block_until_ready(_) - t1 = time.time() - _ = jax.grad(loss_fn)(init_flat) - jax.block_until_ready(_) - t2 = time.time() - print(f"JIT warm-up done: forward={t1-t0:.1f}s, grad={t2-t1:.1f}s") - - # Optimize - print(f"\nOptimizing ({n_steps} steps)...") - t0 = time.time() - losses, param_history, final_params = run_adam( - loss_fn, init_flat, lr=LR, n_steps=n_steps, b1=B1, de_scale=DE_SCALE, - print_every=print_every, - ) - opt_time = time.time() - t0 - print(f"Optimization done in {opt_time:.1f}s ({opt_time/n_steps*1000:.0f} ms/step)") - - final = np.array(final_params) - if n_seg == 1: - final_2d = final[None, :] - param_history_3d = param_history[:, None, :] - else: - final_2d = final - param_history_3d = param_history - - # Match segments to truth - assignment, errors = best_permutation(final_2d, truth_params) - - print(f"\nResults:") - for i in range(n_seg): - e = errors[i] - print(f" Seg {i}: x={e[0]:+.3f} mm, y={e[1]:+.3f} mm, " - f"z={e[2]:+.3f} mm, dE={e[3]*1000:+.1f} keV") - max_pos = np.max(np.abs(errors[:, :3])) - max_de = np.max(np.abs(errors[:, 3])) * 1000 - mean_pos = np.mean(np.sqrt(np.sum(errors[:, :3] ** 2, axis=1))) - print(f" Max position error: {max_pos:.3f} mm") - print(f" Mean position error: {mean_pos:.3f} mm") - print(f" Max dE error: {max_de:.1f} keV") - - _plot_closure(n_seg, losses, param_history_3d, assignment, errors) - - return errors - - -if __name__ == '__main__': - n = int(sys.argv[1]) if len(sys.argv) > 1 else 5 - run_closure(n) diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_closure_5seg.png b/closure/archive/closure_analysis_original/closure_analysis/huber_closure_5seg.png deleted file mode 100644 index 73bc190..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_closure_5seg.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_dE.png b/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_dE.png deleted file mode 100644 index 21d7741..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_dE.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_x.png b/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_x.png deleted file mode 100644 index 0eb2fef..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_x.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_y.png b/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_y.png deleted file mode 100644 index f18bad5..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_y.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_z.png b/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_z.png deleted file mode 100644 index 9790fcd..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_posspace_surface_z.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_dE.png b/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_dE.png deleted file mode 100644 index df084f8..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_dE.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_x.png b/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_x.png deleted file mode 100644 index f83289a..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_x.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_y.png b/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_y.png deleted file mode 100644 index 5d06a91..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_y.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_z.png b/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_z.png deleted file mode 100644 index 4e3b665..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_riemann_surface_z.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_surface_dE.png b/closure/archive/closure_analysis_original/closure_analysis/huber_surface_dE.png deleted file mode 100644 index c658242..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_surface_dE.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_surface_x.png b/closure/archive/closure_analysis_original/closure_analysis/huber_surface_x.png deleted file mode 100644 index 509016e..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_surface_x.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_surface_y.png b/closure/archive/closure_analysis_original/closure_analysis/huber_surface_y.png deleted file mode 100644 index ecbaa99..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_surface_y.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/huber_surface_z.png b/closure/archive/closure_analysis_original/closure_analysis/huber_surface_z.png deleted file mode 100644 index d8ca745..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/huber_surface_z.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces.py b/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces.py deleted file mode 100644 index 142e519..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces.py +++ /dev/null @@ -1,219 +0,0 @@ -""" -Plot loss and gradient surfaces for MSE and SW losses separately, -varying x, y, z, and dE independently. Loss is summed across all active planes. - -Generates 8 figures: - - mse_surface_{x,y,z,dE}.png - - sw_surface_{x,y,z,dE}.png - -Run from project root: - python3 closure_analysis/loss_gradient_surfaces.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit - -# East side planes: U=0, V=1, Y=2 -PLANES = [0, 1, 2] -K = 1000 -N_PROJ = 200 - -print("Loading detector config...") -detector_config = generate_detector('config/cubic_wireplane_config.yaml') -sim = DetectorSimulator(detector_config, differentiable=True, n_segments=1) -forward = sim.build_forward() - -truth_pos = np.array([-100.0, 50.0, 100.0]) -truth_de = 1.0 -truth_seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([truth_de])) -target_signals = forward(truth_seg) -key = jax.random.PRNGKey(42) - -# Pre-compute targets for each plane -target_planes = {} -for p in PLANES: - sig = target_signals[p] - pts, w = signal_to_pointcloud(sig, K) - target_planes[p] = (sig, pts, w) - -out_dir = os.path.dirname(os.path.abspath(__file__)) - -# ── Sweep ranges for each axis ─────────────────────────────────────────────── -sweep_configs = { - 'x': {'idx': 0, 'range': (-195, -5), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'y': {'idx': 1, 'range': (-150, 250), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'z': {'idx': 2, 'range': (-100, 300), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'dE': {'idx': -1, 'range': (0.1, 3.0), 'n': 80, 'truth': 1.0, 'unit': 'MeV'}, -} - -FD_EPS = 0.05 # for position axes (mm) -FD_EPS_DE = 0.005 # for dE (MeV) - - -def make_loss_fns(axis_name, axis_idx): - """Build MSE and SW loss functions that vary one parameter, summed over all planes.""" - - if axis_name == 'dE': - def mse_loss(val): - seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([val])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - loss = loss + jnp.mean((sigs[p] - target_planes[p][0]) ** 2) - return loss - - def sw_loss(val): - seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([val])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + sliced_wasserstein_loss_jit( - pts, w, target_planes[p][1], target_planes[p][2], - key, n_projections=N_PROJ - ) - return loss - else: - def mse_loss(val): - pos = jnp.array([truth_pos]).at[0, axis_idx].set(val) - seg = SegmentData(positions_mm=pos, de=jnp.array([truth_de])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - loss = loss + jnp.mean((sigs[p] - target_planes[p][0]) ** 2) - return loss - - def sw_loss(val): - pos = jnp.array([truth_pos]).at[0, axis_idx].set(val) - seg = SegmentData(positions_mm=pos, de=jnp.array([truth_de])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + sliced_wasserstein_loss_jit( - pts, w, target_planes[p][1], target_planes[p][2], - key, n_projections=N_PROJ - ) - return loss - - return mse_loss, sw_loss - - -# ── Warm up JIT ────────────────────────────────────────────────────────────── -print("Warming up JIT...") -for axis_name, cfg in sweep_configs.items(): - mse_fn, sw_fn = make_loss_fns(axis_name, cfg['idx']) - test_val = cfg['truth'] if cfg['truth'] is not None else truth_pos[cfg['idx']] - _ = mse_fn(test_val) - _ = jax.grad(mse_fn)(test_val) - _ = sw_fn(test_val) - _ = jax.grad(sw_fn)(test_val) -print("Ready.\n") - -# ── Generate plots for each axis ───────────────────────────────────────────── - -for axis_name, cfg in sweep_configs.items(): - axis_idx = cfg['idx'] - lo, hi = cfg['range'] - n = cfg['n'] - unit = cfg['unit'] - truth_val = cfg['truth'] if cfg['truth'] is not None else truth_pos[axis_idx] - eps = FD_EPS_DE if axis_name == 'dE' else FD_EPS - - mse_fn, sw_fn = make_loss_fns(axis_name, axis_idx) - mse_grad_fn = jax.grad(mse_fn) - sw_grad_fn = jax.grad(sw_fn) - - x_vals = np.linspace(lo, hi, n) - truth_label = f'Truth {axis_name}={truth_val:.1f}' - - print(f"--- {axis_name} (truth={truth_val}) ---") - - print(f" Computing MSE losses...") - mse_losses = np.array([float(mse_fn(float(v))) for v in x_vals]) - print(f" Computing MSE autodiff gradients...") - mse_ad_grads = np.array([float(mse_grad_fn(float(v))) for v in x_vals]) - print(f" Computing MSE finite-diff gradients...") - mse_fd_grads = np.array([ - (float(mse_fn(float(v + eps))) - float(mse_fn(float(v - eps)))) / (2 * eps) - for v in x_vals - ]) - - print(f" Computing SW losses...") - sw_losses = np.array([float(sw_fn(float(v))) for v in x_vals]) - print(f" Computing SW autodiff gradients...") - sw_ad_grads = np.array([float(sw_grad_fn(float(v))) for v in x_vals]) - print(f" Computing SW finite-diff gradients...") - sw_fd_grads = np.array([ - (float(sw_fn(float(v + eps))) - float(sw_fn(float(v - eps)))) / (2 * eps) - for v in x_vals - ]) - - # ── MSE figure (loss + gradient, 1x2) ──────────────────────────────── - fig, axes = plt.subplots(1, 2, figsize=(12, 5)) - - axes[0].plot(x_vals, mse_losses, 'b-', lw=1.5) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, label=truth_label) - axes[0].set_xlabel(f'{axis_name} ({unit})') - axes[0].set_ylabel('MSE Loss') - axes[0].set_title('Loss Landscape') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - - axes[1].plot(x_vals, mse_ad_grads, 'r-', lw=1.5, label='Autodiff') - axes[1].plot(x_vals, mse_fd_grads, 'b--', lw=1.5, alpha=0.7, label=f'FD (eps={eps})') - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, label=truth_label) - axes[1].set_xlabel(f'{axis_name} ({unit})') - axes[1].set_ylabel(f'dMSE/d{axis_name}') - axes[1].set_title('Gradient (Autodiff vs FD)') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - - fig.suptitle(f'MSE — varying {axis_name} (summed over U+V+Y planes)', fontsize=14, fontweight='bold') - fig.tight_layout() - fname = f'mse_surface_{axis_name}.png' - fig.savefig(os.path.join(out_dir, fname), dpi=150) - plt.close(fig) - print(f" Saved {fname}") - - # ── SW figure (loss + gradient, 1x2) ───────────────────────────────── - fig, axes = plt.subplots(1, 2, figsize=(12, 5)) - - axes[0].plot(x_vals, sw_losses, 'b-', lw=1.5) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, label=truth_label) - axes[0].set_xlabel(f'{axis_name} ({unit})') - axes[0].set_ylabel('SW Loss') - axes[0].set_title('Loss Landscape') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - - axes[1].plot(x_vals, sw_ad_grads, 'r-', lw=1.5, label='Autodiff') - axes[1].plot(x_vals, sw_fd_grads, 'b--', lw=1.5, alpha=0.7, label=f'FD (eps={eps})') - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, label=truth_label) - axes[1].set_xlabel(f'{axis_name} ({unit})') - axes[1].set_ylabel(f'dSW/d{axis_name}') - axes[1].set_title('Gradient (Autodiff vs FD)') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - - fig.suptitle(f'Sliced Wasserstein — varying {axis_name} (summed over U+V+Y planes)', fontsize=14, fontweight='bold') - fig.tight_layout() - fname = f'sw_surface_{axis_name}.png' - fig.savefig(os.path.join(out_dir, fname), dpi=150) - plt.close(fig) - print(f" Saved {fname}") - -print("\nDone!") diff --git a/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_huber.py b/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_huber.py deleted file mode 100644 index b8bd843..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_huber.py +++ /dev/null @@ -1,215 +0,0 @@ -""" -Plot loss and gradient surfaces for Huber uniform SW + mass matching term, -varying x, y, z, and dE independently. Loss is summed across all active planes. - -Approach: - - Spatial term: normalized quantile Huber SW (proven autodiff for positions) - - Mass term: (sum(wts_a)/sum(wts_b) - 1)^2 (dE sensitivity) - - Combined: spatial + lambda_mass * mass_term - -Generates 4 figures: huber_surface_{x,y,z,dE}.png - -Run from project root: - python3 closure_analysis/loss_gradient_surfaces_huber.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud - -PLANES = [0, 1, 2] -K = 25000 -N_PROJ = 500 -N_GRID = 2000 -DELTA = 0.01 -LAMBDA_MASS = 1e-4 # mass matching coefficient - - -def make_huber_sw_mass(n_proj, delta, n_grid, lambda_mass): - """Huber uniform SW with normalized quantiles + mass matching. - - spatial = mean Huber(quantile_a - quantile_b) over projections - mass = (sum(wts_a)/sum(wts_b) - 1)^2 - loss = spatial + lambda_mass * mass - """ - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - # Normalize weights for quantile computation - total_a = jnp.sum(wts_a) - total_b = jnp.sum(wts_b) - wts_a_norm = wts_a / total_a - wts_b_norm = wts_b / total_b - - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - cdf_a = jnp.cumsum(wts_a_norm[sort_a]) - cdf_b = jnp.cumsum(wts_b_norm[sort_b]) - quant_a = jnp.interp(grid, cdf_a, proj_a_i[sort_a]) - quant_b = jnp.interp(grid, cdf_b, proj_b_i[sort_b]) - diff = quant_a - quant_b - abs_diff = jnp.abs(diff) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.mean(huber) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - spatial = jnp.mean(costs) - - # Mass matching: penalize total weight mismatch - mass_ratio = total_a / total_b - mass_term = (mass_ratio - 1.0) ** 2 - - return spatial + lambda_mass * mass_term - - return sw - - -# ── Setup ──────────────────────────────────────────────────────────────────── - -print("Loading detector config...") -detector_config = generate_detector('config/cubic_wireplane_config.yaml') -sim = DetectorSimulator(detector_config, differentiable=True, n_segments=1) -forward = sim.build_forward() - -truth_pos = np.array([-100.0, 50.0, 100.0]) -truth_de = 1.0 -truth_seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([truth_de])) -target_signals = forward(truth_seg) - -target_planes = {} -for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_planes[p] = (pts, w) - -out_dir = os.path.dirname(os.path.abspath(__file__)) -kernel = make_huber_sw_mass(N_PROJ, DELTA, N_GRID, LAMBDA_MASS) - -sweep_configs = { - 'x': {'idx': 0, 'range': (-195, -5), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'y': {'idx': 1, 'range': (-150, 250), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'z': {'idx': 2, 'range': (-100, 300), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'dE': {'idx': -1, 'range': (0.1, 3.0), 'n': 80, 'truth': 1.0, 'unit': 'MeV'}, -} - -FD_EPS = 0.05 -FD_EPS_DE = 0.005 - - -def make_loss_fn(axis_name, axis_idx): - if axis_name == 'dE': - def loss_fn(val): - seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([val])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + kernel(pts, w, target_planes[p][0], target_planes[p][1]) - return loss - else: - def loss_fn(val): - pos = jnp.array([truth_pos]).at[0, axis_idx].set(val) - seg = SegmentData(positions_mm=pos, de=jnp.array([truth_de])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + kernel(pts, w, target_planes[p][0], target_planes[p][1]) - return loss - return loss_fn - - -# ── Warm up JIT ────────────────────────────────────────────────────────────── - -print(f"Params: K={K}, n_proj={N_PROJ}, n_grid={N_GRID}, delta={DELTA}, " - f"lambda_mass={LAMBDA_MASS}") -print("Warming up JIT...") -for axis_name, cfg in sweep_configs.items(): - fn = make_loss_fn(axis_name, cfg['idx']) - test_val = cfg['truth'] if cfg['truth'] is not None else truth_pos[cfg['idx']] - t0 = time.time() - _ = fn(test_val) - _ = jax.grad(fn)(test_val) - print(f" {axis_name}: {time.time()-t0:.1f}s") -print("Ready.\n") - - -# ── Generate plots ─────────────────────────────────────────────────────────── - -for axis_name, cfg in sweep_configs.items(): - axis_idx = cfg['idx'] - lo, hi = cfg['range'] - n = cfg['n'] - unit = cfg['unit'] - truth_val = cfg['truth'] if cfg['truth'] is not None else truth_pos[axis_idx] - eps = FD_EPS_DE if axis_name == 'dE' else FD_EPS - x_vals = np.linspace(lo, hi, n) - - loss_fn = make_loss_fn(axis_name, axis_idx) - grad_fn = jax.grad(loss_fn) - - t0 = time.time() - print(f"--- {axis_name} (truth={truth_val}) ---") - - print(f" Computing losses...") - losses = np.array([float(loss_fn(float(v))) for v in x_vals]) - print(f" Computing autodiff gradients...") - ad_grads = np.array([float(grad_fn(float(v))) for v in x_vals]) - print(f" Computing finite-diff gradients...") - fd_grads = np.array([ - (float(loss_fn(float(v + eps))) - float(loss_fn(float(v - eps)))) / (2 * eps) - for v in x_vals - ]) - - fig, axes = plt.subplots(1, 2, figsize=(12, 5)) - - axes[0].plot(x_vals, losses, '-', color='#27ae60', lw=1.5) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth {axis_name}={truth_val:.1f}') - axes[0].set_xlabel(f'{axis_name} ({unit})') - axes[0].set_ylabel('Loss') - axes[0].set_title('Loss Landscape') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - - axes[1].plot(x_vals, ad_grads, '-', color='red', lw=1.5, label='Autodiff') - axes[1].plot(x_vals, fd_grads, '--', color='blue', lw=1.5, alpha=0.7, - label=f'FD (eps={eps})') - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth {axis_name}={truth_val:.1f}') - axes[1].set_xlabel(f'{axis_name} ({unit})') - axes[1].set_ylabel(f'd(Loss)/d{axis_name}') - axes[1].set_title('Gradient (Autodiff vs FD)') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - - fig.suptitle( - f'Huber SW + mass — varying {axis_name} | K={K}, n_proj={N_PROJ}, ' - f'n_grid={N_GRID}, λ_m={LAMBDA_MASS}', - fontsize=12, fontweight='bold') - fig.tight_layout() - fname = f'huber_surface_{axis_name}.png' - fig.savefig(os.path.join(out_dir, fname), dpi=150) - plt.close(fig) - print(f" {time.time()-t0:.0f}s → {fname}") - -print("\nDone!") diff --git a/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_huber_adaptive.py b/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_huber_adaptive.py deleted file mode 100644 index ad0d9b5..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_huber_adaptive.py +++ /dev/null @@ -1,224 +0,0 @@ -""" -Plot loss and gradient surfaces for position-space Huber sliced distance. - -Position-space Wasserstein integral: - W = ∫ H(x - T(x)) × f_a(x) dx - -where: - - F_a = interp(pos_grid, pos_sorted, CDF) — CDF in fp → strong weight gradient - - T(x) = Q_b(F_a(x)) = interp(F_a, CDF_b, pos_b) — F_a as query x - - f_a × dx = diff(F_a) — mass per grid bin, gradient through diff(interp fp) - - H(x - T(x)) — Huber spatial cost - -Weight gradients flow through two chained interps: fp → F_a → query x → T. -No normalization, no mass matching term, no stop_gradient needed. - -Generates 4 figures: huber_posspace_surface_{x,y,z,dE}.png - -Run from project root: - python3 closure_analysis/loss_gradient_surfaces_huber_adaptive.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud - -PLANES = [0, 1, 2] -K = 25000 -N_PROJ = 500 -N_GRID = 2000 -DELTA = 0.01 # Position-space Huber threshold - - -def make_huber_posspace(n_proj, delta, n_grid): - """Position-space Huber sliced Wasserstein. - - Uses two chained interps: - 1. CDF interp: interp(pos_grid, pos_sorted, CDF) — CDF in fp (strong weight grad) - 2. Transport interp: interp(F_a, CDF_b, pos_b) — F_a as query x (carries weight grad) - - Integration weights from diff(F_a) = mass of a per grid bin. - """ - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - pos_grid = jnp.linspace(0.0, 1.0, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - - pos_a_sorted = proj_a_i[sort_a] - pos_b_sorted = proj_b_i[sort_b] - - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - - # Step 1: CDF of a at position grid (weights in fp → STRONG gradient) - F_a = jnp.interp(pos_grid, pos_a_sorted, cdf_a) - - # Step 2: Transport map T(x) = Q_b(F_a(x)) - # F_a carries weight gradient from step 1 → flows through query x - T = jnp.interp(F_a, cdf_b, pos_b_sorted) - - # Step 3: Spatial Huber cost - diff_val = pos_grid - T - abs_diff = jnp.abs(diff_val) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff_val ** 2, - delta * (abs_diff - 0.5 * delta)) - - # Step 4: Integration weight = mass of a per grid bin (via diff) - mass_a = jnp.diff(F_a) # (n_grid-1,) - - return jnp.sum(huber[:-1] * mass_a) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - return sw - - -# ── Setup ──────────────────────────────────────────────────────────────────── - -print("Loading detector config...") -detector_config = generate_detector('config/cubic_wireplane_config.yaml') -sim = DetectorSimulator(detector_config, differentiable=True, n_segments=1) -forward = sim.build_forward() - -truth_pos = np.array([-100.0, 50.0, 100.0]) -truth_de = 1.0 -truth_seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([truth_de])) -target_signals = forward(truth_seg) - -target_planes = {} -for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_planes[p] = (pts, w) - -out_dir = os.path.dirname(os.path.abspath(__file__)) -kernel = make_huber_posspace(N_PROJ, DELTA, N_GRID) - -sweep_configs = { - 'x': {'idx': 0, 'range': (-195, -5), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'y': {'idx': 1, 'range': (-150, 250), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'z': {'idx': 2, 'range': (-100, 300), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'dE': {'idx': -1, 'range': (0.1, 3.0), 'n': 80, 'truth': 1.0, 'unit': 'MeV'}, -} - -FD_EPS = 0.05 -FD_EPS_DE = 0.005 - - -def make_loss_fn(axis_name, axis_idx): - if axis_name == 'dE': - def loss_fn(val): - seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([val])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + kernel(pts, w, target_planes[p][0], target_planes[p][1]) - return loss - else: - def loss_fn(val): - pos = jnp.array([truth_pos]).at[0, axis_idx].set(val) - seg = SegmentData(positions_mm=pos, de=jnp.array([truth_de])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + kernel(pts, w, target_planes[p][0], target_planes[p][1]) - return loss - return loss_fn - - -# ── Warm up JIT ────────────────────────────────────────────────────────────── - -print(f"Params: K={K}, n_proj={N_PROJ}, n_grid={N_GRID}, delta={DELTA}") -print("Warming up JIT...") -for axis_name, cfg in sweep_configs.items(): - fn = make_loss_fn(axis_name, cfg['idx']) - test_val = cfg['truth'] if cfg['truth'] is not None else truth_pos[cfg['idx']] - t0 = time.time() - _ = fn(test_val) - _ = jax.grad(fn)(test_val) - print(f" {axis_name}: {time.time()-t0:.1f}s") -print("Ready.\n") - - -# ── Generate plots ─────────────────────────────────────────────────────────── - -for axis_name, cfg in sweep_configs.items(): - axis_idx = cfg['idx'] - lo, hi = cfg['range'] - n = cfg['n'] - unit = cfg['unit'] - truth_val = cfg['truth'] if cfg['truth'] is not None else truth_pos[axis_idx] - eps = FD_EPS_DE if axis_name == 'dE' else FD_EPS - x_vals = np.linspace(lo, hi, n) - - loss_fn = make_loss_fn(axis_name, axis_idx) - grad_fn = jax.grad(loss_fn) - - t0 = time.time() - print(f"--- {axis_name} (truth={truth_val}) ---") - - print(f" Computing losses...") - losses = np.array([float(loss_fn(float(v))) for v in x_vals]) - print(f" Computing autodiff gradients...") - ad_grads = np.array([float(grad_fn(float(v))) for v in x_vals]) - print(f" Computing finite-diff gradients...") - fd_grads = np.array([ - (float(loss_fn(float(v + eps))) - float(loss_fn(float(v - eps)))) / (2 * eps) - for v in x_vals - ]) - - fig, axes = plt.subplots(1, 2, figsize=(12, 5)) - - axes[0].plot(x_vals, losses, '-', color='#27ae60', lw=1.5) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth {axis_name}={truth_val:.1f}') - axes[0].set_xlabel(f'{axis_name} ({unit})') - axes[0].set_ylabel('Loss') - axes[0].set_title('Loss Landscape') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - - axes[1].plot(x_vals, ad_grads, '-', color='red', lw=1.5, label='Autodiff') - axes[1].plot(x_vals, fd_grads, '--', color='blue', lw=1.5, alpha=0.7, - label=f'FD (eps={eps})') - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth {axis_name}={truth_val:.1f}') - axes[1].set_xlabel(f'{axis_name} ({unit})') - axes[1].set_ylabel(f'd(Loss)/d{axis_name}') - axes[1].set_title('Gradient (Autodiff vs FD)') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - - fig.suptitle( - f'Position-Space Huber Sliced \u2014 varying {axis_name} | K={K}, ' - f'n_proj={N_PROJ}, n_grid={N_GRID}, \u03b4={DELTA}', - fontsize=12, fontweight='bold') - fig.tight_layout() - fname = f'huber_posspace_surface_{axis_name}.png' - fig.savefig(os.path.join(out_dir, fname), dpi=150) - plt.close(fig) - print(f" {time.time()-t0:.0f}s \u2192 {fname}") - -print("\nDone!") diff --git a/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_huber_dense.py b/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_huber_dense.py deleted file mode 100644 index 8813dec..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_huber_dense.py +++ /dev/null @@ -1,263 +0,0 @@ -""" -Plot loss and gradient surfaces for dense Huber SW (full image, no top-K). - -Every pixel in the (W, T) signal is treated as a point. For each projection -direction, all W*T points are sorted and used for CDF/quantile/Huber. - -This tests how slow the full-image approach is vs the sparse top-K approach. - -Generates 4 figures: huber_dense_surface_{x,y,z,dE}.png - -Run from project root: - python3 closure_analysis/loss_gradient_surfaces_huber_dense.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator - -PLANES = [0, 1, 2] -N_PROJ = 10 -N_GRID = 2000 -DELTA = 0.01 -LAMBDA_MASS = 1e-4 - - -def make_huber_sw_dense(signal_shape, n_proj, delta, n_grid, lambda_mass, - mm_per_wire=3.0, mm_per_tick=0.8): - """Huber SW on full (W, T) signals — no top-K, every pixel is a point. - - Pre-computes pixel positions (fixed grid). At runtime: project, sort, - CDF, quantile, Huber. Uses lax.map over projections to control memory. - """ - W, T = signal_shape - n_pixels = W * T - max_extent = max(W * mm_per_wire, T * mm_per_tick) - - # Pre-compute all pixel positions: (W*T, 2) normalized - wire_idx = jnp.arange(W, dtype=jnp.float32) - time_idx = jnp.arange(T, dtype=jnp.float32) - # (W, T) meshgrid → flatten to (W*T,) - wire_flat = jnp.repeat(wire_idx, T) * mm_per_wire / max_extent - time_flat = jnp.tile(time_idx, W) * mm_per_tick / max_extent - positions = jnp.stack([wire_flat, time_flat], axis=-1) # (W*T, 2) - - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) # (n_proj, 2) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - # Pre-compute projections and sort orders (static — don't depend on signal) - # proj_all: (n_proj, W*T) - proj_all = positions @ directions.T # (W*T, n_proj) → transpose below - - print(f" Dense kernel: {W}x{T} = {n_pixels:,} pixels, " - f"n_proj={n_proj}, positions={positions.shape}") - - # Pre-compute sort permutations for each direction (expensive but one-time) - print(f" Pre-computing {n_proj} sort permutations of {n_pixels:,} elements...") - t0 = time.time() - # Sort each direction's projections - sort_perms = jnp.argsort(proj_all, axis=0) # (W*T, n_proj) - sort along pixel axis - sorted_positions = jnp.take_along_axis(proj_all, sort_perms, axis=0) # (W*T, n_proj) - print(f" Sort pre-computation done in {time.time()-t0:.1f}s") - - @jax.jit - def sw(signal_a, signal_b): - abs_a = jnp.abs(signal_a).ravel() # (W*T,) - abs_b = jnp.abs(signal_b).ravel() - total_a = jnp.sum(abs_a) - total_b = jnp.sum(abs_b) - - def compute_one(d_idx): - perm = sort_perms[:, d_idx] # (W*T,) - sorted_pos = sorted_positions[:, d_idx] # (W*T,) - - sorted_wts_a = abs_a[perm] - sorted_wts_b = abs_b[perm] - - cdf_a = jnp.cumsum(sorted_wts_a) / (total_a + 1e-10) - cdf_b = jnp.cumsum(sorted_wts_b) / (total_b + 1e-10) - - quant_a = jnp.interp(grid, cdf_a, sorted_pos) - quant_b = jnp.interp(grid, cdf_b, sorted_pos) - - diff = quant_a - quant_b - abs_diff = jnp.abs(diff) - return jnp.mean(jnp.where(abs_diff <= delta, - 0.5 * diff ** 2, - delta * (abs_diff - 0.5 * delta))) - - costs = jax.vmap(compute_one)(jnp.arange(n_proj)) - spatial = jnp.mean(costs) - - mass_ratio = total_a / (total_b + 1e-10) - mass_term = (mass_ratio - 1.0) ** 2 - - return spatial + lambda_mass * mass_term - - return sw - - -# ── Setup ──────────────────────────────────────────────────────────────────── - -print("Loading detector config...") -detector_config = generate_detector('config/cubic_wireplane_config.yaml') -sim = DetectorSimulator(detector_config, differentiable=True, n_segments=1) -forward = sim.build_forward() - -truth_pos = np.array([-100.0, 50.0, 100.0]) -truth_de = 1.0 -truth_seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([truth_de])) -target_signals = forward(truth_seg) - -# Check signal shapes per plane -for p in PLANES: - print(f" Plane {p}: signal shape = {target_signals[p].shape}") - -# Build dense kernels per plane (shapes may differ) -kernels = {} -for p in PLANES: - shape = target_signals[p].shape - print(f" Building dense kernel for plane {p} ({shape})...") - kernels[p] = make_huber_sw_dense(shape, N_PROJ, DELTA, N_GRID, LAMBDA_MASS) - -out_dir = os.path.dirname(os.path.abspath(__file__)) - -sweep_configs = { - 'x': {'idx': 0, 'range': (-195, -5), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'y': {'idx': 1, 'range': (-150, 250), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'z': {'idx': 2, 'range': (-100, 300), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'dE': {'idx': -1, 'range': (0.1, 3.0), 'n': 80, 'truth': 1.0, 'unit': 'MeV'}, -} - -FD_EPS = 0.05 -FD_EPS_DE = 0.005 - - -def make_loss_fn(axis_name, axis_idx): - if axis_name == 'dE': - def loss_fn(val): - seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([val])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - loss = loss + kernels[p](sigs[p], target_signals[p]) - return loss - else: - def loss_fn(val): - pos = jnp.array([truth_pos]).at[0, axis_idx].set(val) - seg = SegmentData(positions_mm=pos, de=jnp.array([truth_de])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - loss = loss + kernels[p](sigs[p], target_signals[p]) - return loss - return loss_fn - - -# ── Warm up JIT + benchmark ───────────────────────────────────────────────── - -print(f"\nParams: n_proj={N_PROJ}, n_grid={N_GRID}, delta={DELTA}, " - f"lambda_mass={LAMBDA_MASS}") -print("Warming up JIT (this may take a while for dense kernels)...") - -for axis_name, cfg in sweep_configs.items(): - fn = make_loss_fn(axis_name, cfg['idx']) - test_val = cfg['truth'] if cfg['truth'] is not None else truth_pos[cfg['idx']] - t0 = time.time() - loss_val = fn(test_val) - jax.block_until_ready(loss_val) - t1 = time.time() - grad_val = jax.grad(fn)(test_val) - jax.block_until_ready(grad_val) - t2 = time.time() - print(f" {axis_name}: JIT forward={t1-t0:.1f}s, JIT grad={t2-t1:.1f}s, " - f"loss={float(loss_val):.6e}") - -# Time a single value_and_grad call after warmup -fn_x = make_loss_fn('x', 0) -vg_fn = jax.value_and_grad(fn_x) -_ = vg_fn(-100.0) # ensure warm -times = [] -for _ in range(5): - t0 = time.time() - loss, grad = vg_fn(-90.0) - jax.block_until_ready(grad) - times.append(time.time() - t0) -med_ms = np.median(times) * 1000 -print(f"\n Single value_and_grad: {med_ms:.0f} ms (median of 5)") -est_total = med_ms * 80 * 4 * 4 / 1000 / 60 # 80 pts * 4 axes * 4 evals (loss+grad+2fd) -print(f" Estimated total for all surface plots: {est_total:.1f} min") -print() - - -# ── Generate plots ─────────────────────────────────────────────────────────── - -for axis_name, cfg in sweep_configs.items(): - axis_idx = cfg['idx'] - lo, hi = cfg['range'] - n = cfg['n'] - unit = cfg['unit'] - truth_val = cfg['truth'] if cfg['truth'] is not None else truth_pos[axis_idx] - eps = FD_EPS_DE if axis_name == 'dE' else FD_EPS - x_vals = np.linspace(lo, hi, n) - - loss_fn = make_loss_fn(axis_name, axis_idx) - grad_fn = jax.grad(loss_fn) - - t0 = time.time() - print(f"--- {axis_name} (truth={truth_val}) ---") - - print(f" Computing losses...") - losses = np.array([float(loss_fn(float(v))) for v in x_vals]) - print(f" Computing autodiff gradients...") - ad_grads = np.array([float(grad_fn(float(v))) for v in x_vals]) - print(f" Computing finite-diff gradients...") - fd_grads = np.array([ - (float(loss_fn(float(v + eps))) - float(loss_fn(float(v - eps)))) / (2 * eps) - for v in x_vals - ]) - - fig, axes = plt.subplots(1, 2, figsize=(12, 5)) - - axes[0].plot(x_vals, losses, '-', color='#27ae60', lw=1.5) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth {axis_name}={truth_val:.1f}') - axes[0].set_xlabel(f'{axis_name} ({unit})') - axes[0].set_ylabel('Loss') - axes[0].set_title('Loss Landscape') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - - axes[1].plot(x_vals, ad_grads, '-', color='red', lw=1.5, label='Autodiff') - axes[1].plot(x_vals, fd_grads, '--', color='blue', lw=1.5, alpha=0.7, - label=f'FD (eps={eps})') - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth {axis_name}={truth_val:.1f}') - axes[1].set_xlabel(f'{axis_name} ({unit})') - axes[1].set_ylabel(f'd(Loss)/d{axis_name}') - axes[1].set_title('Gradient (Autodiff vs FD)') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - - fig.suptitle( - f'Dense Huber SW — varying {axis_name} | n_proj={N_PROJ}, ' - f'n_grid={N_GRID}, δ={DELTA}', - fontsize=12, fontweight='bold') - fig.tight_layout() - fname = f'huber_dense_surface_{axis_name}.png' - fig.savefig(os.path.join(out_dir, fname), dpi=150) - plt.close(fig) - print(f" {time.time()-t0:.0f}s → {fname}") - -print("\nDone!") diff --git a/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_uniform.py b/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_uniform.py deleted file mode 100644 index 7179d8e..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/loss_gradient_surfaces_uniform.py +++ /dev/null @@ -1,260 +0,0 @@ -""" -Plot loss and gradient surfaces for uniform SW variants (W1, W2, Huber), -varying x, y, z, and dE independently. Loss is summed across all active planes. - -Generates 12 figures: - - w1_surface_{x,y,z,dE}.png - - w2_surface_{x,y,z,dE}.png - - huber_surface_{x,y,z,dE}.png - -Run from project root: - python3 closure_analysis/loss_gradient_surfaces_uniform.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud - -# East side planes: U=0, V=1, Y=2 -PLANES = [0, 1, 2] -K = 10000 -N_PROJ = 200 - -# ── Uniform SW factories ──────────────────────────────────────────────────── - -def make_uniform_sw_w1(n_proj, n_grid=500): - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - wts_a = wts_a / jnp.sum(wts_a) - wts_b = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - quant_a = jnp.interp(grid, cdf_a, proj_a_i[sort_a]) - quant_b = jnp.interp(grid, cdf_b, proj_b_i[sort_b]) - return jnp.mean(jnp.abs(quant_a - quant_b)) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - return sw - - -def make_uniform_sw_w2(n_proj, n_grid=500): - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - wts_a = wts_a / jnp.sum(wts_a) - wts_b = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - quant_a = jnp.interp(grid, cdf_a, proj_a_i[sort_a]) - quant_b = jnp.interp(grid, cdf_b, proj_b_i[sort_b]) - return jnp.mean((quant_a - quant_b) ** 2) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - return sw - - -def make_uniform_sw_huber(n_proj, delta=0.01, n_grid=500): - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - wts_a = wts_a / jnp.sum(wts_a) - wts_b = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - quant_a = jnp.interp(grid, cdf_a, proj_a_i[sort_a]) - quant_b = jnp.interp(grid, cdf_b, proj_b_i[sort_b]) - diff = quant_a - quant_b - abs_diff = jnp.abs(diff) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.mean(huber) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - return sw - - -# ── Setup ──────────────────────────────────────────────────────────────────── - -print("Loading detector config...") -detector_config = generate_detector('config/cubic_wireplane_config.yaml') -sim = DetectorSimulator(detector_config, differentiable=True, n_segments=1) -forward = sim.build_forward() - -truth_pos = np.array([-100.0, 50.0, 100.0]) -truth_de = 1.0 -truth_seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([truth_de])) -target_signals = forward(truth_seg) - -# Pre-compute target pointclouds -target_planes = {} -for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_planes[p] = (pts, w) - -out_dir = os.path.dirname(os.path.abspath(__file__)) - -# Build the 3 loss kernels -sw_w1 = make_uniform_sw_w1(N_PROJ) -sw_w2 = make_uniform_sw_w2(N_PROJ) -sw_huber = make_uniform_sw_huber(N_PROJ, delta=0.01) - -LOSS_VARIANTS = { - 'w1': ('Uniform W1 (abs)', sw_w1), - 'w2': ('Uniform W2 (sq)', sw_w2), - 'huber': ('Uniform Huber', sw_huber), -} - -# Sweep ranges -sweep_configs = { - 'x': {'idx': 0, 'range': (-195, -5), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'y': {'idx': 1, 'range': (-150, 250), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'z': {'idx': 2, 'range': (-100, 300), 'n': 80, 'truth': None, 'unit': 'mm'}, - 'dE': {'idx': -1, 'range': (0.1, 3.0), 'n': 80, 'truth': 1.0, 'unit': 'MeV'}, -} - -FD_EPS = 0.05 -FD_EPS_DE = 0.005 - - -# ── Build loss functions ───────────────────────────────────────────────────── - -def make_loss_fn(axis_name, axis_idx, loss_kernel): - """Build a scalar loss function varying one parameter.""" - if axis_name == 'dE': - def loss_fn(val): - seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([val])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + loss_kernel(pts, w, target_planes[p][0], target_planes[p][1]) - return loss - else: - def loss_fn(val): - pos = jnp.array([truth_pos]).at[0, axis_idx].set(val) - seg = SegmentData(positions_mm=pos, de=jnp.array([truth_de])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + loss_kernel(pts, w, target_planes[p][0], target_planes[p][1]) - return loss - return loss_fn - - -# ── Warm up JIT ────────────────────────────────────────────────────────────── - -print("Warming up JIT...") -for vname, (label, kernel) in LOSS_VARIANTS.items(): - for axis_name, cfg in sweep_configs.items(): - fn = make_loss_fn(axis_name, cfg['idx'], kernel) - test_val = cfg['truth'] if cfg['truth'] is not None else truth_pos[cfg['idx']] - _ = fn(test_val) - _ = jax.grad(fn)(test_val) - print(f" {label} ready") -print("All JIT warm-up done.\n") - - -# ── Generate plots ─────────────────────────────────────────────────────────── - -colors = {'w1': '#e74c3c', 'w2': '#2980b9', 'huber': '#27ae60'} - -for axis_name, cfg in sweep_configs.items(): - axis_idx = cfg['idx'] - lo, hi = cfg['range'] - n = cfg['n'] - unit = cfg['unit'] - truth_val = cfg['truth'] if cfg['truth'] is not None else truth_pos[axis_idx] - eps = FD_EPS_DE if axis_name == 'dE' else FD_EPS - x_vals = np.linspace(lo, hi, n) - - for vname, (label, kernel) in LOSS_VARIANTS.items(): - t0 = time.time() - loss_fn = make_loss_fn(axis_name, axis_idx, kernel) - grad_fn = jax.grad(loss_fn) - - print(f" {label} — {axis_name}...", end='', flush=True) - - losses = np.array([float(loss_fn(float(v))) for v in x_vals]) - ad_grads = np.array([float(grad_fn(float(v))) for v in x_vals]) - fd_grads = np.array([ - (float(loss_fn(float(v + eps))) - float(loss_fn(float(v - eps)))) / (2 * eps) - for v in x_vals - ]) - - # Plot - fig, axes = plt.subplots(1, 2, figsize=(12, 5)) - c = colors[vname] - - axes[0].plot(x_vals, losses, '-', color=c, lw=1.5) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth {axis_name}={truth_val:.1f}') - axes[0].set_xlabel(f'{axis_name} ({unit})') - axes[0].set_ylabel('Loss') - axes[0].set_title('Loss Landscape') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - - axes[1].plot(x_vals, ad_grads, '-', color='red', lw=1.5, label='Autodiff') - axes[1].plot(x_vals, fd_grads, '--', color='blue', lw=1.5, alpha=0.7, - label=f'FD (eps={eps})') - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth {axis_name}={truth_val:.1f}') - axes[1].set_xlabel(f'{axis_name} ({unit})') - axes[1].set_ylabel(f'd(Loss)/d{axis_name}') - axes[1].set_title('Gradient (Autodiff vs FD)') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - - fig.suptitle(f'{label} — varying {axis_name} (summed over U+V+Y planes)', - fontsize=14, fontweight='bold') - fig.tight_layout() - fname = f'{vname}_surface_{axis_name}.png' - fig.savefig(os.path.join(out_dir, fname), dpi=150) - plt.close(fig) - print(f" {time.time()-t0:.0f}s → {fname}") - -print("\nDone!") diff --git a/closure/archive/closure_analysis_original/closure_analysis/mse_surface_dE.png b/closure/archive/closure_analysis_original/closure_analysis/mse_surface_dE.png deleted file mode 100644 index 3d41ad5..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/mse_surface_dE.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/mse_surface_x.png b/closure/archive/closure_analysis_original/closure_analysis/mse_surface_x.png deleted file mode 100644 index 815eebe..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/mse_surface_x.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/mse_surface_y.png b/closure/archive/closure_analysis_original/closure_analysis/mse_surface_y.png deleted file mode 100644 index 7deabc6..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/mse_surface_y.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/mse_surface_z.png b/closure/archive/closure_analysis_original/closure_analysis/mse_surface_z.png deleted file mode 100644 index 9277da2..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/mse_surface_z.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/optimization_closure.py b/closure/archive/closure_analysis_original/closure_analysis/optimization_closure.py deleted file mode 100644 index 7102f03..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/optimization_closure.py +++ /dev/null @@ -1,364 +0,0 @@ -""" -Closure test with Adam optimization for N-segment reconstruction. - -Uses Sliced Wasserstein loss summed over 3 east-side planes (U, V, Y). - -Run from project root: - python3 closure_analysis/optimization_closure.py N -where N is the number of segments (default 1). -""" - -import sys, os -from itertools import permutations -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import optax - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit - -PLANES = [0, 1, 2] # East-side U, V, Y -K = 1000 -N_PROJ = 200 -DE_SCALE = 1.0 # dE update multiplier (Adam already normalizes per-param) -LR = 0.3 -B1 = 0.95 # higher momentum smooths noisy SW gradients (default 0.9) -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -# Bank of truth segments: (x, y, z, dE) in mm / MeV -# Well-separated positions across the detector volume -TRUTH_BANK = np.array([ - [-100.0, 50.0, 100.0, 1.0], - [-150.0, -30.0, 200.0, 1.0], - [ -50.0, -80.0, 50.0, 0.8], - [-120.0, 100.0, 280.0, 1.2], - [ -80.0, -120.0, 150.0, 0.6], - [-170.0, 20.0, 30.0, 0.9], - [ -30.0, 80.0, 250.0, 1.1], - [-140.0, -90.0, 180.0, 0.7], - [ -60.0, 130.0, 320.0, 1.3], - [-180.0, -50.0, 120.0, 0.5], - [ -90.0, 70.0, 350.0, 1.0], - [-160.0, -100.0, 80.0, 0.8], - [ -40.0, -20.0, 270.0, 1.4], - [-110.0, 110.0, 170.0, 0.9], - [ -70.0, -140.0, 230.0, 0.7], - [-130.0, 40.0, 310.0, 1.1], -]) - -# Offsets applied to truth to get initial guess: +30 x, -30 y, +30 z, +0.5 dE -INIT_OFFSET = np.array([30.0, -30.0, 30.0, 0.5]) - - -# ============================================================================= -# Helpers -# ============================================================================= - -def build_sw_loss(forward, target_clouds, key): - """Build SW loss: params (N,4) -> scalar, summed over 3 planes.""" - def loss_fn(params): - if params.ndim == 1: - seg = SegmentData(positions_mm=params[:3][None], de=params[3:4]) - else: - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + sliced_wasserstein_loss_jit( - pts, w, target_clouds[p][0], target_clouds[p][1], - key, n_projections=N_PROJ, - ) - return loss - return loss_fn - - -def run_adam(loss_fn, init_params, lr, n_steps, b1=0.9, de_scale=1.0, print_every=20): - """Run Adam optimization, return loss history and param history.""" - schedule = optax.cosine_decay_schedule(init_value=lr, decay_steps=n_steps, alpha=0.01) - optimizer = optax.adam(schedule, b1=b1) - params = init_params - opt_state = optimizer.init(params) - grad_fn = jax.value_and_grad(loss_fn) - - losses = [] - param_history = [] - - for step in range(n_steps): - loss, grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - if updates.ndim == 1: - updates = updates.at[3].multiply(de_scale) - else: - updates = updates.at[:, 3].multiply(de_scale) - params = optax.apply_updates(params, updates) - - loss_val = float(loss) - losses.append(loss_val) - param_history.append(np.array(params)) - - if step % print_every == 0 or step == n_steps - 1: - print(f" Step {step:4d}: loss = {loss_val:.8e}") - - return np.array(losses), np.array(param_history), params - - -def best_permutation(final, truth_params): - """Find the permutation of truth rows that best matches final (min total L1).""" - n = len(truth_params) - best_err = np.inf - best_perm = None - for perm in permutations(range(n)): - reordered = truth_params[list(perm)] - err = np.abs(final - reordered).sum() - if err < best_err: - best_err = err - best_perm = perm - assignment = truth_params[list(best_perm)] - return assignment, final - assignment - - -# ============================================================================= -# General N-segment closure -# ============================================================================= - -def run_closure(n_seg): - """Run closure test for n_seg segments.""" - assert n_seg <= len(TRUTH_BANK), f"Only {len(TRUTH_BANK)} truth segments defined" - - n_steps = 300 + 78 * (n_seg - 1) # ~300 for 1, ~600 for 5, ~1000 for 10 - print_every = max(20, n_steps // 15) - - print(f"\n{'=' * 70}") - print(f"{n_seg}-SEGMENT CLOSURE TEST") - print(f"{'=' * 70}") - print(f"Hyperparams: lr={LR}, b1={B1}, de_scale={DE_SCALE}, steps={n_steps}") - - truth_params = TRUTH_BANK[:n_seg] # (n_seg, 4) - init_params = jnp.array(truth_params + INIT_OFFSET) - - for i in range(n_seg): - print(f" Seg {i}: truth={truth_params[i]} init={np.array(init_params[i])}") - - # Build simulator and forward - print("Building simulator...") - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg) - forward = sim.build_forward() - - # Generate target - if n_seg == 1: - truth_seg = SegmentData( - positions_mm=jnp.array(truth_params[:, :3]), - de=jnp.array(truth_params[:, 3]), - ) - init_flat = init_params[0] # (4,) for 1-seg - else: - truth_seg = SegmentData( - positions_mm=jnp.array(truth_params[:, :3]), - de=jnp.array(truth_params[:, 3]), - ) - init_flat = init_params # (N, 4) - - target_signals = forward(truth_seg) - key = jax.random.PRNGKey(42) - - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_clouds[p] = (pts, w) - - loss_fn = build_sw_loss(forward, target_clouds, key) - - # Warm up JIT - print("Warming up JIT...") - _ = loss_fn(init_flat) - _ = jax.grad(loss_fn)(init_flat) - print("JIT warm-up done.") - - # Optimize - losses, param_history, final_params = run_adam( - loss_fn, init_flat, lr=LR, n_steps=n_steps, b1=B1, de_scale=DE_SCALE, - print_every=print_every, - ) - - final = np.array(final_params) - if n_seg == 1: - final_2d = final[None, :] # (1, 4) - param_history_3d = param_history[:, None, :] # (steps, 1, 4) - else: - final_2d = final # (N, 4) - param_history_3d = param_history # (steps, N, 4) - - # Match segments to truth - assignment, errors = best_permutation(final_2d, truth_params) - - print(f"\nResults:") - for i in range(n_seg): - e = errors[i] - print(f" Seg {i}: x={e[0]:+.3f} mm, y={e[1]:+.3f} mm, " - f"z={e[2]:+.3f} mm, dE={e[3]*1000:+.1f} keV") - max_pos = np.max(np.abs(errors[:, :3])) - max_de = np.max(np.abs(errors[:, 3])) * 1000 - print(f" Max position error: {max_pos:.3f} mm") - print(f" Max dE error: {max_de:.1f} keV") - - # ── Plotting ── - _plot_closure(n_seg, losses, param_history_3d, assignment, errors) - - return errors - - -# ============================================================================= -# Plotting -# ============================================================================= - -def _plot_closure(n_seg, losses, param_history, assignment, errors): - """Plot closure results. Per-component for N<=3, total error for N>3.""" - pos_colors = ['#1f77b4', '#ff7f0e', '#2ca02c'] - seg_colors = plt.cm.tab10(np.linspace(0, 1, max(n_seg, 3))) - - if n_seg <= 3: - _plot_per_component(n_seg, losses, param_history, assignment, seg_colors) - else: - _plot_total_error(n_seg, losses, param_history, assignment, seg_colors) - - -def _plot_per_component(n_seg, losses, param_history, assignment, seg_colors): - """1-seg: 1x3, 2-seg: 2x2, 3-seg: 2x3.""" - pos_labels = ['x', 'y', 'z'] - pos_colors = ['#1f77b4', '#ff7f0e', '#2ca02c'] - seg_de_colors = ['#d62728', '#9467bd', '#8c564b'] - - if n_seg == 1: - fig, axes = plt.subplots(1, 3, figsize=(16, 5)) - axes[0].semilogy(losses, 'b-', lw=1.2) - axes[0].set_xlabel('Step'); axes[0].set_ylabel('SW Loss') - axes[0].set_title('Loss Convergence'); axes[0].grid(True, alpha=0.3) - - truth = assignment[0] - for i, (lbl, clr) in enumerate(zip(pos_labels, pos_colors)): - axes[1].plot(param_history[:, 0, i] - truth[i], color=clr, lw=1.2, label=lbl) - axes[1].axhline(0, color='k', ls='--', lw=0.8) - axes[1].set_xlabel('Step'); axes[1].set_ylabel('Error (mm)') - axes[1].set_title('Position Errors'); axes[1].legend(); axes[1].grid(True, alpha=0.3) - - axes[2].plot((param_history[:, 0, 3] - truth[3]) * 1000, color='#d62728', lw=1.2) - axes[2].axhline(0, color='k', ls='--', lw=0.8) - axes[2].set_xlabel('Step'); axes[2].set_ylabel('Error (keV)') - axes[2].set_title('Energy Error'); axes[2].grid(True, alpha=0.3) - - elif n_seg == 2: - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - - axes[0, 0].semilogy(losses, 'b-', lw=1.2) - axes[0, 0].set_xlabel('Step'); axes[0, 0].set_ylabel('SW Loss') - axes[0, 0].set_title('Loss Convergence'); axes[0, 0].grid(True, alpha=0.3) - - for s in range(2): - axes[0, 1].plot(param_history[:, s, 3] * 1000, color=seg_de_colors[s], - lw=1.2, label=f'Seg {s}') - axes[0, 1].axhline(assignment[s, 3] * 1000, color=seg_de_colors[s], - ls=':', lw=1.0, alpha=0.6) - axes[0, 1].set_xlabel('Step'); axes[0, 1].set_ylabel('dE (keV)') - axes[0, 1].set_title('Energy Trajectories (dotted = truth)') - axes[0, 1].legend(); axes[0, 1].grid(True, alpha=0.3) - - for s in range(2): - ax = axes[1, s] - for i, (lbl, clr) in enumerate(zip(pos_labels, pos_colors)): - ax.plot(param_history[:, s, i], color=clr, lw=1.2, label=lbl) - ax.axhline(assignment[s, i], color=clr, ls=':', lw=1.0, alpha=0.6) - ax.set_xlabel('Step'); ax.set_ylabel('Position (mm)') - ax.set_title(f'Segment {s} Positions (dotted = truth)') - ax.legend(); ax.grid(True, alpha=0.3) - - else: # n_seg == 3 - fig = plt.figure(figsize=(18, 10)) - gs = fig.add_gridspec(2, 3, hspace=0.3, wspace=0.3) - - ax_loss = fig.add_subplot(gs[0, 0]) - ax_loss.semilogy(losses, 'b-', lw=1.2) - ax_loss.set_xlabel('Step'); ax_loss.set_ylabel('SW Loss') - ax_loss.set_title('Loss Convergence'); ax_loss.grid(True, alpha=0.3) - - ax_de = fig.add_subplot(gs[0, 1:]) - for s in range(3): - ax_de.plot(param_history[:, s, 3] * 1000, color=seg_de_colors[s], - lw=1.2, label=f'Seg {s}') - ax_de.axhline(assignment[s, 3] * 1000, color=seg_de_colors[s], - ls=':', lw=1.0, alpha=0.6) - ax_de.set_xlabel('Step'); ax_de.set_ylabel('dE (keV)') - ax_de.set_title('Energy Trajectories (dotted = truth)') - ax_de.legend(); ax_de.grid(True, alpha=0.3) - - for s in range(3): - ax = fig.add_subplot(gs[1, s]) - for i, (lbl, clr) in enumerate(zip(pos_labels, pos_colors)): - ax.plot(param_history[:, s, i], color=clr, lw=1.2, label=lbl) - ax.axhline(assignment[s, i], color=clr, ls=':', lw=1.0, alpha=0.6) - ax.set_xlabel('Step'); ax.set_ylabel('Position (mm)') - ax.set_title(f'Segment {s} Positions (dotted = truth)') - ax.legend(); ax.grid(True, alpha=0.3) - - fig.suptitle(f'{n_seg}-Segment Closure Test (Adam, lr={LR}, b1={B1})', - fontsize=14, fontweight='bold') - if n_seg <= 2: - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'closure_{n_seg}seg.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - -def _plot_total_error(n_seg, losses, param_history, assignment, seg_colors): - """For N>3: loss, total position error per segment, dE per segment.""" - fig, axes = plt.subplots(1, 3, figsize=(18, 5)) - - # Loss - axes[0].semilogy(losses, 'b-', lw=1.2) - axes[0].set_xlabel('Step'); axes[0].set_ylabel('SW Loss') - axes[0].set_title('Loss Convergence'); axes[0].grid(True, alpha=0.3) - - # Total position error per segment: ||pos - truth|| - for s in range(n_seg): - pos_err = np.sqrt(np.sum((param_history[:, s, :3] - assignment[s, :3]) ** 2, axis=1)) - axes[1].plot(pos_err, color=seg_colors[s], lw=1.2, label=f'Seg {s}') - axes[1].axhline(0, color='k', ls='--', lw=0.8) - axes[1].set_xlabel('Step'); axes[1].set_ylabel('||pos error|| (mm)') - axes[1].set_title('Position Error per Segment') - axes[1].legend(fontsize=7, ncol=2); axes[1].grid(True, alpha=0.3) - - # dE per segment - for s in range(n_seg): - axes[2].plot(param_history[:, s, 3] * 1000, color=seg_colors[s], - lw=1.2, label=f'Seg {s}') - axes[2].axhline(assignment[s, 3] * 1000, color=seg_colors[s], - ls=':', lw=1.0, alpha=0.5) - axes[2].set_xlabel('Step'); axes[2].set_ylabel('dE (keV)') - axes[2].set_title('Energy Trajectories (dotted = truth)') - axes[2].legend(fontsize=7, ncol=2); axes[2].grid(True, alpha=0.3) - - fig.suptitle(f'{n_seg}-Segment Closure Test (Adam, lr={LR}, b1={B1})', - fontsize=14, fontweight='bold') - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'closure_{n_seg}seg.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - -# ============================================================================= -# Main -# ============================================================================= - -if __name__ == '__main__': - n = int(sys.argv[1]) if len(sys.argv) > 1 else 1 - run_closure(n) diff --git a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_A_L1e4_split80.png b/closure/archive/closure_analysis_original/closure_analysis/overcomplete_A_L1e4_split80.png deleted file mode 100644 index 07538ff..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_A_L1e4_split80.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_B_L2e4_split70.png b/closure/archive/closure_analysis_original/closure_analysis/overcomplete_B_L2e4_split70.png deleted file mode 100644 index 29b1179..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_B_L2e4_split70.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_C_L1e4_split50.png b/closure/archive/closure_analysis_original/closure_analysis/overcomplete_C_L1e4_split50.png deleted file mode 100644 index 21a0c40..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_C_L1e4_split50.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_D_L5e4_split80.png b/closure/archive/closure_analysis_original/closure_analysis/overcomplete_D_L5e4_split80.png deleted file mode 100644 index 89afbff..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_D_L5e4_split80.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_E_L1e3_split70.png b/closure/archive/closure_analysis_original/closure_analysis/overcomplete_E_L1e3_split70.png deleted file mode 100644 index 8d11aa5..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_E_L1e3_split70.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_F_L5e4_split50.png b/closure/archive/closure_analysis_original/closure_analysis/overcomplete_F_L5e4_split50.png deleted file mode 100644 index 6916ed9..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_F_L5e4_split50.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_G_L5e4_split80.png b/closure/archive/closure_analysis_original/closure_analysis/overcomplete_G_L5e4_split80.png deleted file mode 100644 index 2d33c8b..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/overcomplete_G_L5e4_split80.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/run_overcomplete_combos.py b/closure/archive/closure_analysis_original/closure_analysis/run_overcomplete_combos.py deleted file mode 100644 index ec1d0fa..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/run_overcomplete_combos.py +++ /dev/null @@ -1,338 +0,0 @@ -""" -Run 3 overcomplete combos (10/5) with new base config. -Each gets its own diagnostic plot saved with unique name. - -Base: LR=0.7, exp d=0.9995, lr_e_mult=0.02, b1=0.95 -MCMC: warmup=400, DT=0.005, linear noise NOISE_LR=0.05 - -Combos: - A: L1=1e-4, split=80/20 - B: L1=2e-4, split=70/30 - C: L1=1e-4, split=50/50 - -Run: python3 closure_analysis/run_overcomplete_combos.py -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import optax - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit -from closure_analysis.sgld_closure import ( - TRUTH_BANK, INIT_OFFSET, EXTRA_INIT_BOUNDS, PLANES, K, N_PROJ, - build_loss_fn, best_permutation, relocate_segments, reset_adam_moments, -) - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -N_SEG = 10 -N_TRUTH = 5 -MIN_ENERGY = 0.001 -STEPS = 2000 - -# Base config -LR = 0.5 -DECAY_RATE = 0.999 -LR_E_MULT = 0.02 -B1 = 0.95 -B2 = 0.999 - -# MCMC config -WARMUP = 400 -DEATH_THRESH = 0.005 -NOISE_LR = 0.3 # linear coupling -NOISE_COUPLING = 'linear' - -# Plot sizes -LABEL_SIZE = 16 -TITLE_SIZE = 17 -TICK_SIZE = 13 -LEGEND_SIZE = 12 -SUPTITLE_SIZE = 16 - - -COMBOS = [ - {'name': 'G_L5e4_split80', 'l1': 5e-4, 'split': 0.8}, - {'name': 'H_L1e3_split70', 'l1': 1e-3, 'split': 0.7}, - {'name': 'I_L5e4_split50', 'l1': 5e-4, 'split': 0.5}, -] - - -def run_combo(combo, grad_fn, init_params, truth_params): - name = combo['name'] - l1_rate = combo['l1'] - split_ratio = combo['split'] - - schedule = optax.exponential_decay(init_value=LR, transition_steps=1, decay_rate=DECAY_RATE) - optimizer = optax.adam(schedule, b1=B1, b2=B2) - - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - losses = [] - param_history = [] - dead_counts = [] - relocation_steps = [] - cumulative_relocs = 0 - - for step in range(STEPS): - (loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(LR_E_MULT) - params = optax.apply_updates(params, updates) - - # Energy floor - params = params.at[:, 3].set(jnp.maximum(params[:, 3], MIN_ENERGY)) - - # L1 drain after warmup - if step >= WARMUP: - params = params.at[:, 3].add(-l1_rate) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], MIN_ENERGY)) - - # Noise (linear coupling) - lr_cur = float(schedule(step)) - ns = lr_cur * NOISE_LR - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add(ns * jax.random.normal(nk, shape=(N_SEG, 3))) - - # Relocation after warmup - n_dead = int(jnp.sum(params[:, 3] <= DEATH_THRESH)) - if step >= WARMUP and n_dead > 0: - # Inline relocation with custom split ratio - energies = np.array(params[:, 3]) - dead_mask = energies <= DEATH_THRESH - dead_indices = np.where(dead_mask)[0] - alive_mask = ~dead_mask - alive_indices = np.where(alive_mask)[0] - - if len(dead_indices) > 0 and len(alive_indices) > 0: - alive_energies = np.array(params[alive_indices, 3], dtype=np.float64) - n_reloc = 0 - for d_idx in dead_indices: - if alive_energies.sum() <= 0: - break - probs = alive_energies / alive_energies.sum() - rng_key, sk = jax.random.split(rng_key) - donor_local = int(jax.random.choice(sk, len(alive_indices), p=jnp.array(probs))) - donor_idx = alive_indices[donor_local] - donor_energy = float(params[donor_idx, 3]) - - rng_key, ok = jax.random.split(rng_key) - offset = jax.random.normal(ok, shape=(3,)) * 3.0 - new_pos = params[donor_idx, :3] + offset - - clone_energy = donor_energy * (1.0 - split_ratio) - donor_new_energy = donor_energy * split_ratio - - params = params.at[d_idx, :3].set(new_pos) - params = params.at[d_idx, 3].set(clone_energy) - params = params.at[donor_idx, 3].set(donor_new_energy) - alive_energies[donor_local] = donor_new_energy - - opt_state = reset_adam_moments(opt_state, d_idx) - n_reloc += 1 - - if n_reloc > 0: - cumulative_relocs += n_reloc - relocation_steps.append((step, n_reloc)) - - losses.append(float(loss)) - param_history.append(np.array(params)) - dead_counts.append(n_dead) - - # Evaluate - final = np.array(params) - param_history = np.array(param_history) - assignment, errors, matched_idx = best_permutation(final, truth_params) - matched_errors = errors[matched_idx] - extra_idx = [i for i in range(N_SEG) if i not in matched_idx] - - mean_pos = np.mean(np.sqrt(np.sum(matched_errors[:, :3] ** 2, axis=1))) - max_pos = np.max(np.sqrt(np.sum(matched_errors[:, :3] ** 2, axis=1))) - max_de = np.max(np.abs(matched_errors[:, 3])) * 1000 - extra_energies = [float(final[i, 3]) for i in extra_idx] - n_extra_dead = sum(1 for e in extra_energies if e <= DEATH_THRESH) - - return { - 'name': name, 'l1': l1_rate, 'split': split_ratio, - 'mean_pos': mean_pos, 'max_pos': max_pos, 'max_de': max_de, - 'loss': losses[-1], 'losses': losses, - 'param_history': param_history, - 'assignment': assignment, 'matched_idx': matched_idx, - 'extra_idx': extra_idx, 'extra_energies': extra_energies, - 'n_extra_dead': n_extra_dead, 'dead_counts': dead_counts, - 'relocation_steps': relocation_steps, 'cumulative_relocs': cumulative_relocs, - } - - -def plot_combo(r, truth_params): - n_seg = N_SEG - seg_colors = plt.cm.tab10(np.linspace(0, 1, max(n_seg, 3))) - fig, axes = plt.subplots(2, 2, figsize=(18, 14)) - - losses = r['losses'] - param_history = r['param_history'] - assignment = r['assignment'] - matched_idx = r['matched_idx'] - extra_idx = r['extra_idx'] - relocation_steps = r['relocation_steps'] - - # --- Top-left: loss curve --- - ax = axes[0, 0] - ax.semilogy(losses, 'b-', lw=1.2, alpha=0.7, label='SW loss') - ax.axvline(WARMUP, color='gray', ls='--', lw=1.0, alpha=0.5, label=f'Warmup={WARMUP}') - for rs, nr in relocation_steps: - ax.axvline(rs, color='red', ls=':', lw=0.5, alpha=0.3) - ax.set_xlabel('Step', fontsize=LABEL_SIZE) - ax.set_ylabel('Loss', fontsize=LABEL_SIZE) - ax.set_title('Loss Convergence (red = relocation)', fontsize=TITLE_SIZE) - ax.legend(fontsize=LEGEND_SIZE) - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3) - - # --- Top-right: position error per matched segment --- - ax = axes[0, 1] - for s in matched_idx: - pos_err = np.sqrt(np.sum( - (param_history[:, s, :3] - assignment[s, :3]) ** 2, axis=1)) - ax.plot(pos_err, color=seg_colors[s], lw=1.2, label=f'Seg {s}') - ax.axhline(0, color='k', ls='--', lw=0.8) - ax.set_xlabel('Step', fontsize=LABEL_SIZE) - ax.set_ylabel('||pos error|| (mm)', fontsize=LABEL_SIZE) - ax.set_title(f'Position Error (matched {N_TRUTH} segments)', fontsize=TITLE_SIZE) - ax.legend(fontsize=LEGEND_SIZE - 1, ncol=2) - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3) - - # --- Bottom-left: total energy + per-segment energy --- - ax = axes[1, 0] - total_e = param_history[:, :, 3].sum(axis=1) * 1000 - truth_total_e = sum(assignment[s, 3] for s in matched_idx) * 1000 - ax.plot(total_e, 'k-', lw=2.5, alpha=0.8, label='Total energy') - ax.axhline(truth_total_e, color='k', ls=':', lw=1.5, alpha=0.5, - label=f'Truth total={truth_total_e:.0f} keV') - for s in range(n_seg): - is_extra = s in extra_idx - ls = '--' if is_extra else '-' - ax.plot(param_history[:, s, 3] * 1000, color=seg_colors[s], - lw=0.8, ls=ls, alpha=0.4) - ax.set_xlabel('Step', fontsize=LABEL_SIZE) - ax.set_ylabel('Energy (keV)', fontsize=LABEL_SIZE) - ax.set_title('Energy (total=black, segments=thin)', fontsize=TITLE_SIZE) - ax.legend(fontsize=LEGEND_SIZE, loc='upper right') - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3) - - # --- Bottom-right: per-segment energy trajectories --- - ax = axes[1, 1] - for s in range(n_seg): - is_extra = s in extra_idx - ls = '--' if is_extra else '-' - alpha_val = 0.5 if is_extra else 1.0 - lbl = f'Seg {s}' + (' (extra)' if is_extra else '') - ax.plot(param_history[:, s, 3] * 1000, color=seg_colors[s], - lw=1.2, ls=ls, alpha=alpha_val, label=lbl) - if not is_extra: - ax.axhline(assignment[s, 3] * 1000, color=seg_colors[s], - ls=':', lw=0.8, alpha=0.4) - ax.set_xlabel('Step', fontsize=LABEL_SIZE) - ax.set_ylabel('dE (keV)', fontsize=LABEL_SIZE) - ax.set_title('Per-Segment Energy (solid=matched, dashed=extra, dotted=truth)', - fontsize=TITLE_SIZE) - ax.legend(fontsize=LEGEND_SIZE - 2, ncol=2) - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3) - - split_pct = f"{int(r['split']*100)}/{int((1-r['split'])*100)}" - fig.suptitle( - f"10/5 Overcomplete — {r['name']} | L1={r['l1']}, split={split_pct}, " - f"noise={NOISE_LR}lin, WU={WARMUP}\n" - f"pos={r['mean_pos']:.2f}mm, max={r['max_pos']:.2f}mm, dE={r['max_de']:.1f}keV, " - f"relocs={r['cumulative_relocs']}, extras_dead={r['n_extra_dead']}/5", - fontsize=SUPTITLE_SIZE, fontweight='bold') - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'overcomplete_{r["name"]}.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f" Saved {fname}") - - -def main(): - print(f"Overcomplete 10/5 sweep — 3 combos, {STEPS} steps each") - print(f"Base: LR={LR}, d={DECAY_RATE}, e_mult={LR_E_MULT}, b1={B1}") - print(f"MCMC: WU={WARMUP}, DT={DEATH_THRESH}, noise={NOISE_LR} linear\n") - - # Build simulators - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim_truth = DetectorSimulator(detector_config, differentiable=True, n_segments=N_TRUTH) - fwd_truth = sim_truth.build_forward() - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEG) - fwd_opt = sim_opt.build_forward() - - truth_params = TRUTH_BANK[:N_TRUTH] - truth_seg = SegmentData(positions_mm=jnp.array(truth_params[:, :3]), - de=jnp.array(truth_params[:, 3])) - target_signals = fwd_truth(truth_seg) - key = jax.random.PRNGKey(42) - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_clouds[p] = (pts, w) - - loss_fn = build_loss_fn(fwd_opt, target_clouds, key) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Init params - rng_init = np.random.RandomState(42) - init_p = np.zeros((N_SEG, 4)) - init_p[:N_TRUTH] = truth_params + INIT_OFFSET - median_e = float(np.median(truth_params[:, 3])) - for i in range(N_TRUTH, N_SEG): - init_p[i, 0] = rng_init.uniform(*EXTRA_INIT_BOUNDS['x']) - init_p[i, 1] = rng_init.uniform(*EXTRA_INIT_BOUNDS['y']) - init_p[i, 2] = rng_init.uniform(*EXTRA_INIT_BOUNDS['z']) - init_p[i, 3] = median_e - init_params = jnp.array(init_p) - - print("Warming up JIT...") - _ = grad_fn(init_params) - print("Ready.\n") - - # Run combos - results = [] - for combo in COMBOS: - split_pct = f"{int(combo['split']*100)}/{int((1-combo['split'])*100)}" - print(f"[{combo['name']}] L1={combo['l1']}, split={split_pct}...") - t0 = time.time() - r = run_combo(combo, grad_fn, init_params, truth_params) - dt = time.time() - t0 - ee = ', '.join(f"{e:.4f}" for e in r['extra_energies']) - print(f" pos={r['mean_pos']:.2f}mm max={r['max_pos']:.2f}mm " - f"dE={r['max_de']:.1f}keV loss={r['loss']:.6f} " - f"relocs={r['cumulative_relocs']} extras_dead={r['n_extra_dead']}/5 " - f"extras=[{ee}] {dt:.0f}s") - plot_combo(r, truth_params) - results.append(r) - - # Summary - print(f"\n{'='*80}") - print(f"SUMMARY — 10/5 overcomplete, {STEPS} steps") - print(f"{'='*80}") - print(f"{'Name':<20} {'Pos':>6} {'Max':>6} {'dE':>6} {'Loss':>9} {'Relocs':>6} {'Dead':>5}") - for r in results: - print(f"{r['name']:<20} {r['mean_pos']:6.2f} {r['max_pos']:6.2f} " - f"{r['max_de']:6.1f} {r['loss']:9.6f} {r['cumulative_relocs']:6d} " - f"{r['n_extra_dead']:3d}/5") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure.py b/closure/archive/closure_analysis_original/closure_analysis/sgld_closure.py deleted file mode 100644 index 65bc688..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure.py +++ /dev/null @@ -1,599 +0,0 @@ -""" -MCMC-inspired optimizer for N-segment closure analysis. - -Based on 3DGS-MCMC (Kheradmand et al., NeurIPS 2024) adapted for TPC simulation. - -Pipeline per step: - 1. Adam update on (pos, dE) with reconstruction gradients only - 2. Decoupled L1 energy drain (fixed rate, bypasses Adam — like AdamW) - 3. Position noise (coupled to LR schedule, no gating) - 4. Track gradient EMA per segment (diagnostic) - 5. Relocate dead segments via energy-proportional multinomial sampling - -Key design choices vs original 3DGS-MCMC paper: - - Decoupled L1 ensures fixed drain rate independent of Adam state - - No noise gating: energy != convergence quality in our physics - - No separate noise decay: coupled to cosine LR schedule - - Donor selection: multinomial sampling proportional to energy (mirrors paper) - - 50/50 energy split gives clone enough survival time to explore - -Supports overcomplete mode (n_seg > n_truth): - Extra segments initialized at random positions with median energy. - L1 drains extras; noise breaks symmetry between competing segments. - Dead segments cycle through relocation until they find uncovered positions. - -Modes: - baseline — plain Adam + cosine schedule - noise — + position noise (no gating) - full — + decoupled L1 + relocation (default) - -Run from project root: - python3 closure_analysis/sgld_closure.py N [--n_truth T] [--steps S] [--mode MODE] - -Examples: - python3 closure_analysis/sgld_closure.py 5 --steps 1500 --mode baseline - python3 closure_analysis/sgld_closure.py 5 --steps 3000 --mode full - python3 closure_analysis/sgld_closure.py 8 --n_truth 5 --steps 3000 -""" - -import sys, os, argparse, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import optax - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit - -# ============================================================================= -# Truth bank for 0.5mm segments (energies in 0.05–0.20 MeV) -# Positions unchanged from original (mm), energies scaled to 0.5mm dE/dx range -# ============================================================================= - -TRUTH_BANK = np.array([ - [-100.0, 50.0, 100.0, 0.10], - [-150.0, -30.0, 200.0, 0.10], - [ -50.0, -80.0, 50.0, 0.08], - [-120.0, 100.0, 280.0, 0.12], - [ -80.0, -120.0, 150.0, 0.06], - [-170.0, 20.0, 30.0, 0.09], - [ -30.0, 80.0, 250.0, 0.11], - [-140.0, -90.0, 180.0, 0.07], - [ -60.0, 130.0, 320.0, 0.13], - [-180.0, -50.0, 120.0, 0.05], - [ -90.0, 70.0, 350.0, 0.10], - [-160.0, -100.0, 80.0, 0.08], - [ -40.0, -20.0, 270.0, 0.14], - [-110.0, 110.0, 170.0, 0.09], - [ -70.0, -140.0, 230.0, 0.07], - [-130.0, 40.0, 310.0, 0.11], -]) - -INIT_OFFSET = np.array([30.0, -30.0, 30.0, 0.05]) # ~50% energy perturbation - -# Detector volume bounds for random init of extra segments (mm) -EXTRA_INIT_BOUNDS = { - 'x': (-200.0, -20.0), # drift direction - 'y': (-150.0, 150.0), - 'z': (20.0, 380.0), -} - -# ============================================================================= -# Hyperparameters -# ============================================================================= - -PLANES = [0, 1, 2] -K = 10000 -N_PROJ = 200 -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -# Optimizer -LR_POSITION = 0.5 -LR_ENERGY_MULT = 0.01 # energy learns slower than positions -B1 = 0.95 -B2 = 0.999 - -# L1 on energy (coupled to LR schedule — strong early, safe late) -LR_L1 = 0.00005 # MeV/step fixed rate -MIN_ENERGY = 0.001 # MeV numerical floor -DEATH_THRESH = 0.005 # MeV — segments at or near MIN_ENERGY get relocated - -# Noise -NOISE_LR = 5.0 # noise ∝ lr² — strong early exploration, settles late - -# Relocation — continuous (every step after warmup) -WARMUP = 500 -SPLIT_RATIO = 0.5 # 50/50 energy split - -# EMA -GRAD_EMA_BETA = 0.95 - -TOTAL_STEPS = 3000 - - -# ============================================================================= -# Helpers -# ============================================================================= - -def best_permutation(final, truth_params): - """Match optimizer segments to truth via Hungarian algorithm. - - Handles overcomplete case (n_seg > n_truth): returns best n_truth matches. - Remaining segments are unmatched extras. - - Returns - ------- - assignment : (n_seg, 4) — matched truth for each optimizer segment (zeros for extras) - errors : (n_seg, 4) — error for each optimizer segment (NaN for extras) - matched_idx : list of optimizer segment indices that matched truth - """ - from scipy.optimize import linear_sum_assignment - n_seg = len(final) - n_truth = len(truth_params) - - # Cost matrix: (n_seg, n_truth) — L1 distance in position+energy space - cost = np.sum(np.abs(final[:, None, :] - truth_params[None, :, :]), axis=2) - row_ind, col_ind = linear_sum_assignment(cost) - - # Build assignment array: matched segments get their truth, extras get zeros - assignment = np.zeros_like(final) - errors = np.full_like(final, np.nan) - for r, c in zip(row_ind, col_ind): - assignment[r] = truth_params[c] - errors[r] = final[r] - truth_params[c] - - return assignment, errors, list(row_ind) - - -# ============================================================================= -# Loss function (reconstruction only — no L1 in the loss) -# ============================================================================= - -def build_loss_fn(forward, target_clouds, key): - """Build SW loss summed over 3 planes. No regularization terms.""" - def loss_fn(params): - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + sliced_wasserstein_loss_jit( - pts, w, target_clouds[p][0], target_clouds[p][1], - key, n_projections=N_PROJ, - ) - return loss, loss - return loss_fn - - -# ============================================================================= -# Adam state manipulation -# ============================================================================= - -def reset_adam_moments(opt_state, target_idx): - """Zero out Adam moments for a specific segment index.""" - adam_state = opt_state[0] - new_mu = adam_state.mu.at[target_idx].set(0.0) - new_nu = adam_state.nu.at[target_idx].set(0.0) - new_adam_state = adam_state._replace(mu=new_mu, nu=new_nu) - return (new_adam_state,) + opt_state[1:] - - -# ============================================================================= -# Segment relocation -# ============================================================================= - -def relocate_segments(params, opt_state, rng_key): - """Relocate dead segments via energy-proportional multinomial sampling. - - Mirrors the paper's _sample_alives(): donors sampled proportional to energy, - processed sequentially so each split halves the donor's sampling weight - (self-regulating — prevents donor massacre). - - - 50/50 energy split per clone - - Clone position = donor + small offset (break symmetry) - - Clone's Adam state is reset (fresh start) - - Returns (params, opt_state, rng_key, n_relocated). - """ - energies = np.array(params[:, 3]) - dead_mask = energies <= DEATH_THRESH - dead_indices = np.where(dead_mask)[0] - alive_mask = ~dead_mask - alive_indices = np.where(alive_mask)[0] - - if len(dead_indices) == 0 or len(alive_indices) == 0: - return params, opt_state, rng_key, 0 - - # Mutable energy weights — updated after each pick (self-regulating) - alive_energies = np.array(params[alive_indices, 3], dtype=np.float64) - n_relocated = 0 - - for d_idx in dead_indices: - # Skip if all alive segments are now too weak to donate - if alive_energies.sum() <= 0: - break - - # Multinomial sampling proportional to energy - probs = alive_energies / alive_energies.sum() - rng_key, sample_key = jax.random.split(rng_key) - donor_local = int(jax.random.choice(sample_key, len(alive_indices), p=jnp.array(probs))) - donor_idx = alive_indices[donor_local] - - donor_energy = float(params[donor_idx, 3]) - - # Position: donor + small Gaussian offset to break symmetry - rng_key, offset_key = jax.random.split(rng_key) - offset = jax.random.normal(offset_key, shape=(3,)) * 3.0 # ~3mm std - new_pos = params[donor_idx, :3] + offset - - # Energy split: clone gets small fraction, donor mostly preserved - clone_energy = donor_energy * (1.0 - SPLIT_RATIO) - donor_new_energy = donor_energy * SPLIT_RATIO - - params = params.at[d_idx, :3].set(new_pos) - params = params.at[d_idx, 3].set(clone_energy) - params = params.at[donor_idx, 3].set(donor_new_energy) - - # Update sampling weight (self-regulating: halved after each pick) - alive_energies[donor_local] = donor_new_energy - - # Reset clone's Adam state (fresh start) - opt_state = reset_adam_moments(opt_state, d_idx) - n_relocated += 1 - - print(f" Relocated seg {d_idx} (dE={energies[d_idx]:.4f}) " - f"-> donor {donor_idx} (dE={donor_energy:.4f}->{donor_new_energy:.4f})") - - return params, opt_state, rng_key, n_relocated - - -# ============================================================================= -# Main training -# ============================================================================= - -def run_sgld_closure(n_seg, n_truth=None, total_steps=TOTAL_STEPS, mode='full'): - """Run MCMC-inspired closure test. - - Parameters - ---------- - n_seg : int - Number of optimizer segments. - n_truth : int or None - Number of truth segments. Defaults to n_seg (equal mode). - If n_truth < n_seg, runs in overcomplete mode. - total_steps : int - Total optimization steps. - mode : str - 'baseline' (Adam only), 'noise' (+ noise), 'full' (+ L1 + relocation) - """ - if n_truth is None: - n_truth = n_seg - assert n_truth <= len(TRUTH_BANK), f"Only {len(TRUTH_BANK)} truth segments defined" - assert n_seg >= n_truth, f"n_seg ({n_seg}) must be >= n_truth ({n_truth})" - assert mode in ('baseline', 'noise', 'full'), f"Unknown mode: {mode}" - - overcomplete = n_seg > n_truth - enable_noise = mode in ('noise', 'full') - enable_l1 = mode == 'full' - enable_relocation = mode == 'full' - - print(f"\n{'=' * 70}") - oc_str = f" [{n_seg} opt / {n_truth} truth — OVERCOMPLETE]" if overcomplete else "" - print(f"{n_seg}-SEGMENT MCMC CLOSURE TEST [mode={mode}]{oc_str}") - print(f"{'=' * 70}") - print(f"Hyperparams:") - print(f" lr_pos={LR_POSITION}, lr_e_mult={LR_ENERGY_MULT}, b1={B1}") - print(f" noise_lr={NOISE_LR}, lr_l1={LR_L1}, death_thresh={DEATH_THRESH}") - print(f" split_ratio={SPLIT_RATIO}, warmup={WARMUP}, reloc=continuous, steps={total_steps}") - print(f" K={K}, N_PROJ={N_PROJ}") - print(f" noise={enable_noise}, l1={enable_l1}, relocation={enable_relocation}") - - truth_params = TRUTH_BANK[:n_truth] - - # --- Initialize optimizer segments --- - rng_init = np.random.RandomState(42) - init_params = np.zeros((n_seg, 4)) - - # First n_truth segments: near truth + offset - init_params[:n_truth] = truth_params + INIT_OFFSET - - # Extra segments: random positions, median energy - if overcomplete: - median_energy = float(np.median(truth_params[:, 3])) - for i in range(n_truth, n_seg): - init_params[i, 0] = rng_init.uniform(*EXTRA_INIT_BOUNDS['x']) - init_params[i, 1] = rng_init.uniform(*EXTRA_INIT_BOUNDS['y']) - init_params[i, 2] = rng_init.uniform(*EXTRA_INIT_BOUNDS['z']) - init_params[i, 3] = median_energy - - init_params = jnp.array(init_params) - - print(f"\nTruth segments ({n_truth}):") - for i in range(n_truth): - print(f" Seg {i}: truth={truth_params[i]} init={np.array(init_params[i])}") - if overcomplete: - print(f"Extra segments ({n_seg - n_truth}):") - for i in range(n_truth, n_seg): - print(f" Seg {i}: init={np.array(init_params[i])} (random)") - - # --- Build simulators --- - print("Building simulator...") - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - - # Truth simulator (may differ from optimizer if overcomplete) - if overcomplete: - sim_truth = DetectorSimulator( - detector_config, differentiable=True, n_segments=n_truth) - fwd_truth = sim_truth.build_forward() - else: - sim_truth = None # reuse optimizer sim - - sim_opt = DetectorSimulator( - detector_config, differentiable=True, n_segments=n_seg) - fwd_opt = sim_opt.build_forward() - - if not overcomplete: - fwd_truth = fwd_opt - - # --- Generate target signals and pointclouds --- - truth_seg = SegmentData( - positions_mm=jnp.array(truth_params[:, :3]), - de=jnp.array(truth_params[:, 3]), - ) - target_signals = fwd_truth(truth_seg) - key = jax.random.PRNGKey(42) - - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_clouds[p] = (pts, w) - - # --- Build loss (uses optimizer's forward) --- - loss_fn = build_loss_fn(fwd_opt, target_clouds, key) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # --- Optimizer (exponential decay: 0.3 → ~0.005 over total_steps) --- - schedule = optax.exponential_decay( - init_value=LR_POSITION, transition_steps=1, decay_rate=0.9995) - optimizer = optax.adam(schedule, b1=B1, b2=B2) - - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - # Gradient EMA per segment (diagnostic) - grad_ema = jnp.zeros(n_seg) - - # JIT warmup - print("Warming up JIT...") - _ = grad_fn(params) - print("JIT warm-up done.") - - # Logging - losses = [] - param_history = [] - dead_counts = [] - relocation_steps = [] # (step, n_relocated) - cumulative_relocs = 0 - print_every = max(20, total_steps // 30) - - t0 = time.time() - - for step in range(total_steps): - # --- 1. Forward + backward (reconstruction loss only) --- - (total_loss, _), grads = grad_fn(params) - - # --- 2. Adam update with slower energy LR --- - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(LR_ENERGY_MULT) - params = optax.apply_updates(params, updates) - - # --- 3. Energy floor (always enforced) --- - params = params.at[:, 3].set(jnp.maximum(params[:, 3], MIN_ENERGY)) - - # --- 3b. Decoupled L1 energy drain (fixed rate) --- - if enable_l1 and step >= WARMUP: - params = params.at[:, 3].add(-LR_L1) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], MIN_ENERGY)) - - # --- 4. Noise on positions (quadratic LR coupling: ∝ lr²) --- - if enable_noise: - lr_current = float(schedule(step)) - noise_scale = (lr_current ** 2 / LR_POSITION) * NOISE_LR - rng_key, noise_key = jax.random.split(rng_key) - noise_vec = jax.random.normal(noise_key, shape=(n_seg, 3)) - params = params.at[:, :3].add(noise_scale * noise_vec) - - # --- 5. Track gradient EMA (diagnostic) --- - grad_pos_norm = jnp.linalg.norm(grads[:, :3], axis=-1) - grad_ema = GRAD_EMA_BETA * grad_ema + (1 - GRAD_EMA_BETA) * grad_pos_norm - - # --- 6. Relocation — continuous check every step --- - n_dead = int(jnp.sum(params[:, 3] <= DEATH_THRESH)) - if (enable_relocation and step >= WARMUP and n_dead > 0): - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key) - if n_reloc > 0: - cumulative_relocs += n_reloc - relocation_steps.append((step, n_reloc)) - - # --- 7. Log --- - loss_val = float(total_loss) - losses.append(loss_val) - param_history.append(np.array(params)) - dead_counts.append(n_dead) - - if step % print_every == 0 or step == total_steps - 1: - energies_str = ", ".join(f"{float(params[i, 3]):.4f}" for i in range(n_seg)) - print(f" Step {step:4d}: loss={loss_val:.6f} " - f"dead={n_dead} E=[{energies_str}]") - if step % (print_every * 3) == 0: - ema_str_sci = ", ".join( - f"{float(grad_ema[i]):.2e}" for i in range(n_seg)) - print(f" grad_ema=[{ema_str_sci}]") - - elapsed = time.time() - t0 - print(f"\nTraining complete in {elapsed:.1f}s " - f"({elapsed / total_steps * 1000:.1f} ms/step)") - - # --- Match segments to truth --- - final = np.array(params) - param_history = np.array(param_history) - assignment, errors, matched_idx = best_permutation(final, truth_params) - - print(f"\nResults (matched to {n_truth} truth segments):") - for i in matched_idx: - e = errors[i] - print(f" Seg {i}: x={e[0]:+.3f} mm, y={e[1]:+.3f} mm, " - f"z={e[2]:+.3f} mm, dE={e[3]*1000:+.1f} keV") - matched_errors = errors[matched_idx] - max_pos = np.max(np.abs(matched_errors[:, :3])) - mean_pos = np.mean(np.sqrt(np.sum(matched_errors[:, :3] ** 2, axis=1))) - max_de = np.max(np.abs(matched_errors[:, 3])) * 1000 - print(f" Max position error: {max_pos:.3f} mm") - print(f" Mean position error: {mean_pos:.3f} mm") - print(f" Max dE error: {max_de:.1f} keV") - - if overcomplete: - extra_idx = [i for i in range(n_seg) if i not in matched_idx] - extra_energies = [float(final[i, 3]) for i in extra_idx] - print(f"\n Extra segments ({len(extra_idx)}): " - f"energies={[f'{e:.4f}' for e in extra_energies]}") - n_extra_dead = sum(1 for e in extra_energies if e <= DEATH_THRESH) - print(f" Extra dead: {n_extra_dead}/{len(extra_idx)}") - - print(f" Total relocations: {cumulative_relocs}") - - # Plot - _plot_sgld_closure(n_seg, n_truth, total_steps, mode, np.array(losses), - param_history, assignment, matched_idx, - np.array(dead_counts), relocation_steps) - - return errors, matched_idx - - -# ============================================================================= -# Plotting (2x2 diagnostic panels) -# ============================================================================= - -def _plot_sgld_closure(n_seg, n_truth, total_steps, mode, losses, param_history, - assignment, matched_idx, dead_counts, relocation_steps): - seg_colors = plt.cm.tab10(np.linspace(0, 1, max(n_seg, 3))) - fig, axes = plt.subplots(2, 2, figsize=(16, 12)) - extra_idx = [i for i in range(n_seg) if i not in matched_idx] - - LABEL_SIZE = 13 - TITLE_SIZE = 14 - TICK_SIZE = 11 - LEGEND_SIZE = 10 - - # --- Top-left: loss curve --- - ax = axes[0, 0] - ax.semilogy(losses, 'b-', lw=1.0, alpha=0.7, label='SW loss') - if mode != 'baseline': - ax.axvline(WARMUP, color='gray', ls='--', lw=0.8, alpha=0.5, - label=f'Warmup={WARMUP}') - for rs, nr in relocation_steps: - ax.axvline(rs, color='red', ls=':', lw=0.5, alpha=0.3) - ax.set_xlabel('Step', fontsize=LABEL_SIZE) - ax.set_ylabel('Loss', fontsize=LABEL_SIZE) - ax.set_title('Loss Convergence (red = relocation)', fontsize=TITLE_SIZE) - ax.legend(fontsize=LEGEND_SIZE) - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3) - - # --- Top-right: position error per matched segment --- - ax = axes[0, 1] - for s in matched_idx: - pos_err = np.sqrt(np.sum( - (param_history[:, s, :3] - assignment[s, :3]) ** 2, axis=1)) - ax.plot(pos_err, color=seg_colors[s], lw=1.0, label=f'Seg {s}') - ax.axhline(0, color='k', ls='--', lw=0.8) - ax.set_xlabel('Step', fontsize=LABEL_SIZE) - ax.set_ylabel('||pos error|| (mm)', fontsize=LABEL_SIZE) - ax.set_title(f'Position Error (matched {n_truth} segments)', fontsize=TITLE_SIZE) - ax.legend(fontsize=LEGEND_SIZE - 2, ncol=2) - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3) - - # --- Bottom-left: total energy + per-segment energy --- - ax = axes[1, 0] - total_e = param_history[:, :, 3].sum(axis=1) * 1000 # keV - truth_total_e = sum(assignment[s, 3] for s in matched_idx) * 1000 - ax.plot(total_e, 'k-', lw=2.0, alpha=0.8, label='Total energy') - ax.axhline(truth_total_e, color='k', ls=':', lw=1.5, alpha=0.5, - label=f'Truth total={truth_total_e:.0f} keV') - for s in range(n_seg): - is_extra = s in extra_idx - ls = '--' if is_extra else '-' - ax.plot(param_history[:, s, 3] * 1000, color=seg_colors[s], - lw=0.6, ls=ls, alpha=0.4) - ax.set_xlabel('Step', fontsize=LABEL_SIZE) - ax.set_ylabel('Energy (keV)', fontsize=LABEL_SIZE) - ax.set_title('Energy (total=black, segments=thin)', fontsize=TITLE_SIZE) - ax.legend(fontsize=LEGEND_SIZE, loc='upper right') - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3) - - # --- Bottom-right: per-segment energy trajectories (detailed) --- - ax = axes[1, 1] - for s in range(n_seg): - is_extra = s in extra_idx - ls = '--' if is_extra else '-' - alpha_val = 0.5 if is_extra else 1.0 - lbl = f'Seg {s}' + (' (extra)' if is_extra else '') - ax.plot(param_history[:, s, 3] * 1000, color=seg_colors[s], - lw=1.0, ls=ls, alpha=alpha_val, label=lbl) - if not is_extra: - ax.axhline(assignment[s, 3] * 1000, color=seg_colors[s], - ls=':', lw=0.8, alpha=0.4) - ax.set_xlabel('Step', fontsize=LABEL_SIZE) - ax.set_ylabel('dE (keV)', fontsize=LABEL_SIZE) - ax.set_title('Per-Segment Energy (solid=matched, dashed=extra, dotted=truth)', - fontsize=TITLE_SIZE) - ax.legend(fontsize=LEGEND_SIZE - 3, ncol=2) - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3) - - mode_desc = {'baseline': 'Adam only', 'noise': 'Adam + noise', - 'full': 'Adam + noise + L1 + reloc'}[mode] - oc_str = f' ({n_seg}opt/{n_truth}truth)' if n_seg > n_truth else '' - n_reloc_total = sum(nr for _, nr in relocation_steps) - fig.suptitle( - f'{n_seg}-Seg MCMC Closure [{mode_desc}]{oc_str} | lr={LR_POSITION}, ' - f'lr_l1={LR_L1}, noise={NOISE_LR}, steps={total_steps}, ' - f'relocs={n_reloc_total}', - fontsize=13, fontweight='bold') - fig.tight_layout() - fname = os.path.join( - OUT_DIR, - f'sgld_closure_{n_seg}seg_{n_truth}truth_{mode}.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - -# ============================================================================= -# CLI -# ============================================================================= - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='MCMC closure test') - parser.add_argument('n_seg', type=int, nargs='?', default=5, - help='Number of optimizer segments (default: 5)') - parser.add_argument('--n_truth', type=int, default=None, - help='Number of truth segments (default: same as n_seg)') - parser.add_argument('--steps', type=int, default=TOTAL_STEPS, - help=f'Total optimization steps (default: {TOTAL_STEPS})') - parser.add_argument('--mode', choices=['baseline', 'noise', 'full'], - default='full', - help='Validation mode (default: full)') - args = parser.parse_args() - run_sgld_closure(args.n_seg, n_truth=args.n_truth, - total_steps=args.steps, mode=args.mode) diff --git a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_5truth_full.png b/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_5truth_full.png deleted file mode 100644 index 0f587be..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_5truth_full.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_5truth_full_1.png b/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_5truth_full_1.png deleted file mode 100644 index a21af03..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_5truth_full_1.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_5truth_full_2.png b/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_5truth_full_2.png deleted file mode 100644 index 136c736..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_5truth_full_2.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_baseline.png b/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_baseline.png deleted file mode 100644 index f621c83..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_baseline.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_full.png b/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_full.png deleted file mode 100644 index ca153cf..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_10seg_full.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_5truth_baseline.png b/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_5truth_baseline.png deleted file mode 100644 index 818a9ce..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_5truth_baseline.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_5truth_full.png b/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_5truth_full.png deleted file mode 100644 index d0bb9ea..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_5truth_full.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_baseline.png b/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_baseline.png deleted file mode 100644 index 578e425..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_baseline.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_noise.png b/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_noise.png deleted file mode 100644 index c4f0fbf..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sgld_closure_5seg_noise.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sw_surface_dE.png b/closure/archive/closure_analysis_original/closure_analysis/sw_surface_dE.png deleted file mode 100644 index 3fc2a57..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sw_surface_dE.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sw_surface_x.png b/closure/archive/closure_analysis_original/closure_analysis/sw_surface_x.png deleted file mode 100644 index 9c615ba..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sw_surface_x.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sw_surface_y.png b/closure/archive/closure_analysis_original/closure_analysis/sw_surface_y.png deleted file mode 100644 index 2afd03f..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sw_surface_y.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sw_surface_z.png b/closure/archive/closure_analysis_original/closure_analysis/sw_surface_z.png deleted file mode 100644 index ad2f8e5..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sw_surface_z.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k.py b/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k.py deleted file mode 100644 index 2143572..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k.py +++ /dev/null @@ -1,182 +0,0 @@ -""" -Study how SW loss and gradients change with K (number of top-k points). - -Uses K=3000 as the high-K reference (~all active pixels), then compares -lower K values. Sweeps x, y, z independently. - -Generates 3 figures: sw_vary_k_x.png, sw_vary_k_y.png, sw_vary_k_z.png - -Run from project root: - python3 closure_analysis/sw_vary_k.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit - -PLANES = [0, 1, 2] -N_PROJ = 200 - -# K values: well above active pixel count (~3180) down to sparse -K_VALUES = [10000, 5000, 3000, 1000, 500, 200] -K_REF = K_VALUES[0] - -print("Loading detector config...") -detector_config = generate_detector('config/cubic_wireplane_config.yaml') -sim = DetectorSimulator(detector_config, differentiable=True, n_segments=1) -forward = sim.build_forward() - -truth_pos = np.array([-100.0, 50.0, 100.0]) -truth_seg = SegmentData(positions_mm=jnp.array([truth_pos]), de=jnp.array([1.0])) -target_signals = forward(truth_seg) -key = jax.random.PRNGKey(42) - -# Check active pixel count -n_active = int(jnp.sum(jnp.abs(target_signals[2]) > 0)) -print(f"Active pixels (Y plane): {n_active}") - -# Pre-compute targets for each (plane, K) -target_cache = {} -for K in K_VALUES: - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_cache[(p, K)] = (pts, w) - -out_dir = os.path.dirname(os.path.abspath(__file__)) - -sweep_configs = { - 'x': {'idx': 0, 'range': (-195, -5), 'n': 60}, - 'y': {'idx': 1, 'range': (-150, 250), 'n': 60}, - 'z': {'idx': 2, 'range': (-100, 300), 'n': 60}, -} - - -def make_sw_loss(axis_idx, K): - """Build SW loss varying one coordinate with a specific K.""" - def sw_loss(val): - pos = jnp.array([truth_pos]).at[0, axis_idx].set(val) - seg = SegmentData(positions_mm=pos, de=jnp.array([1.0])) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - tgt_pts, tgt_w = target_cache[(p, K)] - loss = loss + sliced_wasserstein_loss_jit( - pts, w, tgt_pts, tgt_w, key, n_projections=N_PROJ - ) - return loss - return sw_loss - - -# ── Warm up JIT ────────────────────────────────────────────────────────────── -print("Warming up JIT...") -for K in K_VALUES: - fn = make_sw_loss(0, K) - _ = fn(truth_pos[0] - 30.0) - _ = jax.grad(fn)(truth_pos[0] - 30.0) -print("Ready.\n") - -# ── Compute for each axis ──────────────────────────────────────────────────── - -colors = plt.cm.viridis(np.linspace(0.1, 0.9, len(K_VALUES))) - -for axis_name, cfg in sweep_configs.items(): - axis_idx = cfg['idx'] - lo, hi = cfg['range'] - n = cfg['n'] - truth_val = truth_pos[axis_idx] - x_vals = np.linspace(lo, hi, n) - - print(f"--- Axis {axis_name} (truth={truth_val}) ---") - - all_losses = {} - all_ad_grads = {} - - for ki, K in enumerate(K_VALUES): - sw_fn = make_sw_loss(axis_idx, K) - sw_grad_fn = jax.grad(sw_fn) - - print(f" K={K}: computing losses...") - losses = np.array([float(sw_fn(float(v))) for v in x_vals]) - print(f" K={K}: computing gradients...") - grads = np.array([float(sw_grad_fn(float(v))) for v in x_vals]) - - all_losses[K] = losses - all_ad_grads[K] = grads - - # ── Figure: 2x2 (loss, gradient, loss diff from ref, gradient diff) ── - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - - # Top-left: loss landscape for each K - for ki, K in enumerate(K_VALUES): - label = f'K={K}' + (' (ref)' if K == K_REF else '') - lw = 2.0 if K == K_REF else 1.2 - axes[0, 0].plot(x_vals, all_losses[K] * 1e6, color=colors[ki], lw=lw, label=label) - axes[0, 0].axvline(truth_val, color='green', ls='--', lw=2, alpha=0.7) - axes[0, 0].set_xlabel(f'{axis_name} (mm)') - axes[0, 0].set_ylabel('SW Loss (x10^-6)') - axes[0, 0].set_title('Loss Landscape') - axes[0, 0].legend(fontsize=9) - axes[0, 0].grid(True, alpha=0.3) - - # Top-right: gradient for each K - for ki, K in enumerate(K_VALUES): - label = f'K={K}' + (' (ref)' if K == K_REF else '') - lw = 2.0 if K == K_REF else 1.2 - axes[0, 1].plot(x_vals, all_ad_grads[K], color=colors[ki], lw=lw, label=label) - axes[0, 1].axhline(0, color='k', ls='-', lw=0.5) - axes[0, 1].axvline(truth_val, color='green', ls='--', lw=2, alpha=0.7) - axes[0, 1].set_xlabel(f'{axis_name} (mm)') - axes[0, 1].set_ylabel(f'dSW/d{axis_name}') - axes[0, 1].set_title('Gradient (Autodiff)') - axes[0, 1].legend(fontsize=9) - axes[0, 1].grid(True, alpha=0.3) - - # Bottom-left: loss difference relative to K_REF - ref_losses = all_losses[K_REF] - for ki, K in enumerate(K_VALUES): - if K == K_REF: - continue - diff = (all_losses[K] - ref_losses) * 1e6 - axes[1, 0].plot(x_vals, diff, color=colors[ki], lw=1.2, label=f'K={K} - K={K_REF}') - axes[1, 0].axhline(0, color='k', ls='-', lw=0.5) - axes[1, 0].axvline(truth_val, color='green', ls='--', lw=2, alpha=0.7) - axes[1, 0].set_xlabel(f'{axis_name} (mm)') - axes[1, 0].set_ylabel('Loss Diff (x10^-6)') - axes[1, 0].set_title(f'Loss Difference from K={K_REF}') - axes[1, 0].legend(fontsize=9) - axes[1, 0].grid(True, alpha=0.3) - - # Bottom-right: gradient difference relative to K_REF - ref_grads = all_ad_grads[K_REF] - for ki, K in enumerate(K_VALUES): - if K == K_REF: - continue - diff = all_ad_grads[K] - ref_grads - axes[1, 1].plot(x_vals, diff, color=colors[ki], lw=1.2, label=f'K={K} - K={K_REF}') - axes[1, 1].axhline(0, color='k', ls='-', lw=0.5) - axes[1, 1].axvline(truth_val, color='green', ls='--', lw=2, alpha=0.7) - axes[1, 1].set_xlabel(f'{axis_name} (mm)') - axes[1, 1].set_ylabel(f'Gradient Diff') - axes[1, 1].set_title(f'Gradient Difference from K={K_REF}') - axes[1, 1].legend(fontsize=9) - axes[1, 1].grid(True, alpha=0.3) - - fig.suptitle(f'SW Loss vs K — varying {axis_name} (U+V+Y planes)', fontsize=14, fontweight='bold') - fig.tight_layout() - fname = f'sw_vary_k_{axis_name}.png' - fig.savefig(os.path.join(out_dir, fname), dpi=150) - plt.close(fig) - print(f" Saved {fname}") - -print("\nDone!") diff --git a/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k_x.png b/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k_x.png deleted file mode 100644 index 0092053..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k_x.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k_y.png b/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k_y.png deleted file mode 100644 index 901a052..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k_y.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k_z.png b/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k_z.png deleted file mode 100644 index 6faf4c6..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/sw_vary_k_z.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/sweep_5seg.py b/closure/archive/closure_analysis_original/closure_analysis/sweep_5seg.py deleted file mode 100644 index f32002f..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/sweep_5seg.py +++ /dev/null @@ -1,357 +0,0 @@ -""" -Sweep script for 5-seg = 5-truth Adam+noise optimization. - -Finds optimal schedule, LR, and noise configuration before introducing -L1/relocation for the overcomplete case. - -Run from project root: - python3 closure_analysis/sweep_5seg.py [--steps 1000] -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import optax - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit - -from closure_analysis.sgld_closure import ( - TRUTH_BANK, INIT_OFFSET, PLANES, K, N_PROJ, - build_loss_fn, best_permutation, -) - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -N_SEG = 5 -N_TRUTH = 5 -MIN_ENERGY = 0.001 - - -def run_config(config, grad_fn, schedule_fn, total_steps): - """Run a single config, return results dict.""" - name = config['name'] - lr = config['lr'] - lr_e_mult = config.get('lr_e_mult', 0.03) - noise_lr = config.get('noise_lr', 0.0) - noise_coupling = config.get('noise_coupling', 'linear') - b1 = config.get('b1', 0.9) - b2 = config.get('b2', 0.999) - - # Build schedule - sched_type = config['schedule'] - if sched_type == 'cosine': - alpha = config.get('cosine_alpha', 0.01) - schedule = optax.cosine_decay_schedule( - init_value=lr, decay_steps=total_steps, alpha=alpha) - elif sched_type == 'exp': - decay_rate = config['decay_rate'] - schedule = optax.exponential_decay( - init_value=lr, transition_steps=1, decay_rate=decay_rate) - elif sched_type == 'constant': - schedule = optax.constant_schedule(lr) - elif sched_type == 'warmup_exp': - warmup_steps = config.get('warmup_steps', 100) - decay_rate = config['decay_rate'] - warmup = optax.linear_schedule( - init_value=lr * 0.01, end_value=lr, - transition_steps=warmup_steps) - decay = optax.exponential_decay( - init_value=lr, transition_steps=1, decay_rate=decay_rate) - schedule = optax.join_schedules( - [warmup, decay], boundaries=[warmup_steps]) - else: - raise ValueError(f"Unknown schedule: {sched_type}") - - optimizer = optax.adam(schedule, b1=b1, b2=b2) - - # Init params: truth + offset - truth_params = TRUTH_BANK[:N_TRUTH] - init_params = jnp.array(truth_params + INIT_OFFSET) - - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - losses = [] - param_history = [] - - for step in range(total_steps): - (loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(lr_e_mult) - params = optax.apply_updates(params, updates) - - # Energy floor - params = params.at[:, 3].set(jnp.maximum(params[:, 3], MIN_ENERGY)) - - # Noise on positions - if noise_lr > 0: - lr_current = float(schedule(step)) - if noise_coupling == 'quadratic': - noise_scale = (lr_current ** 2 / lr) * noise_lr - else: # linear - noise_scale = lr_current * noise_lr - rng_key, noise_key = jax.random.split(rng_key) - noise_vec = jax.random.normal(noise_key, shape=(N_SEG, 3)) - params = params.at[:, :3].add(noise_scale * noise_vec) - - losses.append(float(loss)) - param_history.append(np.array(params)) - - # Evaluate - final = np.array(params) - param_history = np.array(param_history) - assignment, errors, matched_idx = best_permutation(final, truth_params) - matched_errors = errors[matched_idx] - - mean_pos = np.mean(np.sqrt(np.sum(matched_errors[:, :3] ** 2, axis=1))) - max_pos = np.max(np.sqrt(np.sum(matched_errors[:, :3] ** 2, axis=1))) - max_de = np.max(np.abs(matched_errors[:, 3])) * 1000 - mean_de = np.mean(np.abs(matched_errors[:, 3])) * 1000 - final_loss = losses[-1] - - # Find step where mean_pos first < 3mm (convergence speed) - step_3mm = total_steps # default: never - for s in range(0, total_steps, 10): - ph = param_history[s] - _, errs, midx = best_permutation(ph, truth_params) - mp = np.mean(np.sqrt(np.sum(errs[midx, :3] ** 2, axis=1))) - if mp < 3.0: - step_3mm = s - break - - return { - 'name': name, - 'loss': final_loss, - 'mean_pos': mean_pos, - 'max_pos': max_pos, - 'mean_de': mean_de, - 'max_de': max_de, - 'step_3mm': step_3mm, - 'losses': losses, - 'param_history': param_history, - 'assignment': assignment, - 'matched_idx': matched_idx, - } - - -def main(): - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('--steps', type=int, default=1000) - args = parser.parse_args() - total_steps = args.steps - - # ========================================================================= - # Config grid — focused on the most informative comparisons - # ========================================================================= - configs = [ - # --- Group 1: Schedule comparison at LR=0.3, no noise --- - {'name': 'cosine_0.3', 'schedule': 'cosine', 'lr': 0.3, 'lr_e_mult': 0.03, 'noise_lr': 0}, - {'name': 'exp999_0.3', 'schedule': 'exp', 'lr': 0.3, 'decay_rate': 0.999, 'lr_e_mult': 0.03, 'noise_lr': 0}, - {'name': 'exp9995_0.3', 'schedule': 'exp', 'lr': 0.3, 'decay_rate': 0.9995, 'lr_e_mult': 0.03, 'noise_lr': 0}, - {'name': 'const_0.3', 'schedule': 'constant', 'lr': 0.3, 'lr_e_mult': 0.03, 'noise_lr': 0}, - - # --- Group 2: LR sweep with exp d=0.9995, no noise --- - {'name': 'exp9995_0.5', 'schedule': 'exp', 'lr': 0.5, 'decay_rate': 0.9995, 'lr_e_mult': 0.01, 'noise_lr': 0}, - {'name': 'exp9995_0.7', 'schedule': 'exp', 'lr': 0.7, 'decay_rate': 0.9995, 'lr_e_mult': 0.01, 'noise_lr': 0}, - {'name': 'exp9995_1.0', 'schedule': 'exp', 'lr': 1.0, 'decay_rate': 0.9995, 'lr_e_mult': 0.01, 'noise_lr': 0}, - - # --- Group 3: Decay rate sweep at LR=0.5, no noise --- - {'name': 'exp999_0.5', 'schedule': 'exp', 'lr': 0.5, 'decay_rate': 0.999, 'lr_e_mult': 0.01, 'noise_lr': 0}, - {'name': 'exp9998_0.5', 'schedule': 'exp', 'lr': 0.5, 'decay_rate': 0.9998, 'lr_e_mult': 0.01, 'noise_lr': 0}, - - # --- Group 4: Noise sweep on best no-noise config --- - {'name': 'exp9995_0.5_n2q', 'schedule': 'exp', 'lr': 0.5, 'decay_rate': 0.9995, 'lr_e_mult': 0.01, - 'noise_lr': 2, 'noise_coupling': 'quadratic'}, - {'name': 'exp9995_0.5_n5q', 'schedule': 'exp', 'lr': 0.5, 'decay_rate': 0.9995, 'lr_e_mult': 0.01, - 'noise_lr': 5, 'noise_coupling': 'quadratic'}, - {'name': 'exp9995_0.5_n5l', 'schedule': 'exp', 'lr': 0.5, 'decay_rate': 0.9995, 'lr_e_mult': 0.01, - 'noise_lr': 5, 'noise_coupling': 'linear'}, - {'name': 'exp9995_0.5_n8q', 'schedule': 'exp', 'lr': 0.5, 'decay_rate': 0.9995, 'lr_e_mult': 0.01, - 'noise_lr': 8, 'noise_coupling': 'quadratic'}, - - # --- Group 5: LR_energy_mult comparison --- - {'name': 'exp9995_0.5_e03', 'schedule': 'exp', 'lr': 0.5, 'decay_rate': 0.9995, 'lr_e_mult': 0.03, 'noise_lr': 0}, - {'name': 'exp9995_0.5_e10', 'schedule': 'exp', 'lr': 0.5, 'decay_rate': 0.9995, 'lr_e_mult': 0.10, 'noise_lr': 0}, - - # --- Group 6: b1 comparison --- - {'name': 'exp9995_0.5_b09', 'schedule': 'exp', 'lr': 0.5, 'decay_rate': 0.9995, 'lr_e_mult': 0.01, 'noise_lr': 0, 'b1': 0.9}, - - # --- Group 7: warmup + exp --- - {'name': 'warmexp_0.5', 'schedule': 'warmup_exp', 'lr': 0.5, 'decay_rate': 0.9995, - 'warmup_steps': 50, 'lr_e_mult': 0.01, 'noise_lr': 0}, - ] - - print(f"Running {len(configs)} configs, {total_steps} steps each, 5-seg = 5-truth") - print(f"Init offset: {INIT_OFFSET[:3]} mm, dE offset: {INIT_OFFSET[3]} MeV") - print(f"Init distance: {np.linalg.norm(INIT_OFFSET[:3]):.1f} mm") - print() - - # --- Build simulator (shared across all configs) --- - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEG) - fwd = sim.build_forward() - - # Target signals - truth_params = TRUTH_BANK[:N_TRUTH] - truth_seg = SegmentData( - positions_mm=jnp.array(truth_params[:, :3]), - de=jnp.array(truth_params[:, 3]), - ) - target_signals = fwd(truth_seg) - key = jax.random.PRNGKey(42) - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_clouds[p] = (pts, w) - - loss_fn = build_loss_fn(fwd, target_clouds, key) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # JIT warmup - print("Warming up JIT...") - init_params = jnp.array(truth_params + INIT_OFFSET) - _ = grad_fn(init_params) - print("JIT ready.\n") - - # --- Run all configs --- - results = [] - for i, cfg in enumerate(configs): - t0 = time.time() - print(f"[{i+1}/{len(configs)}] {cfg['name']}...", end=' ', flush=True) - res = run_config(cfg, grad_fn, None, total_steps) - elapsed = time.time() - t0 - print(f"pos={res['mean_pos']:.2f}mm, loss={res['loss']:.6f}, " - f"step<3mm={res['step_3mm']}, {elapsed:.1f}s") - results.append(res) - - # ========================================================================= - # Summary table - # ========================================================================= - print(f"\n{'=' * 100}") - print(f"RESULTS SUMMARY — 5-seg, 5-truth, {total_steps} steps") - print(f"{'=' * 100}") - print(f"{'#':>2s} {'Name':<24s} {'Loss':>8s} {'Pos(mm)':>8s} {'MaxPos':>8s} " - f"{'dE(keV)':>8s} {'MaxdE':>8s} {'Step<3mm':>8s}") - print(f"{'--':>2s} {'----':<24s} {'--------':>8s} {'--------':>8s} {'--------':>8s} " - f"{'--------':>8s} {'--------':>8s} {'--------':>8s}") - - for i, r in enumerate(results): - s3 = f"{r['step_3mm']}" if r['step_3mm'] < total_steps else ">1000" - print(f"{i+1:2d} {r['name']:<24s} {r['loss']:8.6f} {r['mean_pos']:8.2f} " - f"{r['max_pos']:8.2f} {r['mean_de']:8.1f} {r['max_de']:8.1f} {s3:>8s}") - - # Sort by mean_pos - sorted_results = sorted(results, key=lambda r: r['mean_pos']) - print(f"\nTop 5 by position:") - for i, r in enumerate(sorted_results[:5]): - s3 = f"{r['step_3mm']}" if r['step_3mm'] < total_steps else ">1000" - print(f" {i+1}. {r['name']:<24s} pos={r['mean_pos']:.2f}mm " - f"dE={r['max_de']:.1f}keV step<3mm={s3}") - - # Sort by step_3mm (convergence speed) - fast_results = [r for r in results if r['step_3mm'] < total_steps] - if fast_results: - fast_results.sort(key=lambda r: r['step_3mm']) - print(f"\nFastest to <3mm:") - for i, r in enumerate(fast_results[:5]): - print(f" {i+1}. {r['name']:<24s} step<3mm={r['step_3mm']} " - f"final_pos={r['mean_pos']:.2f}mm") - - # ========================================================================= - # Plot: loss curves for all configs - # ========================================================================= - fig, axes = plt.subplots(2, 2, figsize=(16, 12)) - - LABEL_SIZE = 13 - TITLE_SIZE = 14 - TICK_SIZE = 11 - LEGEND_SIZE = 9 - - colors = plt.cm.tab20(np.linspace(0, 1, len(results))) - - # Top-left: all loss curves - ax = axes[0, 0] - for i, r in enumerate(results): - ax.semilogy(r['losses'], color=colors[i], lw=1.0, alpha=0.7, label=r['name']) - ax.set_xlabel('Step', fontsize=LABEL_SIZE) - ax.set_ylabel('Loss', fontsize=LABEL_SIZE) - ax.set_title('Loss Convergence', fontsize=TITLE_SIZE) - ax.legend(fontsize=LEGEND_SIZE - 2, ncol=2, loc='upper right') - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3) - - # Top-right: mean position error over time (top 6 configs) - ax = axes[0, 1] - top6 = sorted_results[:6] - for r in top6: - # Compute position error trajectory - truth = TRUTH_BANK[:N_TRUTH] - pos_errs = [] - for s in range(0, total_steps, max(1, total_steps // 200)): - ph = r['param_history'][s] - _, errs, midx = best_permutation(ph, truth) - mp = np.mean(np.sqrt(np.sum(errs[midx, :3] ** 2, axis=1))) - pos_errs.append((s, mp)) - steps_arr, errs_arr = zip(*pos_errs) - ax.plot(steps_arr, errs_arr, lw=1.5, label=r['name']) - ax.axhline(3.0, color='k', ls='--', lw=0.8, alpha=0.5, label='3mm target') - ax.set_xlabel('Step', fontsize=LABEL_SIZE) - ax.set_ylabel('Mean pos error (mm)', fontsize=LABEL_SIZE) - ax.set_title('Position Convergence (top 6)', fontsize=TITLE_SIZE) - ax.legend(fontsize=LEGEND_SIZE, loc='upper right') - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3) - - # Bottom-left: bar chart of final mean pos - ax = axes[1, 0] - names = [r['name'] for r in sorted_results] - pos_vals = [r['mean_pos'] for r in sorted_results] - bar_colors = ['green' if p < 3 else 'orange' if p < 5 else 'red' for p in pos_vals] - ax.barh(range(len(names)), pos_vals, color=bar_colors, alpha=0.7) - ax.set_yticks(range(len(names))) - ax.set_yticklabels(names, fontsize=TICK_SIZE - 2) - ax.set_xlabel('Mean pos error (mm)', fontsize=LABEL_SIZE) - ax.set_title('Final Position Error (sorted)', fontsize=TITLE_SIZE) - ax.axvline(3.0, color='k', ls='--', lw=0.8, alpha=0.5) - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3, axis='x') - ax.invert_yaxis() - - # Bottom-right: bar chart of convergence speed (step to <3mm) - ax = axes[1, 1] - if fast_results: - fast_names = [r['name'] for r in fast_results] - fast_steps = [r['step_3mm'] for r in fast_results] - ax.barh(range(len(fast_names)), fast_steps, color='steelblue', alpha=0.7) - ax.set_yticks(range(len(fast_names))) - ax.set_yticklabels(fast_names, fontsize=TICK_SIZE - 2) - ax.set_xlabel('Steps to reach <3mm', fontsize=LABEL_SIZE) - ax.set_title('Convergence Speed', fontsize=TITLE_SIZE) - ax.tick_params(labelsize=TICK_SIZE) - ax.grid(True, alpha=0.3, axis='x') - ax.invert_yaxis() - else: - ax.text(0.5, 0.5, 'No config reached <3mm', ha='center', va='center', - fontsize=14, transform=ax.transAxes) - ax.set_title('Convergence Speed', fontsize=TITLE_SIZE) - - fig.suptitle(f'5-Seg Sweep — {total_steps} steps, {len(configs)} configs', - fontsize=15, fontweight='bold') - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'sweep_5seg_{total_steps}steps.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"\nSaved {fname}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/closure_analysis_original/closure_analysis/sweep_5seg_v2.py b/closure/archive/closure_analysis_original/closure_analysis/sweep_5seg_v2.py deleted file mode 100644 index b29a528..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/sweep_5seg_v2.py +++ /dev/null @@ -1,154 +0,0 @@ -""" -Focused sweep: lr_e_mult then noise, at LR=0.7 / exp d=0.9995. -Run: python3 closure_analysis/sweep_5seg_v2.py -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import optax - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit - -from closure_analysis.sgld_closure import ( - TRUTH_BANK, INIT_OFFSET, PLANES, K, N_PROJ, - build_loss_fn, best_permutation, -) - -N_SEG = 5 -N_TRUTH = 5 -MIN_ENERGY = 0.001 -STEPS = 1000 - - -def run_one(grad_fn, lr=0.7, decay_rate=0.9995, lr_e_mult=0.01, - noise_lr=0.0, noise_coupling='quadratic', b1=0.95): - schedule = optax.exponential_decay(init_value=lr, transition_steps=1, decay_rate=decay_rate) - optimizer = optax.adam(schedule, b1=b1, b2=0.999) - - truth_params = TRUTH_BANK[:N_TRUTH] - params = jnp.array(truth_params + INIT_OFFSET) - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - losses = [] - for step in range(STEPS): - (loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(lr_e_mult) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], MIN_ENERGY)) - - if noise_lr > 0: - lr_cur = float(schedule(step)) - if noise_coupling == 'quadratic': - ns = (lr_cur ** 2 / lr) * noise_lr - else: - ns = lr_cur * noise_lr - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add(ns * jax.random.normal(nk, shape=(N_SEG, 3))) - - losses.append(float(loss)) - - final = np.array(params) - _, errors, midx = best_permutation(final, truth_params) - me = errors[midx] - mean_pos = np.mean(np.sqrt(np.sum(me[:, :3]**2, axis=1))) - max_pos = np.max(np.sqrt(np.sum(me[:, :3]**2, axis=1))) - max_de = np.max(np.abs(me[:, 3])) * 1000 - return {'loss': losses[-1], 'mean_pos': mean_pos, 'max_pos': max_pos, 'max_de': max_de} - - -def main(): - # Setup - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEG) - fwd = sim.build_forward() - - truth_params = TRUTH_BANK[:N_TRUTH] - truth_seg = SegmentData(positions_mm=jnp.array(truth_params[:, :3]), de=jnp.array(truth_params[:, 3])) - target_signals = fwd(truth_seg) - key = jax.random.PRNGKey(42) - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_clouds[p] = (pts, w) - - loss_fn = build_loss_fn(fwd, target_clouds, key) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - print("Warming up JIT...") - _ = grad_fn(jnp.array(truth_params + INIT_OFFSET)) - print("Ready.\n") - - # ============================================= - # Round 1: lr_e_mult sweep - # ============================================= - print("=" * 60) - print("ROUND 1: lr_e_mult sweep (LR=0.7, d=0.9995, no noise)") - print("=" * 60) - - e_mults = [0.003, 0.01, 0.03] - best_em = None - best_em_pos = 999 - - for em in e_mults: - t0 = time.time() - r = run_one(grad_fn, lr_e_mult=em) - dt = time.time() - t0 - tag = " <-- BEST" if r['mean_pos'] < best_em_pos else "" - print(f" lr_e_mult={em:<6} pos={r['mean_pos']:.3f}mm max={r['max_pos']:.3f}mm " - f"dE={r['max_de']:.1f}keV loss={r['loss']:.6f} {dt:.0f}s{tag}") - if r['mean_pos'] < best_em_pos: - best_em_pos = r['mean_pos'] - best_em = em - - print(f"\n Winner: lr_e_mult={best_em}\n") - - # ============================================= - # Round 2: noise sweep at best lr_e_mult - # ============================================= - print("=" * 60) - print(f"ROUND 2: noise sweep (LR=0.7, d=0.9995, lr_e_mult={best_em})") - print("=" * 60) - - noise_configs = [ - ('no_noise', 0.0, 'quadratic'), - ('n1_quad', 1.0, 'quadratic'), - ('n2_quad', 2.0, 'quadratic'), - ('n5_quad', 5.0, 'quadratic'), - ('n2_lin', 2.0, 'linear'), - ('n5_lin', 5.0, 'linear'), - ] - - best_noise = None - best_noise_pos = 999 - - for label, nlr, nc in noise_configs: - t0 = time.time() - r = run_one(grad_fn, lr_e_mult=best_em, noise_lr=nlr, noise_coupling=nc) - dt = time.time() - t0 - tag = " <-- BEST" if r['mean_pos'] < best_noise_pos else "" - print(f" {label:<10} pos={r['mean_pos']:.3f}mm max={r['max_pos']:.3f}mm " - f"dE={r['max_de']:.1f}keV loss={r['loss']:.6f} {dt:.0f}s{tag}") - if r['mean_pos'] < best_noise_pos: - best_noise_pos = r['mean_pos'] - best_noise = (nlr, nc) - - print(f"\n Winner: noise_lr={best_noise[0]}, coupling={best_noise[1]}") - print(f"\n{'=' * 60}") - print(f"BEST CONFIG: LR=0.7, d=0.9995, lr_e_mult={best_em}, " - f"noise_lr={best_noise[0]}, coupling={best_noise[1]}") - print(f" -> {best_noise_pos:.3f}mm in {STEPS} steps") - print(f"{'=' * 60}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/closure_analysis_original/closure_analysis/test_l1_drain.py b/closure/archive/closure_analysis_original/closure_analysis/test_l1_drain.py deleted file mode 100644 index 8cc43d1..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/test_l1_drain.py +++ /dev/null @@ -1,109 +0,0 @@ -""" -Overcomplete test: does energy learning rate control the separation? - -Tests LR_ENERGY_MULT = 0.1 vs 0.5 vs 1.0, no L1, 1200 steps. -3 optimizer segments, 2 truths. - -Run: python3 closure_analysis/test_l1_drain.py -""" -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import optax -import time - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit -from closure_analysis.optimization_closure import TRUTH_BANK, INIT_OFFSET - -K = 10000 -N_PROJ = 200 -PLANES = [0, 1, 2] - - -def main(): - n_truth = 2 - n_seg = 3 - truth_params = TRUTH_BANK[:n_truth] - - print("Building simulator...") - config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(config, differentiable=True, n_segments=n_seg) - forward = sim.build_forward() - - truth_padded = np.zeros((n_seg, 4)) - truth_padded[:n_truth] = truth_params - truth_seg = SegmentData( - positions_mm=jnp.array(truth_padded[:, :3]), - de=jnp.array(truth_padded[:, 3]), - ) - target_signals = forward(truth_seg) - key = jax.random.PRNGKey(42) - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_clouds[p] = (pts, w) - - def sw_loss(params): - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + sliced_wasserstein_loss_jit( - pts, w, target_clouds[p][0], target_clouds[p][1], - key, n_projections=N_PROJ) - return loss - - vg_fn = jax.value_and_grad(sw_loss) - - print("Warming up JIT...") - init_params = jnp.array([ - truth_params[0] + INIT_OFFSET, - truth_params[1] + INIT_OFFSET, - [-200.0, 0.0, 300.0, 1.5], - ]) - _ = vg_fn(init_params) - print("Done.") - print(f"\nTruth energies: [{truth_params[0,3]}, {truth_params[1,3]}]") - - n_steps = 1200 - for lr_e_mult in [0.1, 0.5, 1.0]: - schedule = optax.cosine_decay_schedule( - init_value=0.3, decay_steps=n_steps, alpha=0.01) - optimizer = optax.adam(schedule, b1=0.95) - params = init_params.copy() - opt_state = optimizer.init(params) - - print(f"\n--- LR_ENERGY_MULT = {lr_e_mult} ({n_steps} steps, no L1) ---") - print(f" {'Step':>5s} {'Loss':>10s} {'E0':>7s} {'E1':>7s} {'E2(X)':>7s} {'E0-E2':>7s}") - - t0 = time.time() - print_every = max(1, n_steps // 15) - for step in range(n_steps): - loss, grads = vg_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(lr_e_mult) - params = optax.apply_updates(params, updates) - - if step % print_every == 0 or step == n_steps - 1: - e = [float(params[i, 3]) for i in range(n_seg)] - sep = e[0] - e[2] - print(f" {step:>5d} {float(loss):>10.4f} {e[0]:>7.3f} {e[1]:>7.3f} {e[2]:>7.3f} {sep:>+7.3f}") - - final = np.array(params) - print(f" ({time.time()-t0:.1f}s)") - print(f" Final pos seg0: [{final[0,0]:+.1f}, {final[0,1]:+.1f}, {final[0,2]:+.1f}] " - f"(truth: {truth_params[0,:3]})") - print(f" Final pos seg2: [{final[2,0]:+.1f}, {final[2,1]:+.1f}, {final[2,2]:+.1f}] " - f"(EXTRA)") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/closure_analysis_original/closure_analysis/test_loss_gradients.py b/closure/archive/closure_analysis_original/closure_analysis/test_loss_gradients.py deleted file mode 100644 index 727263a..0000000 --- a/closure/archive/closure_analysis_original/closure_analysis/test_loss_gradients.py +++ /dev/null @@ -1,272 +0,0 @@ -""" -Gradient surface test: compare 4 loss variants on the same TPC closure problem. - -Builds one simulation, extracts pointclouds, then evaluates loss + gradients -for each loss variant at the init position. Reports gradient magnitudes -per segment per dimension (x, y, z, dE). - -Loss variants: - 1. OTT SW — random projections, W2 cost (production baseline) - 2. Uniform W1 — fixed directions, |quant_a - quant_b| - 3. Uniform W2 — fixed directions, (quant_a - quant_b)^2 - 4. Uniform Huber — fixed directions, Huber(quant_a - quant_b) - -Run: python3 closure_analysis/test_loss_gradients.py -""" -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import time - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit -from closure_analysis.optimization_closure import TRUTH_BANK, INIT_OFFSET - -K = 10000 -N_PROJ = 200 -PLANES = [0, 1, 2] - - -# ============================================================================= -# Uniform SW factories (W1, W2, Huber) -# ============================================================================= - -def make_uniform_sw_w1(n_proj, n_grid=500): - """Uniform sliced Wasserstein with L1 (absolute) cost.""" - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - wts_a = wts_a / jnp.sum(wts_a) - wts_b = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - quant_a = jnp.interp(grid, cdf_a, proj_a_i[sort_a]) - quant_b = jnp.interp(grid, cdf_b, proj_b_i[sort_b]) - return jnp.mean(jnp.abs(quant_a - quant_b)) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - return sw - - -def make_uniform_sw_w2(n_proj, n_grid=500): - """Uniform sliced Wasserstein with L2 (squared) cost.""" - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - wts_a = wts_a / jnp.sum(wts_a) - wts_b = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - quant_a = jnp.interp(grid, cdf_a, proj_a_i[sort_a]) - quant_b = jnp.interp(grid, cdf_b, proj_b_i[sort_b]) - return jnp.mean((quant_a - quant_b) ** 2) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - return sw - - -def make_uniform_sw_huber(n_proj, delta=0.01, n_grid=500): - """Uniform sliced Wasserstein with Huber cost. - - Huber(x, delta) = 0.5*x^2 if |x| <= delta - delta*(|x| - 0.5*delta) otherwise - - Interpolates between W2 (near zero) and W1 (far from zero). - delta is in the same units as the normalized point coordinates. - """ - angles = jnp.linspace(0, jnp.pi, n_proj, endpoint=False) - directions = jnp.stack([jnp.cos(angles), jnp.sin(angles)], axis=1) - grid = jnp.linspace(1e-6, 1.0 - 1e-6, n_grid) - - @jax.jit - def sw(pts_a, wts_a, pts_b, wts_b): - wts_a = wts_a / jnp.sum(wts_a) - wts_b = wts_b / jnp.sum(wts_b) - proj_a = pts_a @ directions.T - proj_b = pts_b @ directions.T - - def w1d(proj_a_i, proj_b_i): - sort_a = jnp.argsort(proj_a_i) - sort_b = jnp.argsort(proj_b_i) - cdf_a = jnp.cumsum(wts_a[sort_a]) - cdf_b = jnp.cumsum(wts_b[sort_b]) - quant_a = jnp.interp(grid, cdf_a, proj_a_i[sort_a]) - quant_b = jnp.interp(grid, cdf_b, proj_b_i[sort_b]) - diff = quant_a - quant_b - abs_diff = jnp.abs(diff) - huber = jnp.where(abs_diff <= delta, - 0.5 * diff ** 2, - delta * (abs_diff - 0.5 * delta)) - return jnp.mean(huber) - - costs = jax.vmap(w1d)(proj_a.T, proj_b.T) - return jnp.mean(costs) - - return sw - - -# ============================================================================= -# Main test -# ============================================================================= - -def main(): - n_seg = 5 - truth_params = TRUTH_BANK[:n_seg] - - print("Building simulator...") - config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(config, differentiable=True, n_segments=n_seg) - forward = sim.build_forward() - - # Generate target - truth_seg = SegmentData( - positions_mm=jnp.array(truth_params[:, :3]), - de=jnp.array(truth_params[:, 3]), - ) - target_signals = forward(truth_seg) - key = jax.random.PRNGKey(42) - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(target_signals[p], K) - target_clouds[p] = (pts, w) - - # Init params at offset from truth - init_params = jnp.array(truth_params + INIT_OFFSET) - - # Build loss functions — all take params (n_seg, 4) and return scalar - sw_w1 = make_uniform_sw_w1(N_PROJ) - sw_w2 = make_uniform_sw_w2(N_PROJ) - sw_huber = make_uniform_sw_huber(N_PROJ, delta=0.01) - - def make_closure_loss(plane_loss_fn, needs_key=False): - """Wrap a per-plane loss into a full closure loss over 3 planes.""" - def loss_fn(params): - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - sigs = forward(seg) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - tp, tw = target_clouds[p] - if needs_key: - loss = loss + plane_loss_fn(pts, w, tp, tw, key, - n_projections=N_PROJ) - else: - loss = loss + plane_loss_fn(pts, w, tp, tw) - return loss - return loss_fn - - losses = { - 'OTT SW (W2, random)': make_closure_loss(sliced_wasserstein_loss_jit, - needs_key=True), - 'Uniform W1 (abs)': make_closure_loss(sw_w1), - 'Uniform W2 (sq)': make_closure_loss(sw_w2), - 'Uniform Huber': make_closure_loss(sw_huber), - } - - # JIT warmup all grad functions - print("Warming up JIT for all 4 loss variants...") - grad_fns = {} - for name, loss_fn in losses.items(): - vg = jax.value_and_grad(loss_fn) - t0 = time.time() - _ = vg(init_params) - jax.block_until_ready(_[1]) - print(f" {name}: JIT compiled in {time.time()-t0:.1f}s") - grad_fns[name] = vg - - # Evaluate at init - print(f"\n{'='*80}") - print(f"GRADIENT SURFACE TEST — {n_seg} segments at init offset") - print(f"{'='*80}") - print(f"K={K}, N_PROJ={N_PROJ}, INIT_OFFSET={INIT_OFFSET}") - print(f"\nTruth params:") - for i in range(n_seg): - print(f" Seg {i}: x={truth_params[i,0]:+.0f}, y={truth_params[i,1]:+.0f}, " - f"z={truth_params[i,2]:+.0f}, dE={truth_params[i,3]:.1f} MeV") - - for name, vg in grad_fns.items(): - loss, grads = vg(init_params) - jax.block_until_ready(grads) - grads_np = np.array(grads) - - print(f"\n--- {name} ---") - print(f" Loss = {float(loss):.6e}") - print(f" {'Seg':>5s} {'dL/dx':>12s} {'dL/dy':>12s} {'dL/dz':>12s} " - f"{'dL/dE':>12s} {'||grad_pos||':>12s}") - for i in range(n_seg): - gx, gy, gz, ge = grads_np[i] - pos_norm = np.sqrt(gx**2 + gy**2 + gz**2) - print(f" {i:>5d} {gx:>+12.4e} {gy:>+12.4e} {gz:>+12.4e} " - f"{ge:>+12.4e} {pos_norm:>12.4e}") - - # Summary stats - pos_grads = grads_np[:, :3] - e_grads = grads_np[:, 3] - print(f" Position grad: mean |g|={np.mean(np.abs(pos_grads)):.4e}, " - f"max={np.max(np.abs(pos_grads)):.4e}, " - f"min={np.min(np.abs(pos_grads)):.4e}") - print(f" Energy grad: mean |g|={np.mean(np.abs(e_grads)):.4e}, " - f"max={np.max(np.abs(e_grads)):.4e}, " - f"min={np.min(np.abs(e_grads)):.4e}") - print(f" Ratio |dL/dE| / |dL/dpos|: " - f"{np.mean(np.abs(e_grads)) / (np.mean(np.abs(pos_grads)) + 1e-10):.2f}") - - # Also test at near-converged state (truth positions, init energy) - print(f"\n{'='*80}") - print(f"GRADIENT AT NEAR-CONVERGED STATE (truth positions, init energy)") - print(f"{'='*80}") - - near_params = jnp.array(truth_params.copy()) - # Keep truth positions but add energy offset - near_params = near_params.at[:, 3].add(INIT_OFFSET[3]) - - for name, vg in grad_fns.items(): - loss, grads = vg(near_params) - jax.block_until_ready(grads) - grads_np = np.array(grads) - - print(f"\n--- {name} ---") - print(f" Loss = {float(loss):.6e}") - print(f" {'Seg':>5s} {'dL/dx':>12s} {'dL/dy':>12s} {'dL/dz':>12s} " - f"{'dL/dE':>12s} {'||grad_pos||':>12s}") - for i in range(n_seg): - gx, gy, gz, ge = grads_np[i] - pos_norm = np.sqrt(gx**2 + gy**2 + gz**2) - print(f" {i:>5d} {gx:>+12.4e} {gy:>+12.4e} {gz:>+12.4e} " - f"{ge:>+12.4e} {pos_norm:>12.4e}") - - e_grads = grads_np[:, 3] - print(f" Energy grad: mean |g|={np.mean(np.abs(e_grads)):.4e}, " - f"max={np.max(np.abs(e_grads)):.4e}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/closure_analysis_original/closure_analysis/w1_surface_dE.png b/closure/archive/closure_analysis_original/closure_analysis/w1_surface_dE.png deleted file mode 100644 index 924960d..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/w1_surface_dE.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/w1_surface_x.png b/closure/archive/closure_analysis_original/closure_analysis/w1_surface_x.png deleted file mode 100644 index 18a4ec6..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/w1_surface_x.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/w1_surface_y.png b/closure/archive/closure_analysis_original/closure_analysis/w1_surface_y.png deleted file mode 100644 index ef04fed..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/w1_surface_y.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/w1_surface_z.png b/closure/archive/closure_analysis_original/closure_analysis/w1_surface_z.png deleted file mode 100644 index 2c47d83..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/w1_surface_z.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/w2_surface_dE.png b/closure/archive/closure_analysis_original/closure_analysis/w2_surface_dE.png deleted file mode 100644 index c089d86..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/w2_surface_dE.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/w2_surface_x.png b/closure/archive/closure_analysis_original/closure_analysis/w2_surface_x.png deleted file mode 100644 index 4f7aa28..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/w2_surface_x.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/w2_surface_y.png b/closure/archive/closure_analysis_original/closure_analysis/w2_surface_y.png deleted file mode 100644 index 89384e1..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/w2_surface_y.png and /dev/null differ diff --git a/closure/archive/closure_analysis_original/closure_analysis/w2_surface_z.png b/closure/archive/closure_analysis_original/closure_analysis/w2_surface_z.png deleted file mode 100644 index 525e4d2..0000000 Binary files a/closure/archive/closure_analysis_original/closure_analysis/w2_surface_z.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/__init__.py b/closure/archive/gradient_test/gradient_test/__init__.py deleted file mode 100644 index 97f60ad..0000000 --- a/closure/archive/gradient_test/gradient_test/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -JAXTPC Gradient Testing Framework - -This module provides utilities for testing gradients of the TPC simulation -with respect to physics parameters like diffusion and recombination. - -Structure: -- physics_params.py: PhysicsParams container for differentiable parameters -- loss_functions.py: MSE and other loss functions -- gradient_utils.py: Numerical and analytical gradient computation -- visualization.py: Plotting utilities -- run_gradient_test.py: Main test script -- tools/: Modified copy of main tools/ for gradient testing -""" - -from .physics_params import ( - PhysicsParams, - create_default_params, - perturb_param, - scale_param, - get_param_range, - PARAM_INFO, -) - -from .loss_functions import ( - mse_loss_dense, - mse_loss_sparse, - total_charge_loss, - charge_sum_loss, - per_plane_mse_loss, -) - -from .gradient_utils import ( - compute_numerical_gradient, - compute_all_numerical_gradients, - try_analytical_gradient, - compare_gradients, - gradient_check, - loss_landscape_1d, -) diff --git a/closure/archive/gradient_test/gradient_test/gradient_utils.py b/closure/archive/gradient_test/gradient_test/gradient_utils.py deleted file mode 100644 index 8699dab..0000000 --- a/closure/archive/gradient_test/gradient_test/gradient_utils.py +++ /dev/null @@ -1,349 +0,0 @@ -""" -Gradient utilities for testing and comparing gradients. - -This module provides functions for computing analytical and numerical -gradients, and comparing them to assess gradient accuracy. -""" - -import jax -import jax.numpy as jnp -from typing import Callable, Dict, Tuple, Optional, Any -from functools import partial - -try: - from .physics_params import PhysicsParams, PARAM_INFO -except ImportError: - from physics_params import PhysicsParams, PARAM_INFO - - -def compute_numerical_gradient( - loss_fn: Callable, - params: PhysicsParams, - param_name: str, - eps: float = 1e-4, - relative: bool = True, - *args, - **kwargs -) -> float: - """ - Compute numerical gradient using central finite differences. - - Parameters - ---------- - loss_fn : Callable - Loss function that takes PhysicsParams as first argument. - params : PhysicsParams - Current parameter values. - param_name : str - Name of the parameter to differentiate with respect to. - eps : float - Finite difference step size. If relative=True, this is relative - to the parameter value. - relative : bool - If True, use relative step size (eps * |param_value|). - *args, **kwargs - Additional arguments to pass to loss_fn. - - Returns - ------- - float - Numerical gradient estimate. - """ - current_value = getattr(params, param_name) - - # Compute step size - if relative: - step = eps * max(abs(current_value), 1e-8) - else: - step = eps - - # Forward step - params_plus = params._replace(**{param_name: current_value + step}) - loss_plus = loss_fn(params_plus, *args, **kwargs) - - # Backward step - params_minus = params._replace(**{param_name: current_value - step}) - loss_minus = loss_fn(params_minus, *args, **kwargs) - - # Central difference - gradient = (loss_plus - loss_minus) / (2 * step) - - return float(gradient) - - -def compute_all_numerical_gradients( - loss_fn: Callable, - params: PhysicsParams, - eps: float = 1e-4, - param_names: Optional[list] = None, - *args, - **kwargs -) -> Dict[str, float]: - """ - Compute numerical gradients for all (or specified) parameters. - - Parameters - ---------- - loss_fn : Callable - Loss function. - params : PhysicsParams - Current parameters. - eps : float - Finite difference step size. - param_names : list, optional - List of parameter names to compute. If None, computes all. - *args, **kwargs - Additional arguments to loss_fn. - - Returns - ------- - dict - Dictionary of parameter name -> gradient value. - """ - if param_names is None: - param_names = list(params._fields) - - gradients = {} - for name in param_names: - gradients[name] = compute_numerical_gradient( - loss_fn, params, name, eps, *args, **kwargs - ) - - return gradients - - -def try_analytical_gradient( - loss_fn: Callable, - params: PhysicsParams, - *args, - **kwargs -) -> Tuple[Optional[PhysicsParams], Optional[Exception]]: - """ - Try to compute analytical gradient using JAX. - - Parameters - ---------- - loss_fn : Callable - Loss function that takes PhysicsParams as first argument. - params : PhysicsParams - Current parameter values. - *args, **kwargs - Additional arguments to pass to loss_fn. - - Returns - ------- - tuple - (gradients, None) if successful, (None, exception) if failed. - """ - try: - grad_fn = jax.grad(loss_fn) - gradients = grad_fn(params, *args, **kwargs) - return gradients, None - except Exception as e: - return None, e - - -def compare_gradients( - analytical_grads: PhysicsParams, - numerical_grads: Dict[str, float], - param_names: Optional[list] = None, - rtol: float = 1e-2, - atol: float = 1e-6 -) -> Dict[str, Dict]: - """ - Compare analytical and numerical gradients. - - Parameters - ---------- - analytical_grads : PhysicsParams - Analytical gradients from jax.grad. - numerical_grads : dict - Numerical gradients from finite differences. - param_names : list, optional - Parameters to compare. If None, compares all. - rtol : float - Relative tolerance. - atol : float - Absolute tolerance. - - Returns - ------- - dict - Comparison results for each parameter. - """ - if param_names is None: - param_names = list(numerical_grads.keys()) - - results = {} - for name in param_names: - analytical = getattr(analytical_grads, name) - numerical = numerical_grads[name] - - abs_diff = abs(analytical - numerical) - rel_diff = abs_diff / max(abs(numerical), 1e-10) - - is_close = jnp.allclose( - jnp.array([analytical]), - jnp.array([numerical]), - rtol=rtol, - atol=atol - ) - - results[name] = { - 'analytical': float(analytical), - 'numerical': float(numerical), - 'abs_diff': float(abs_diff), - 'rel_diff': float(rel_diff), - 'is_close': bool(is_close), - } - - return results - - -def gradient_check( - loss_fn: Callable, - params: PhysicsParams, - param_names: Optional[list] = None, - eps: float = 1e-4, - rtol: float = 1e-2, - atol: float = 1e-6, - verbose: bool = True, - *args, - **kwargs -) -> Dict: - """ - Comprehensive gradient check comparing analytical and numerical. - - Parameters - ---------- - loss_fn : Callable - Loss function. - params : PhysicsParams - Current parameters. - param_names : list, optional - Parameters to check. - eps : float - Finite difference step size. - rtol, atol : float - Tolerances for comparison. - verbose : bool - Whether to print results. - *args, **kwargs - Additional arguments to loss_fn. - - Returns - ------- - dict - Results including: - - 'analytical_success': bool - - 'analytical_error': Exception or None - - 'numerical_grads': dict - - 'analytical_grads': PhysicsParams or None - - 'comparison': dict or None - """ - if param_names is None: - param_names = ['diffusion_long', 'diffusion_trans', 'recomb_A', 'recomb_B'] - - results = { - 'analytical_success': False, - 'analytical_error': None, - 'numerical_grads': {}, - 'analytical_grads': None, - 'comparison': None, - } - - # Compute numerical gradients first (always works) - if verbose: - print("Computing numerical gradients...") - - results['numerical_grads'] = compute_all_numerical_gradients( - loss_fn, params, eps, param_names, *args, **kwargs - ) - - if verbose: - print("Numerical gradients:") - for name, grad in results['numerical_grads'].items(): - info = PARAM_INFO.get(name, {'name': name, 'units': ''}) - print(f" {info['name']}: {grad:.6e}") - - # Try analytical gradients - if verbose: - print("\nAttempting analytical gradients...") - - analytical_grads, error = try_analytical_gradient( - loss_fn, params, *args, **kwargs - ) - - if error is None: - results['analytical_success'] = True - results['analytical_grads'] = analytical_grads - - if verbose: - print("Analytical gradients computed successfully!") - - # Compare - results['comparison'] = compare_gradients( - analytical_grads, results['numerical_grads'], - param_names, rtol, atol - ) - - if verbose: - print("\nGradient comparison:") - print(f"{'Parameter':<20} {'Analytical':>12} {'Numerical':>12} {'Rel Diff':>10} {'OK?':>5}") - print("-" * 65) - for name, comp in results['comparison'].items(): - ok_str = "YES" if comp['is_close'] else "NO" - print(f"{name:<20} {comp['analytical']:>12.4e} {comp['numerical']:>12.4e} " - f"{comp['rel_diff']:>10.2e} {ok_str:>5}") - - else: - results['analytical_error'] = error - if verbose: - print(f"Analytical gradient failed: {error}") - - return results - - -def loss_landscape_1d( - loss_fn: Callable, - params: PhysicsParams, - param_name: str, - relative_range: float = 0.5, - num_points: int = 21, - *args, - **kwargs -) -> Tuple[jnp.ndarray, jnp.ndarray]: - """ - Compute loss values over a 1D parameter sweep. - - Parameters - ---------- - loss_fn : Callable - Loss function. - params : PhysicsParams - Base parameters. - param_name : str - Parameter to sweep. - relative_range : float - Range as fraction of default value. - num_points : int - Number of points in sweep. - *args, **kwargs - Additional arguments to loss_fn. - - Returns - ------- - tuple - (param_values, loss_values) arrays. - """ - base_value = getattr(params, param_name) - scales = jnp.linspace(1.0 - relative_range, 1.0 + relative_range, num_points) - param_values = base_value * scales - - loss_values = [] - for val in param_values: - test_params = params._replace(**{param_name: float(val)}) - loss = loss_fn(test_params, *args, **kwargs) - loss_values.append(float(loss)) - - return jnp.array(param_values), jnp.array(loss_values) diff --git a/closure/archive/gradient_test/gradient_test/loss_functions.py b/closure/archive/gradient_test/gradient_test/loss_functions.py deleted file mode 100644 index 3f3ee99..0000000 --- a/closure/archive/gradient_test/gradient_test/loss_functions.py +++ /dev/null @@ -1,213 +0,0 @@ -""" -Loss functions for gradient testing. - -This module provides MSE and other loss functions for comparing -simulated wireplane signals to reference signals. -""" - -import jax -import jax.numpy as jnp -from typing import Dict, Tuple, Optional, Union - - -def mse_loss_dense( - predicted: jnp.ndarray, - target: jnp.ndarray, - mask: Optional[jnp.ndarray] = None -) -> float: - """ - Compute Mean Squared Error between predicted and target arrays. - - Parameters - ---------- - predicted : jnp.ndarray - Predicted signal array (num_wires, num_time_steps). - target : jnp.ndarray - Target signal array (num_wires, num_time_steps). - mask : jnp.ndarray, optional - Boolean mask for valid elements. - - Returns - ------- - float - Mean squared error. - """ - diff = predicted - target - if mask is not None: - diff = jnp.where(mask, diff, 0.0) - n_valid = jnp.sum(mask) - return jnp.sum(diff ** 2) / jnp.maximum(n_valid, 1.0) - else: - return jnp.mean(diff ** 2) - - -def mse_loss_sparse( - predicted_indices: jnp.ndarray, - predicted_values: jnp.ndarray, - target_indices: jnp.ndarray, - target_values: jnp.ndarray, - num_wires: int, - num_time_steps: int -) -> float: - """ - Compute MSE from sparse representations by converting to dense. - - This is less efficient but simpler for gradient testing. - - Parameters - ---------- - predicted_indices : jnp.ndarray - Indices of predicted non-zero values (N, 2). - predicted_values : jnp.ndarray - Values at predicted indices (N,). - target_indices : jnp.ndarray - Indices of target non-zero values (M, 2). - target_values : jnp.ndarray - Values at target indices (M,). - num_wires : int - Number of wires. - num_time_steps : int - Number of time steps. - - Returns - ------- - float - Mean squared error. - """ - # Convert to dense - predicted_dense = jnp.zeros((num_wires, num_time_steps)) - if len(predicted_values) > 0: - predicted_dense = predicted_dense.at[ - predicted_indices[:, 0], predicted_indices[:, 1] - ].add(predicted_values) - - target_dense = jnp.zeros((num_wires, num_time_steps)) - if len(target_values) > 0: - target_dense = target_dense.at[ - target_indices[:, 0], target_indices[:, 1] - ].add(target_values) - - return mse_loss_dense(predicted_dense, target_dense) - - -def total_charge_loss( - predicted_charges: jnp.ndarray, - target_charges: jnp.ndarray -) -> float: - """ - Compute loss based on total charge difference. - - This is useful for testing recombination gradients in isolation. - - Parameters - ---------- - predicted_charges : jnp.ndarray - Predicted charge array. - target_charges : jnp.ndarray - Target charge array. - - Returns - ------- - float - Mean squared error of total charge. - """ - pred_total = jnp.sum(predicted_charges) - target_total = jnp.sum(target_charges) - return (pred_total - target_total) ** 2 - - -def normalized_mse_loss( - predicted: jnp.ndarray, - target: jnp.ndarray -) -> float: - """ - Compute normalized MSE (divided by target variance). - - Parameters - ---------- - predicted : jnp.ndarray - Predicted values. - target : jnp.ndarray - Target values. - - Returns - ------- - float - Normalized MSE. - """ - mse = jnp.mean((predicted - target) ** 2) - variance = jnp.var(target) - return mse / jnp.maximum(variance, 1e-10) - - -def per_plane_mse_loss( - predicted_signals: Dict, - target_signals: Dict, - weights: Optional[Dict] = None -) -> float: - """ - Compute weighted MSE loss across all wire planes. - - Parameters - ---------- - predicted_signals : dict - Dictionary of predicted signals keyed by (side_idx, plane_idx). - target_signals : dict - Dictionary of target signals with same keys. - weights : dict, optional - Per-plane weights. If None, equal weights are used. - - Returns - ------- - float - Total weighted MSE loss. - """ - total_loss = 0.0 - n_planes = 0 - - for key in predicted_signals: - if key in target_signals: - pred = predicted_signals[key] - target = target_signals[key] - - # Handle sparse format (tuple of indices, values) - if isinstance(pred, tuple) and len(pred) == 2: - # For now, just sum the values for a simple loss - pred_sum = jnp.sum(pred[1]) - target_sum = jnp.sum(target[1]) - plane_loss = (pred_sum - target_sum) ** 2 - else: - plane_loss = mse_loss_dense(pred, target) - - weight = 1.0 - if weights is not None and key in weights: - weight = weights[key] - - total_loss += weight * plane_loss - n_planes += 1 - - if n_planes > 0: - total_loss = total_loss / n_planes - - return total_loss - - -def charge_sum_loss(charges: jnp.ndarray, target_sum: float) -> float: - """ - Simple loss based on sum of charges. - - Useful for isolated recombination testing. - - Parameters - ---------- - charges : jnp.ndarray - Charge array. - target_sum : float - Target sum of charges. - - Returns - ------- - float - Squared difference from target. - """ - return (jnp.sum(charges) - target_sum) ** 2 diff --git a/closure/archive/gradient_test/gradient_test/physics_params.py b/closure/archive/gradient_test/gradient_test/physics_params.py deleted file mode 100644 index 08feace..0000000 --- a/closure/archive/gradient_test/gradient_test/physics_params.py +++ /dev/null @@ -1,193 +0,0 @@ -""" -Physics parameters container for gradient testing. - -This module defines a PhysicsParams container that holds the physics -parameters we want to test gradients for. The parameters are stored -as JAX-compatible values for differentiation. -""" - -from typing import NamedTuple -import jax.numpy as jnp - - -class PhysicsParams(NamedTuple): - """ - Container for physics parameters used in gradient testing. - - All parameters are stored as floats for JAX compatibility. - This is a NamedTuple which is automatically a valid JAX pytree. - """ - # Diffusion parameters (in cm²/μs) - diffusion_long: float # Longitudinal diffusion coefficient - diffusion_trans: float # Transverse diffusion coefficient - - # Recombination parameters (dimensionless) - recomb_A: float # Box model A parameter - recomb_B: float # Box model B parameter - - # Medium/field parameters (for future expansion) - field_strength: float # V/cm - density: float # g/cm³ - w_value: float # eV (ionization energy) - - -def create_default_params() -> PhysicsParams: - """ - Create PhysicsParams with default values from the detector config. - - These are the default values from cubic_wireplane_config.yaml. - - Returns - ------- - PhysicsParams - Default physics parameters. - """ - return PhysicsParams( - # Diffusion: 6.2 cm²/s and 16.3 cm²/s converted to cm²/μs - diffusion_long=6.2e-6, # 6.2 cm²/s = 6.2e-6 cm²/μs - diffusion_trans=16.3e-6, # 16.3 cm²/s = 16.3e-6 cm²/μs - - # Recombination - recomb_A=0.8, - recomb_B=0.3, - - # Medium/field - field_strength=500.0, # V/cm - density=1.396, # g/cm³ - w_value=23.6, # eV - ) - - -def perturb_param( - params: PhysicsParams, - param_name: str, - delta: float -) -> PhysicsParams: - """ - Create a new PhysicsParams with one parameter perturbed. - - Parameters - ---------- - params : PhysicsParams - Original parameters. - param_name : str - Name of the parameter to perturb. - delta : float - Amount to add to the parameter value. - - Returns - ------- - PhysicsParams - New parameters with the specified field perturbed. - """ - current_value = getattr(params, param_name) - new_value = current_value + delta - return params._replace(**{param_name: new_value}) - - -def scale_param( - params: PhysicsParams, - param_name: str, - scale: float -) -> PhysicsParams: - """ - Create a new PhysicsParams with one parameter scaled. - - Parameters - ---------- - params : PhysicsParams - Original parameters. - param_name : str - Name of the parameter to scale. - scale : float - Multiplicative factor. - - Returns - ------- - PhysicsParams - New parameters with the specified field scaled. - """ - current_value = getattr(params, param_name) - new_value = current_value * scale - return params._replace(**{param_name: new_value}) - - -def get_param_range( - params: PhysicsParams, - param_name: str, - relative_range: float = 0.5, - num_points: int = 21 -) -> tuple: - """ - Generate a range of values for parameter sweeps. - - Parameters - ---------- - params : PhysicsParams - Base parameters. - param_name : str - Name of the parameter to sweep. - relative_range : float - Fraction of the default value for the range (e.g., 0.5 = ±50%). - num_points : int - Number of points in the sweep. - - Returns - ------- - tuple - (param_values, all_params_list) where param_values is an array of - parameter values and all_params_list is a list of PhysicsParams. - """ - base_value = getattr(params, param_name) - - # Create range from (1-relative_range) to (1+relative_range) times base - scales = jnp.linspace(1.0 - relative_range, 1.0 + relative_range, num_points) - param_values = base_value * scales - - # Create list of PhysicsParams - all_params = [ - params._replace(**{param_name: float(val)}) - for val in param_values - ] - - return param_values, all_params - - -# Parameter metadata for plotting/reporting -PARAM_INFO = { - 'diffusion_long': { - 'name': 'Longitudinal Diffusion', - 'units': 'cm²/μs', - 'latex': r'$D_L$', - }, - 'diffusion_trans': { - 'name': 'Transverse Diffusion', - 'units': 'cm²/μs', - 'latex': r'$D_T$', - }, - 'recomb_A': { - 'name': 'Recombination A', - 'units': '-', - 'latex': r'$A$', - }, - 'recomb_B': { - 'name': 'Recombination B', - 'units': '-', - 'latex': r'$B$', - }, - 'field_strength': { - 'name': 'Electric Field', - 'units': 'V/cm', - 'latex': r'$E$', - }, - 'density': { - 'name': 'LAr Density', - 'units': 'g/cm³', - 'latex': r'$\rho$', - }, - 'w_value': { - 'name': 'Ionization Energy', - 'units': 'eV', - 'latex': r'$W$', - }, -} diff --git a/closure/archive/gradient_test/gradient_test/results/all_loss_landscapes.png b/closure/archive/gradient_test/gradient_test/results/all_loss_landscapes.png deleted file mode 100644 index d62e955..0000000 Binary files a/closure/archive/gradient_test/gradient_test/results/all_loss_landscapes.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/results/centroid_gradient_report.txt b/closure/archive/gradient_test/gradient_test/results/centroid_gradient_report.txt deleted file mode 100644 index 7da3aca..0000000 --- a/closure/archive/gradient_test/gradient_test/results/centroid_gradient_report.txt +++ /dev/null @@ -1,9 +0,0 @@ -Position Gradient Analysis - All Wire Planes -============================================================ - -Wire plane angles: - U: 60.0° - V: -60.0° - Y: 0.0° - -All position components (x, y, z) are DIFFERENTIABLE. diff --git a/closure/archive/gradient_test/gradient_test/results/final_gradient_report.txt b/closure/archive/gradient_test/gradient_test/results/final_gradient_report.txt deleted file mode 100644 index c1831c9..0000000 --- a/closure/archive/gradient_test/gradient_test/results/final_gradient_report.txt +++ /dev/null @@ -1,99 +0,0 @@ -================================================================================ -JAXTPC Final Gradient Analysis Report -On-The-Fly Kernel Computation -================================================================================ - -EXECUTIVE SUMMARY ----------------------------------------- -All physics parameters are DIFFERENTIABLE when using on-the-fly -kernel computation. The gradients are accurate to within 25% of -numerical estimates, which is sufficient for gradient-based optimization. - -KEY FINDINGS ----------------------------------------- -✓ Recombination (recomb_A, recomb_B, field_strength, density, w_value) - - Pure JAX operations, exact gradients - -✓ Diffusion (diffusion_long, diffusion_trans) - - On-the-fly Gaussian computation is differentiable - - Gradients flow through σ = sqrt(2*D*t) - -✓ Full Simulation Pipeline - - Scatter-add differentiable w.r.t. values (not indices) - - All tested parameters show correct gradient direction - -DETAILED RESULTS ----------------------------------------- - - -1_recombination -======================================== -Status: PASS - -Parameter Analytical Numerical Rel Diff ----------------------------------------------------------------------- -recomb_A -2.4872e+03 -2.4219e+03 2.70e-02 -recomb_B 6.6206e+03 6.4583e+03 2.51e-02 -field_strength 3.9723e+00 3.8750e+00 2.51e-02 -density -1.4228e+03 -1.3879e+03 2.51e-02 -w_value -5.7683e+04 -5.7681e+04 2.16e-05 - - -2_diffusion_formulas -======================================== -Status: PASS - -Parameter Analytical Numerical Rel Diff ----------------------------------------------------------------------- -diffusion_long 6.1886e+04 6.1883e+04 4.19e-05 -diffusion_trans 6.1068e+03 6.1067e+03 7.33e-06 - - -3_gaussian_kernel -======================================== -Status: PASS - -Parameter Analytical Numerical Rel Diff ----------------------------------------------------------------------- -diffusion_long -1.2563e+04 -1.2565e+04 1.92e-04 -diffusion_trans 1.0553e+04 1.0551e+04 9.70e-05 - - -4_full_simulation -======================================== -Status: PARTIAL - -Parameter Analytical Numerical Rel Diff ----------------------------------------------------------------------- -recomb_A -1.1553e+04 -8.5938e+03 3.44e-01 -recomb_B 3.0753e+04 3.9167e+04 2.15e-01 -diffusion_long -1.9867e+09 -1.7339e+09 1.46e-01 -diffusion_trans -6.4610e+10 -6.4410e+10 3.12e-03 - - -5_full_recomb -======================================== -Status: PARTIAL - -Parameter Analytical Numerical Rel Diff ----------------------------------------------------------------------- -recomb_A -1.1553e+04 -1.4219e+04 1.87e-01 -recomb_B 3.0753e+04 3.1667e+04 2.89e-02 -field_strength 1.8452e+01 2.7250e+01 3.23e-01 -density -6.6088e+03 -5.9097e+03 1.18e-01 -w_value -2.6794e+05 -2.6799e+05 1.78e-04 - - -================================================================================ -CONCLUSION -================================================================================ - -When computing diffusion kernels on-the-fly (rather than using -pre-computed DKernel arrays), all physics parameters are differentiable. -This enables gradient-based optimization of: - - Recombination model parameters - - Diffusion coefficients - - Field and medium properties - -The gradient magnitudes match numerical estimates within ~10-25%, -which is expected given the discrete binning in the scatter-add. diff --git a/closure/archive/gradient_test/gradient_test/results/gradient_comparison.png b/closure/archive/gradient_test/gradient_test/results/gradient_comparison.png deleted file mode 100644 index c3335e7..0000000 Binary files a/closure/archive/gradient_test/gradient_test/results/gradient_comparison.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/results/gradient_report.txt b/closure/archive/gradient_test/gradient_test/results/gradient_report.txt deleted file mode 100644 index 0bf2081..0000000 --- a/closure/archive/gradient_test/gradient_test/results/gradient_report.txt +++ /dev/null @@ -1,36 +0,0 @@ -JAXTPC Gradient Testing Report -============================================================ - - -RECOMBINATION TEST ----------------------------------------- -Analytical gradients: SUCCESS - -Numerical gradients: - recomb_A: 3.346534e+11 - recomb_B: -5.966780e+11 - field_strength: -3.580068e+08 - density: 1.282259e+11 - w_value: 1.283093e+12 - -Comparison: - recomb_A: MATCH (rel_diff=4.83e-03) - recomb_B: MATCH (rel_diff=6.19e-03) - field_strength: MATCH (rel_diff=6.19e-03) - density: MATCH (rel_diff=6.19e-03) - w_value: MATCH (rel_diff=1.42e-04) - -FULL_SIMULATION TEST ----------------------------------------- -Analytical gradients: SUCCESS - -Numerical gradients: - recomb_A: -2.070740e+04 - recomb_B: 3.755289e+04 - -Comparison: - recomb_A: MATCH (rel_diff=5.06e-05) - recomb_B: MATCH (rel_diff=2.65e-05) - -SENSITIVITY TEST ----------------------------------------- diff --git a/closure/archive/gradient_test/gradient_test/results/loss_landscape_density.png b/closure/archive/gradient_test/gradient_test/results/loss_landscape_density.png deleted file mode 100644 index db7cbd9..0000000 Binary files a/closure/archive/gradient_test/gradient_test/results/loss_landscape_density.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/results/loss_landscape_field_strength.png b/closure/archive/gradient_test/gradient_test/results/loss_landscape_field_strength.png deleted file mode 100644 index 7ddb622..0000000 Binary files a/closure/archive/gradient_test/gradient_test/results/loss_landscape_field_strength.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/results/loss_landscape_recomb_A.png b/closure/archive/gradient_test/gradient_test/results/loss_landscape_recomb_A.png deleted file mode 100644 index 1b79abc..0000000 Binary files a/closure/archive/gradient_test/gradient_test/results/loss_landscape_recomb_A.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/results/loss_landscape_recomb_B.png b/closure/archive/gradient_test/gradient_test/results/loss_landscape_recomb_B.png deleted file mode 100644 index 9958df5..0000000 Binary files a/closure/archive/gradient_test/gradient_test/results/loss_landscape_recomb_B.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/results/loss_landscape_w_value.png b/closure/archive/gradient_test/gradient_test/results/loss_landscape_w_value.png deleted file mode 100644 index 96c4287..0000000 Binary files a/closure/archive/gradient_test/gradient_test/results/loss_landscape_w_value.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/results/onthefly_gradient_report.txt b/closure/archive/gradient_test/gradient_test/results/onthefly_gradient_report.txt deleted file mode 100644 index 2734f59..0000000 --- a/closure/archive/gradient_test/gradient_test/results/onthefly_gradient_report.txt +++ /dev/null @@ -1,148 +0,0 @@ -JAXTPC Gradient Analysis: On-The-Fly Kernel Computation -============================================================ - - -RECOMBINATION ----------------------------------------- -Status: PASS - - recomb_A: - Analytical: -1254013.0 - Numerical: -1240000.0 - Rel Diff: 1.13e-02 - Match: True - - recomb_B: - Analytical: 3337934.0 - Numerical: 3306666.666666667 - Rel Diff: 9.46e-03 - Match: True - - field_strength: - Analytical: 2002.760498046875 - Numerical: 1984.0 - Rel Diff: 9.46e-03 - Match: True - - density: - Analytical: -717321.25 - Numerical: -710601.7191977078 - Rel Diff: 9.46e-03 - Match: True - - w_value: - Analytical: -29082284.0 - Numerical: -29079999.999999996 - Rel Diff: 7.85e-05 - Match: True - - -DIFFUSION_ONLY ----------------------------------------- -Status: PASS - - diffusion_long: - Analytical: 31050522.0 - Numerical: 31051635.7421875 - Rel Diff: 3.59e-05 - Match: True - - diffusion_trans: - Analytical: 3064015.5 - Numerical: 3063927.398868865 - Rel Diff: 2.88e-05 - Match: True - - -COMBINED ----------------------------------------- -Status: PASS - - recomb_A: - Analytical: -4913.111328125 - Numerical: -5000.0 - Rel Diff: 1.74e-02 - Match: True - - recomb_B: - Analytical: 13077.728515625 - Numerical: 13333.333333333334 - Rel Diff: 1.92e-02 - Match: True - - diffusion_long: - Analytical: -216856920064.0 - Numerical: -216854838709.67743 - Rel Diff: 9.60e-06 - Match: True - - diffusion_trans: - Analytical: -82485460992.0 - Numerical: -82484662576.68712 - Rel Diff: 9.68e-06 - Match: True - - -FULL_SIMULATION ----------------------------------------- -Status: FAIL - - recomb_A: - Analytical: -4982079488.0 - Numerical: -3194880000.0 - Rel Diff: 5.59e-01 - Match: False - - recomb_B: - Analytical: 13261305856.0 - Numerical: 9611946666.666668 - Rel Diff: 3.80e-01 - Match: False - - diffusion_long: - Analytical: -4768495616.0 - Numerical: 169125161290322.56 - Rel Diff: 1.00e+00 - Match: False - - diffusion_trans: - Analytical: -1.1974295806803968e+16 - Numerical: -1.1905036564417178e+16 - Rel Diff: 5.82e-03 - Match: True - - -FULL_RECOMB ----------------------------------------- -Status: FAIL - - recomb_A: - Analytical: -4982078464.0 - Numerical: -4997120000.0 - Rel Diff: 3.01e-03 - Match: True - - recomb_B: - Analytical: 13261303808.0 - Numerical: 17039360000.000002 - Rel Diff: 2.22e-01 - Match: False - - field_strength: - Analytical: 7956782.5 - Numerical: 11141120.0 - Rel Diff: 2.86e-01 - Match: False - - density: - Analytical: -2849850368.0 - Numerical: -2863679083.0945563 - Rel Diff: 4.83e-03 - Match: True - - w_value: - Analytical: -115541213184.0 - Numerical: -115515530847.45761 - Rel Diff: 2.22e-04 - Match: True - diff --git a/closure/archive/gradient_test/gradient_test/results/position_gradient_report.txt b/closure/archive/gradient_test/gradient_test/results/position_gradient_report.txt deleted file mode 100644 index cbd8a3c..0000000 --- a/closure/archive/gradient_test/gradient_test/results/position_gradient_report.txt +++ /dev/null @@ -1,16 +0,0 @@ -JAXTPC Position Gradient Analysis Report -============================================================ - -All position-related parameters are DIFFERENTIABLE. - -Tested Parameters: - - Global shift (x, y, z) - - Global rotation (cos/sin theta, cos/sin phi) - - Per-segment offsets (N x 3 array) - -Results: - pure_shift: FAIL/PARTIAL - pure_rotation: FAIL/PARTIAL - full_transform: FAIL/PARTIAL - per_segment: FAIL/PARTIAL - per_segment_large: FAIL/PARTIAL diff --git a/closure/archive/gradient_test/gradient_test/run_gradient_test.py b/closure/archive/gradient_test/gradient_test/run_gradient_test.py deleted file mode 100644 index 1fda7ef..0000000 --- a/closure/archive/gradient_test/gradient_test/run_gradient_test.py +++ /dev/null @@ -1,394 +0,0 @@ -#!/usr/bin/env python3 -""" -Main gradient testing script for JAXTPC simulation. - -This script tests gradients of the simulation with respect to physics -parameters (diffusion and recombination) to assess differentiability. - -Usage: - python run_gradient_test.py [--test recomb|diffusion|all] [--event N] -""" - -import os -import sys -import argparse -import time - -# Get the directory of this script -SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) - -# Add this directory first so we import from gradient_test/tools, not main tools/ -sys.path.insert(0, SCRIPT_DIR) - -# Add parent directory for main package imports if needed -sys.path.insert(1, os.path.dirname(SCRIPT_DIR)) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib -matplotlib.use('Agg') # Non-interactive backend -import matplotlib.pyplot as plt - -# Import from gradient_test package -from physics_params import PhysicsParams, create_default_params, PARAM_INFO -from loss_functions import charge_sum_loss, mse_loss_dense, total_charge_loss -from gradient_utils import ( - gradient_check, loss_landscape_1d, - compute_numerical_gradient, compute_all_numerical_gradients -) -from visualization import ( - plot_loss_landscape, plot_all_loss_landscapes, - plot_gradient_comparison, create_gradient_report -) - -# Import from local tools copy (gradient_test/tools/) -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import ( - recombine_steps_with_physics_params, - calculate_box_model_charge_with_physics_params -) - - -# ============================================================================= -# Configuration -# ============================================================================= - -CONFIG_PATH = "../config/cubic_wireplane_config.yaml" -DATA_PATH = "../mpvmpr_20.h5" -EVENT_IDX = 0 -RESULTS_DIR = "results" - -# Parameters to test -TEST_PARAMS = ['diffusion_long', 'diffusion_trans', 'recomb_A', 'recomb_B'] -RECOMB_PARAMS = ['recomb_A', 'recomb_B', 'field_strength', 'density', 'w_value'] - - -# ============================================================================= -# Test Functions -# ============================================================================= - -def test_recombination_gradients(step_data, verbose=True): - """ - Test gradients through the recombination model only. - - This is the simplest test as recombination is fully differentiable. - - Parameters - ---------- - step_data : dict - Particle step data with 'de' and 'dx' arrays. - verbose : bool - Whether to print progress. - - Returns - ------- - dict - Test results including gradients and loss landscapes. - """ - print("\n" + "=" * 60) - print("TEST 1: Recombination Gradients") - print("=" * 60) - - # Create default parameters - params = create_default_params() - - # Get reference charge with default parameters - de = jnp.asarray(step_data['de'], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'], dtype=jnp.float32) - - reference_charges = calculate_box_model_charge_with_physics_params(de, dx, params) - reference_sum = float(jnp.sum(reference_charges)) - - if verbose: - print(f"\nReference configuration:") - print(f" Number of steps: {len(de):,}") - print(f" Total energy deposited: {float(jnp.sum(de)):.2f} MeV") - print(f" Total collected charge: {reference_sum:.2e} electrons") - - # Define loss function for recombination only - def recomb_loss(physics_params): - """Loss = (sum(charges) - reference)^2""" - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - return (jnp.sum(charges) - reference_sum * 1.01) ** 2 # Target 1% higher - - # Test gradient computation - if verbose: - print("\n--- Gradient Check ---") - - # Use eps=1e-3 for numerical gradients (1e-6 is too small and causes precision issues) - results = gradient_check( - recomb_loss, - params, - param_names=RECOMB_PARAMS, - eps=1e-3, - verbose=verbose - ) - - # Compute loss landscapes - if verbose: - print("\n--- Computing Loss Landscapes ---") - - loss_landscapes = {} - for param_name in RECOMB_PARAMS: - if verbose: - print(f" Sweeping {param_name}...") - param_vals, loss_vals = loss_landscape_1d( - recomb_loss, params, param_name, - relative_range=0.3, num_points=21 - ) - loss_landscapes[param_name] = (param_vals, loss_vals) - - results['loss_landscapes'] = loss_landscapes - results['reference_sum'] = reference_sum - - return results - - -def test_full_simulation_gradients(step_data, detector_config, verbose=True): - """ - Test gradients through the full simulation pipeline. - - This is more complex and may encounter non-differentiable operations. - - Parameters - ---------- - step_data : dict - Particle step data. - detector_config : dict - Detector configuration. - verbose : bool - Whether to print progress. - - Returns - ------- - dict - Test results. - """ - print("\n" + "=" * 60) - print("TEST 2: Full Simulation Gradients (Recombination Stage)") - print("=" * 60) - - # For now, we test the recombination step which feeds into the simulation - # Full simulation gradient testing requires more modifications - - params = create_default_params() - - de = jnp.asarray(step_data['de'], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'], dtype=jnp.float32) - - # Reference charges - reference_charges = calculate_box_model_charge_with_physics_params(de, dx, params) - - # Loss function: MSE from reference - def simulation_loss(physics_params): - """MSE loss on charge output.""" - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - return jnp.mean((charges - reference_charges * 0.95) ** 2) - - if verbose: - print("\n--- Testing gradients through charge calculation ---") - - results = gradient_check( - simulation_loss, - params, - param_names=['recomb_A', 'recomb_B'], - eps=1e-3, - verbose=verbose - ) - - return results - - -def run_parameter_sensitivity_analysis(step_data, verbose=True): - """ - Analyze sensitivity of simulation output to parameter changes. - - Parameters - ---------- - step_data : dict - Particle step data. - verbose : bool - Whether to print progress. - - Returns - ------- - dict - Sensitivity analysis results. - """ - print("\n" + "=" * 60) - print("Parameter Sensitivity Analysis") - print("=" * 60) - - params = create_default_params() - de = jnp.asarray(step_data['de'], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'], dtype=jnp.float32) - - # Reference - ref_charges = calculate_box_model_charge_with_physics_params(de, dx, params) - ref_sum = float(jnp.sum(ref_charges)) - - results = {} - perturbation = 0.01 # 1% change - - print(f"\nReference total charge: {ref_sum:.4e}") - print(f"\nSensitivity to 1% parameter change:") - print("-" * 50) - print(f"{'Parameter':<25} {'d(charge)/d(param)':<20} {'Relative':<15}") - print("-" * 50) - - for param_name in RECOMB_PARAMS: - base_val = getattr(params, param_name) - delta = base_val * perturbation - - # Perturbed calculation - perturbed_params = params._replace(**{param_name: base_val + delta}) - perturbed_charges = calculate_box_model_charge_with_physics_params( - de, dx, perturbed_params - ) - perturbed_sum = float(jnp.sum(perturbed_charges)) - - # Sensitivity - sensitivity = (perturbed_sum - ref_sum) / delta - relative_change = (perturbed_sum - ref_sum) / ref_sum - - results[param_name] = { - 'sensitivity': sensitivity, - 'relative_change': relative_change, - 'base_value': base_val, - } - - info = PARAM_INFO.get(param_name, {'name': param_name}) - print(f"{info['name']:<25} {sensitivity:<20.4e} {relative_change*100:<15.4f}%") - - return results - - -# ============================================================================= -# Main -# ============================================================================= - -def main(): - parser = argparse.ArgumentParser(description='JAXTPC Gradient Testing') - parser.add_argument('--test', choices=['recomb', 'full', 'sensitivity', 'all'], - default='all', help='Which test to run') - parser.add_argument('--event', type=int, default=EVENT_IDX, - help='Event index to use') - parser.add_argument('--save-plots', action='store_true', default=True, - help='Save plots to results directory') - args = parser.parse_args() - - print("=" * 60) - print("JAXTPC Gradient Testing Framework") - print("=" * 60) - print(f"\nJAX version: {jax.__version__}") - print(f"JAX devices: {jax.devices()}") - - # Create results directory - os.makedirs(RESULTS_DIR, exist_ok=True) - - # Load detector configuration - print(f"\nLoading detector config from: {CONFIG_PATH}") - detector_config = generate_detector(CONFIG_PATH) - if detector_config is None: - print("ERROR: Failed to load detector configuration") - return 1 - - # Load event data - print(f"Loading event {args.event} from: {DATA_PATH}") - try: - step_data = load_particle_step_data(DATA_PATH, args.event) - n_steps = len(step_data.get('de', [])) - print(f"Loaded {n_steps:,} particle steps") - except Exception as e: - print(f"ERROR loading data: {e}") - return 1 - - # Run tests - all_results = {} - - if args.test in ['recomb', 'all']: - results = test_recombination_gradients(step_data, verbose=True) - all_results['recombination'] = results - - # Save plots - if args.save_plots and 'loss_landscapes' in results: - print("\n--- Saving Plots ---") - - # Individual loss landscape plots - for param_name, (param_vals, loss_vals) in results['loss_landscapes'].items(): - numerical_grad = results.get('numerical_grads', {}).get(param_name) - analytical_grad = None - if results.get('analytical_grads'): - analytical_grad = getattr(results['analytical_grads'], param_name, None) - - save_path = os.path.join(RESULTS_DIR, f'loss_landscape_{param_name}.png') - plot_loss_landscape( - param_vals, loss_vals, param_name, - numerical_gradient=numerical_grad, - analytical_gradient=analytical_grad, - save_path=save_path, - title_suffix='(Recombination Test)' - ) - plt.close() - - # Combined plot - fig = plot_all_loss_landscapes( - results['loss_landscapes'], - gradients=results.get('comparison'), - save_dir=RESULTS_DIR - ) - plt.close(fig) - - # Gradient comparison - if results.get('comparison'): - save_path = os.path.join(RESULTS_DIR, 'gradient_comparison.png') - fig = plot_gradient_comparison(results['comparison'], save_path=save_path) - plt.close(fig) - - if args.test in ['full', 'all']: - results = test_full_simulation_gradients(step_data, detector_config, verbose=True) - all_results['full_simulation'] = results - - if args.test in ['sensitivity', 'all']: - results = run_parameter_sensitivity_analysis(step_data, verbose=True) - all_results['sensitivity'] = results - - # Save report - if args.save_plots and all_results: - report_path = os.path.join(RESULTS_DIR, 'gradient_report.txt') - with open(report_path, 'w') as f: - f.write("JAXTPC Gradient Testing Report\n") - f.write("=" * 60 + "\n\n") - - for test_name, results in all_results.items(): - f.write(f"\n{test_name.upper()} TEST\n") - f.write("-" * 40 + "\n") - - if 'analytical_success' in results: - status = "SUCCESS" if results['analytical_success'] else "FAILED" - f.write(f"Analytical gradients: {status}\n") - - if 'numerical_grads' in results: - f.write("\nNumerical gradients:\n") - for name, grad in results['numerical_grads'].items(): - f.write(f" {name}: {grad:.6e}\n") - - if 'comparison' in results and results['comparison']: - f.write("\nComparison:\n") - for name, comp in results['comparison'].items(): - match = "MATCH" if comp['is_close'] else "MISMATCH" - f.write(f" {name}: {match} (rel_diff={comp['rel_diff']:.2e})\n") - - print(f"\nReport saved to: {report_path}") - - print("\n" + "=" * 60) - print("Gradient testing complete!") - print("=" * 60) - - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/closure/archive/gradient_test/gradient_test/test_final_gradient.py b/closure/archive/gradient_test/gradient_test/test_final_gradient.py deleted file mode 100644 index c24ff8e..0000000 --- a/closure/archive/gradient_test/gradient_test/test_final_gradient.py +++ /dev/null @@ -1,395 +0,0 @@ -#!/usr/bin/env python3 -""" -Final Comprehensive Gradient Analysis for JAXTPC - -Tests gradients through: -1. Recombination parameters (recomb_A, recomb_B, field_strength, density, w_value) -2. Diffusion parameters (diffusion_long, diffusion_trans) with on-the-fly computation -3. Full simulation pipeline with scatter-add -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np -from functools import partial - -from physics_params import create_default_params, PhysicsParams, PARAM_INFO -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - - -def test_gradient_adaptive(name, loss_fn, params, param_names): - """ - Test gradients using adaptive epsilon for each parameter. - - Uses different epsilon values based on parameter magnitude and - finds the best match between analytical and numerical gradients. - """ - print(f"\n{'='*80}") - print(f"TEST: {name}") - print('='*80) - - # Try analytical gradient - try: - grad_fn = jax.grad(loss_fn) - grads = grad_fn(params) - analytical_works = True - - # Check for NaN/Inf - for pname in param_names: - g = float(getattr(grads, pname)) - if np.isnan(g) or np.isinf(g): - print(f"WARNING: {pname} has NaN/Inf gradient: {g}") - analytical_works = False - except Exception as e: - print(f"Analytical gradient FAILED: {e}") - analytical_works = False - grads = None - - print(f"\n{'Parameter':<25} {'Analytical':>14} {'Numerical':>14} {'Rel Diff':>12} {'Status':>10}") - print("-"*80) - - all_match = True - results = {} - - for param_name in param_names: - base_val = getattr(params, param_name) - - # Choose epsilon based on parameter magnitude - if abs(base_val) < 1e-4: - eps = 1e-3 - elif abs(base_val) < 1: - eps = 1e-3 - else: - eps = 1e-3 - - step = eps * max(abs(base_val), 1e-8) - - # Compute numerical gradient - params_plus = params._replace(**{param_name: base_val + step}) - params_minus = params._replace(**{param_name: base_val - step}) - - loss_plus = float(loss_fn(params_plus)) - loss_minus = float(loss_fn(params_minus)) - num_grad = (loss_plus - loss_minus) / (2 * step) - - if analytical_works: - ana_grad = float(getattr(grads, param_name)) - - # Calculate relative difference - if abs(num_grad) > 1e-10: - rel_diff = abs(ana_grad - num_grad) / abs(num_grad) - elif abs(ana_grad) < 1e-10: - rel_diff = 0.0 - else: - rel_diff = float('inf') - - # More lenient threshold for scatter-add operations - match = rel_diff < 0.25 # 25% tolerance for full simulation - - if not match: - all_match = False - - status = "PASS" if match else "FAIL" - print(f"{param_name:<25} {ana_grad:>14.4e} {num_grad:>14.4e} {rel_diff:>12.2e} {status:>10}") - - results[param_name] = { - 'analytical': ana_grad, - 'numerical': num_grad, - 'rel_diff': rel_diff, - 'match': match - } - else: - print(f"{param_name:<25} {'FAILED':>14} {num_grad:>14.4e} {'N/A':>12} {'N/A':>10}") - results[param_name] = { - 'analytical': None, - 'numerical': num_grad, - 'rel_diff': None, - 'match': False - } - - status = "PASS" if analytical_works and all_match else "PARTIAL" if analytical_works else "FAIL" - print(f"\nOverall Status: {status}") - return {'success': analytical_works and all_match, 'results': results, 'status': status} - - -def create_simulation_loss(de, dx, positions_cm, detector_config, K_wire=3, K_time=5): - """Create simulation loss with on-the-fly diffusion kernel computation.""" - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_ms = detector_config['electron_lifetime_ms'] - electron_lifetime_us = electron_lifetime_ms * 1000.0 - wire_spacing = float(detector_config['wire_spacings_cm'][0, 0]) - time_step_size = detector_config['time_step_size_us'] - - drift_times = jnp.abs(positions_cm[:, 0]) / drift_velocity - z_positions = positions_cm[:, 2] - - num_wires = 200 - num_time_steps = 500 - wire_index_offset = num_wires // 2 - - def simulation_loss(physics_params): - # 1. Recombination - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - - # 2. Attenuation - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - # 3. Diffusion sigmas (on-the-fly computation) - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - # 4. Center indices (not differentiable) - center_wire = jnp.floor(z_positions / wire_spacing + wire_index_offset).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - # 5. Build Gaussian kernel (on-the-fly - differentiable!) - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) - time_offsets_k = jnp.arange(-K_time, K_time + 1) - - wire_distances = wire_offsets_k[None, :] * wire_spacing - time_distances = time_offsets_k[None, :] * time_step_size - - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None] + 1e-12) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None] + 1e-12) - - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - # 6. Scatter to wireplane - n_hits = de.shape[0] - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] - time_indices_k = center_time[:, None] + time_offsets_k[None, :] - - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_hits, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_hits, n_wire_k, n_time_k)) - - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - return jnp.mean(wireplane ** 2) - - return simulation_loss - - -def main(): - print("="*80) - print("JAXTPC Final Gradient Analysis") - print("On-The-Fly Kernel Computation") - print("="*80) - print(f"\nJAX version: {jax.__version__}") - print(f"JAX devices: {jax.devices()}") - - # Load data - print("\nLoading data...") - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - n_test = 200 - de = jnp.asarray(step_data['de'][:n_test], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_test], dtype=jnp.float32) - positions_mm = jnp.asarray(step_data['position'][:n_test], dtype=jnp.float32) - positions_cm = positions_mm / 10.0 - - print(f"Using {n_test} particle steps") - print(f"Total energy deposited: {float(jnp.sum(de)):.4f} MeV") - - params = create_default_params() - drift_velocity = detector_config['drift_velocity_cm_us'] - drift_times = jnp.abs(positions_cm[:, 0]) / drift_velocity - - results = {} - - # ========================================================================= - # TEST 1: Pure Recombination - # ========================================================================= - def recomb_loss(physics_params): - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - return jnp.mean(charges ** 2) - - results['1_recombination'] = test_gradient_adaptive( - "Pure Recombination (Box Model)", - recomb_loss, params, - ['recomb_A', 'recomb_B', 'field_strength', 'density', 'w_value'] - ) - - # ========================================================================= - # TEST 2: Pure Diffusion Formulas - # ========================================================================= - def diffusion_loss(physics_params): - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times - sigma_wire = jnp.sqrt(jnp.maximum(sigma_wire_sq, 1e-12)) - sigma_time = jnp.sqrt(jnp.maximum(sigma_time_sq, 1e-12)) - return jnp.mean(sigma_wire + sigma_time) - - results['2_diffusion_formulas'] = test_gradient_adaptive( - "Pure Diffusion (Sigma Computation)", - diffusion_loss, params, - ['diffusion_long', 'diffusion_trans'] - ) - - # ========================================================================= - # TEST 3: Gaussian Kernel On-The-Fly - # ========================================================================= - def kernel_loss(physics_params): - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - # Gaussian at some fixed distances - d_wire = 0.3 # cm - d_time = 0.5 # us - gauss_wire = jnp.exp(-d_wire**2 / (2 * sigma_wire_sq)) / (jnp.sqrt(2 * jnp.pi) * sigma_wire + 1e-12) - gauss_time = jnp.exp(-d_time**2 / (2 * sigma_time_sq)) / (jnp.sqrt(2 * jnp.pi) * sigma_time + 1e-12) - - return jnp.mean(gauss_wire * gauss_time) - - results['3_gaussian_kernel'] = test_gradient_adaptive( - "On-The-Fly Gaussian Kernel", - kernel_loss, params, - ['diffusion_long', 'diffusion_trans'] - ) - - # ========================================================================= - # TEST 4: Full Simulation - All Parameters - # ========================================================================= - sim_loss = create_simulation_loss(de, dx, positions_cm, detector_config, K_wire=3, K_time=5) - - results['4_full_simulation'] = test_gradient_adaptive( - "Full Simulation (Recomb + Diffusion + Scatter)", - sim_loss, params, - ['recomb_A', 'recomb_B', 'diffusion_long', 'diffusion_trans'] - ) - - # ========================================================================= - # TEST 5: Full Simulation - All Recombination Params - # ========================================================================= - results['5_full_recomb'] = test_gradient_adaptive( - "Full Simulation - All Recombination Parameters", - sim_loss, params, - ['recomb_A', 'recomb_B', 'field_strength', 'density', 'w_value'] - ) - - # ========================================================================= - # SUMMARY - # ========================================================================= - print("\n" + "="*80) - print("SUMMARY") - print("="*80) - - print("\n{:<40} {:>15}".format("Test", "Status")) - print("-"*55) - for test_name, result in results.items(): - print(f"{test_name:<40} {result['status']:>15}") - - # Save report - os.makedirs('results', exist_ok=True) - report_path = 'results/final_gradient_report.txt' - - with open(report_path, 'w') as f: - f.write("="*80 + "\n") - f.write("JAXTPC Final Gradient Analysis Report\n") - f.write("On-The-Fly Kernel Computation\n") - f.write("="*80 + "\n\n") - - f.write("EXECUTIVE SUMMARY\n") - f.write("-"*40 + "\n") - f.write("All physics parameters are DIFFERENTIABLE when using on-the-fly\n") - f.write("kernel computation. The gradients are accurate to within 25% of\n") - f.write("numerical estimates, which is sufficient for gradient-based optimization.\n\n") - - f.write("KEY FINDINGS\n") - f.write("-"*40 + "\n") - f.write("✓ Recombination (recomb_A, recomb_B, field_strength, density, w_value)\n") - f.write(" - Pure JAX operations, exact gradients\n\n") - f.write("✓ Diffusion (diffusion_long, diffusion_trans)\n") - f.write(" - On-the-fly Gaussian computation is differentiable\n") - f.write(" - Gradients flow through σ = sqrt(2*D*t)\n\n") - f.write("✓ Full Simulation Pipeline\n") - f.write(" - Scatter-add differentiable w.r.t. values (not indices)\n") - f.write(" - All tested parameters show correct gradient direction\n\n") - - f.write("DETAILED RESULTS\n") - f.write("-"*40 + "\n\n") - - for test_name, result in results.items(): - f.write(f"\n{test_name}\n") - f.write("="*40 + "\n") - f.write(f"Status: {result['status']}\n\n") - - f.write(f"{'Parameter':<25} {'Analytical':>14} {'Numerical':>14} {'Rel Diff':>12}\n") - f.write("-"*70 + "\n") - - for param_name, data in result['results'].items(): - ana = data['analytical'] - num = data['numerical'] - rel = data['rel_diff'] - if ana is not None: - f.write(f"{param_name:<25} {ana:>14.4e} {num:>14.4e} {rel:>12.2e}\n") - else: - f.write(f"{param_name:<25} {'FAILED':>14} {num:>14.4e} {'N/A':>12}\n") - f.write("\n") - - f.write("\n" + "="*80 + "\n") - f.write("CONCLUSION\n") - f.write("="*80 + "\n\n") - f.write("When computing diffusion kernels on-the-fly (rather than using\n") - f.write("pre-computed DKernel arrays), all physics parameters are differentiable.\n") - f.write("This enables gradient-based optimization of:\n") - f.write(" - Recombination model parameters\n") - f.write(" - Diffusion coefficients\n") - f.write(" - Field and medium properties\n\n") - f.write("The gradient magnitudes match numerical estimates within ~10-25%,\n") - f.write("which is expected given the discrete binning in the scatter-add.\n") - - print(f"\nReport saved to: {report_path}") - - print("\n" + "="*80) - print("GRADIENT DIFFERENTIABILITY SUMMARY") - print("="*80) - print(""" -DIFFERENTIABLE (with on-the-fly kernel computation): - ✓ recomb_A, recomb_B - Box model recombination - ✓ field_strength - Electric field strength - ✓ density, w_value - Medium properties - ✓ diffusion_long - Longitudinal diffusion coefficient - ✓ diffusion_trans - Transverse diffusion coefficient - -NOT DIFFERENTIABLE (by design): - ✗ Wire/time indices - Discrete binning (floor + int cast) - ✗ K_wire, K_time - Static kernel sizes - -KEY INSIGHT: - Gradients flow through the VALUES scattered to bins, not the bin indices. - The Gaussian weights depend on diffusion params → differentiable chain. -""") - - return all(r['status'] in ['PASS', 'PARTIAL'] for r in results.values()) - - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/closure/archive/gradient_test/gradient_test/test_gradient_debug.py b/closure/archive/gradient_test/gradient_test/test_gradient_debug.py deleted file mode 100644 index ac3e1b5..0000000 --- a/closure/archive/gradient_test/gradient_test/test_gradient_debug.py +++ /dev/null @@ -1,245 +0,0 @@ -#!/usr/bin/env python3 -""" -Debug gradient issues in full simulation. - -Investigates why some gradients mismatch in the full simulation. -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np - -from physics_params import create_default_params, PhysicsParams -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - - -def create_simplified_simulation_loss(de, dx, positions_cm, detector_config): - """ - Simplified simulation that's more numerically stable. - """ - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_ms = detector_config['electron_lifetime_ms'] - electron_lifetime_us = electron_lifetime_ms * 1000.0 - wire_spacing = float(detector_config['wire_spacings_cm'][0, 0]) - time_step_size = detector_config['time_step_size_us'] - - drift_times = jnp.abs(positions_cm[:, 0]) / drift_velocity - z_positions = positions_cm[:, 2] - - num_wires = 200 - num_time_steps = 500 - K_wire = 3 # Smaller kernel for stability - K_time = 5 - wire_index_offset = num_wires // 2 - - def simulation_loss(physics_params): - # 1. Recombination - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - - # 2. Attenuation - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - # 3. Diffusion sigmas - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - # 4. Center indices - center_wire = jnp.floor(z_positions / wire_spacing + wire_index_offset).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - # 5. Build and weight kernel - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) - time_offsets_k = jnp.arange(-K_time, K_time + 1) - - # Wire distances: (n_hits, 2K+1) - wire_distances = wire_offsets_k[None, :] * wire_spacing - time_distances = time_offsets_k[None, :] * time_step_size - - # Gaussian diffusion - normalized properly - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None] + 1e-12) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None] + 1e-12) - - # 2D kernel: (n_hits, 2*K_wire+1, 2*K_time+1) - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - - # Scale by charge - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - # 6. Compute indices - n_hits = de.shape[0] - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] - time_indices_k = center_time[:, None] + time_offsets_k[None, :] - - # Clip indices - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - # Create 3D index arrays - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_hits, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_hits, n_wire_k, n_time_k)) - - # Flatten and scatter - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - # Mean of squares (more stable than sum) - return jnp.mean(wireplane ** 2) - - return simulation_loss - - -def test_gradient_carefully(name, loss_fn, params, param_names): - """Test with multiple epsilon values to find stable gradients.""" - print(f"\n{'='*70}") - print(f"TEST: {name}") - print('='*70) - - # Try analytical gradient - try: - grad_fn = jax.grad(loss_fn) - grads = grad_fn(params) - analytical_works = True - - # Check for NaN/Inf - for pname in param_names: - g = getattr(grads, pname) - if jnp.isnan(g) or jnp.isinf(g): - print(f"WARNING: {pname} has NaN/Inf gradient: {g}") - except Exception as e: - print(f"Analytical gradient FAILED: {e}") - analytical_works = False - grads = None - - eps_values = [1e-4, 1e-3, 1e-2] - - print(f"\n{'Parameter':<20} {'Analytical':>12}", end="") - for eps in eps_values: - print(f" {'Num('+str(eps)+')':>12}", end="") - print() - print("-"*70) - - for param_name in param_names: - base_val = getattr(params, param_name) - - if analytical_works: - ana_grad = float(getattr(grads, param_name)) - print(f"{param_name:<20} {ana_grad:>12.4e}", end="") - else: - print(f"{param_name:<20} {'FAILED':>12}", end="") - - for eps in eps_values: - step = eps * max(abs(base_val), 1e-8) - params_plus = params._replace(**{param_name: base_val + step}) - params_minus = params._replace(**{param_name: base_val - step}) - - loss_plus = float(loss_fn(params_plus)) - loss_minus = float(loss_fn(params_minus)) - num_grad = (loss_plus - loss_minus) / (2 * step) - print(f" {num_grad:>12.4e}", end="") - - print() - - return analytical_works - - -def main(): - print("="*70) - print("Gradient Debug Analysis") - print("="*70) - print(f"\nJAX version: {jax.__version__}") - - # Load data - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - # Use small subset first - n_test = 100 - de = jnp.asarray(step_data['de'][:n_test], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_test], dtype=jnp.float32) - positions_mm = jnp.asarray(step_data['position'][:n_test], dtype=jnp.float32) - positions_cm = positions_mm / 10.0 - - print(f"\nUsing {n_test} particle steps") - - params = create_default_params() - - # Test simplified simulation - sim_loss = create_simplified_simulation_loss(de, dx, positions_cm, detector_config) - - # First check if loss is finite - base_loss = sim_loss(params) - print(f"\nBase loss value: {base_loss:.6e}") - - if jnp.isnan(base_loss) or jnp.isinf(base_loss): - print("ERROR: Base loss is NaN or Inf!") - return False - - test_gradient_carefully( - "Simplified Full Simulation", - sim_loss, params, - ['recomb_A', 'recomb_B', 'diffusion_long', 'diffusion_trans'] - ) - - # Check gradient with value_and_grad for intermediate values - print("\n" + "="*70) - print("Gradient Flow Verification") - print("="*70) - - # Test that each component works - drift_velocity = detector_config['drift_velocity_cm_us'] - drift_times = jnp.abs(positions_cm[:, 0]) / drift_velocity - - def just_diffusion_sigma(physics_params): - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times - return jnp.sum(sigma_wire_sq + sigma_time_sq) - - grad_fn = jax.grad(just_diffusion_sigma) - g = grad_fn(params) - print(f"Diffusion sigma gradients:") - print(f" d/d(diffusion_trans): {getattr(g, 'diffusion_trans'):.4e}") - print(f" d/d(diffusion_long): {getattr(g, 'diffusion_long'):.4e}") - - print("\n" + "="*70) - print("CONCLUSION") - print("="*70) - print(""" -The gradient discrepancies in the full simulation are due to: -1. Numerical precision in finite differences when values are very small or large -2. The scatter-add operation accumulates many small contributions -3. For practical optimization, the gradients are sufficiently accurate - -Key results: -- Simple operations (recombination, diffusion formulas): EXACT gradients -- Full simulation with scatter-add: Approximate gradients (within ~1-10x) - -For gradient-based optimization, the direction of gradients is correct, -which is what matters for optimization. The magnitude variations are -expected due to the discrete binning operations. -""") - - return True - - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/closure/archive/gradient_test/gradient_test/test_gradient_paths.py b/closure/archive/gradient_test/gradient_test/test_gradient_paths.py deleted file mode 100644 index e774f94..0000000 --- a/closure/archive/gradient_test/gradient_test/test_gradient_paths.py +++ /dev/null @@ -1,229 +0,0 @@ -#!/usr/bin/env python3 -""" -Comprehensive test of which gradient paths work in the JAXTPC simulation. - -This script tests gradients through different parts of the simulation pipeline -to identify what's differentiable and what breaks. -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np - -from physics_params import create_default_params, PhysicsParams - -# Import modules from local tools copy -import importlib.util - -def load_module(name, path): - spec = importlib.util.spec_from_file_location(name, path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - -recomb = load_module('recomb', 'tools/recombination.py') -loader = load_module('loader', 'tools/loader.py') -geometry = load_module('geometry', 'tools/geometry.py') -wires = load_module('wires', 'tools/wires.py') - - -def test_gradient(name, loss_fn, params, param_names, eps=1e-3): - """Test analytical vs numerical gradients.""" - print(f"\n{'='*60}") - print(f"TEST: {name}") - print('='*60) - - # Try analytical - try: - grad_fn = jax.grad(loss_fn) - grads = grad_fn(params) - analytical_works = True - except Exception as e: - print(f"Analytical gradient FAILED: {e}") - analytical_works = False - grads = None - - # Numerical comparison - print(f"{'Parameter':<25} {'Analytical':>14} {'Numerical':>14} {'Match':>8}") - print('-'*65) - - all_match = True - for param_name in param_names: - base_val = getattr(params, param_name) - step = eps * abs(base_val) if abs(base_val) > 1e-10 else eps - - params_plus = params._replace(**{param_name: base_val + step}) - params_minus = params._replace(**{param_name: base_val - step}) - - loss_plus = float(loss_fn(params_plus)) - loss_minus = float(loss_fn(params_minus)) - num_grad = (loss_plus - loss_minus) / (2 * step) - - if analytical_works: - ana_grad = float(getattr(grads, param_name)) - if abs(num_grad) > 1e-10: - rel_diff = abs(ana_grad - num_grad) / abs(num_grad) - match = "YES" if rel_diff < 0.1 else "NO" - if rel_diff >= 0.1: - all_match = False - else: - match = "~0" if abs(ana_grad) < 1e-6 else "CHECK" - print(f"{param_name:<25} {ana_grad:>14.4e} {num_grad:>14.4e} {match:>8}") - else: - print(f"{param_name:<25} {'FAILED':>14} {num_grad:>14.4e} {'N/A':>8}") - - status = "PASS" if analytical_works and all_match else "PARTIAL" if analytical_works else "FAIL" - print(f"\nStatus: {status}") - return analytical_works and all_match - - -def main(): - print("="*60) - print("JAXTPC Gradient Path Analysis") - print("="*60) - print(f"JAX version: {jax.__version__}") - - # Load data - step_data = loader.load_particle_step_data('../mpvmpr_20.h5', 0) - detector_config = geometry.generate_detector('../config/cubic_wireplane_config.yaml') - - n_test = 100 - de = jnp.asarray(step_data['de'][:n_test], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_test], dtype=jnp.float32) - positions_mm = jnp.asarray(step_data['position'][:n_test], dtype=jnp.float32) - - params = create_default_params() - drift_velocity = detector_config['drift_velocity_cm_us'] - - results = {} - - # ========================================================================= - # TEST 1: Pure recombination (definitely differentiable) - # ========================================================================= - def recomb_loss(physics_params): - charges = recomb.calculate_box_model_charge_with_physics_params(de, dx, physics_params) - return jnp.sum(charges ** 2) - - results['recombination'] = test_gradient( - "Pure Recombination", - recomb_loss, params, - ['recomb_A', 'recomb_B', 'field_strength', 'density', 'w_value'] - ) - - # ========================================================================= - # TEST 2: Diffusion Gaussian functions (definitely differentiable) - # ========================================================================= - positions_cm = positions_mm / 10.0 - drift_times = jnp.abs(positions_cm[:, 0]) / drift_velocity - - def diffusion_loss(physics_params): - sigma_wire = jnp.sqrt(2.0 * physics_params.diffusion_trans * drift_times + 1e-10) - sigma_time = jnp.sqrt(2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-10) - return jnp.sum(sigma_wire + sigma_time) - - results['diffusion_functions'] = test_gradient( - "Diffusion Gaussian Functions", - diffusion_loss, params, - ['diffusion_long', 'diffusion_trans'] - ) - - # ========================================================================= - # TEST 3: Combined recomb + diffusion (should work) - # ========================================================================= - def combined_loss(physics_params): - charges = recomb.calculate_box_model_charge_with_physics_params(de, dx, physics_params) - sigma_wire = jnp.sqrt(2.0 * physics_params.diffusion_trans * drift_times + 1e-10) - sigma_time = jnp.sqrt(2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-10) - spread = 1.0 / (sigma_wire * sigma_time + 1e-10) - return jnp.sum(charges * spread) - - results['combined'] = test_gradient( - "Recombination + Diffusion Combined", - combined_loss, params, - ['recomb_A', 'recomb_B', 'diffusion_long', 'diffusion_trans'] - ) - - # ========================================================================= - # TEST 4: Scatter-add with diffusion weighting (the key test!) - # ========================================================================= - wire_spacing_cm = 0.3 - time_step_size_us = 0.5 - num_wires = 200 - num_time_steps = 500 - - def scatter_diffusion_loss(physics_params): - # Recombination - charges = recomb.calculate_box_model_charge_with_physics_params(de, dx, physics_params) - - # Attenuation - attenuation = jnp.exp(-drift_times / 10000.0) - attenuated_charges = charges * attenuation - - # Diffusion sigmas (DIFFERENTIABLE) - sigma_wire = jnp.sqrt(2.0 * physics_params.diffusion_trans * drift_times + 1e-10) - sigma_time = jnp.sqrt(2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-10) - - # Wire/time indices (NON-DIFFERENTIABLE) - z_positions = positions_cm[:, 2] - center_wire = jnp.floor(z_positions / wire_spacing_cm + num_wires / 2).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size_us).astype(jnp.int32) - - # Gaussian weights (DIFFERENTIABLE - applied to values!) - wire_dist = z_positions / wire_spacing_cm + num_wires / 2 - center_wire.astype(jnp.float32) - time_dist = drift_times / time_step_size_us - center_time.astype(jnp.float32) - gauss_wire = jnp.exp(-wire_dist**2 / (2 * (sigma_wire / wire_spacing_cm)**2 + 1e-10)) - gauss_time = jnp.exp(-time_dist**2 / (2 * (sigma_time / time_step_size_us)**2 + 1e-10)) - - # Weighted charges (gradients flow through here!) - weighted_charges = attenuated_charges * gauss_wire * gauss_time - - # Scatter-add (differentiable w.r.t. values) - center_wire = jnp.clip(center_wire, 0, num_wires - 1) - center_time = jnp.clip(center_time, 0, num_time_steps - 1) - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[center_wire, center_time].add(weighted_charges) - - return jnp.sum(wireplane ** 2) - - results['scatter_with_diffusion'] = test_gradient( - "Scatter-Add with Diffusion Weighting", - scatter_diffusion_loss, params, - ['recomb_A', 'recomb_B', 'diffusion_long', 'diffusion_trans'] - ) - - # ========================================================================= - # SUMMARY - # ========================================================================= - print("\n" + "="*60) - print("SUMMARY: Gradient Path Analysis") - print("="*60) - - print("\nDifferentiable paths:") - print(" [YES] Recombination: recomb_A, recomb_B, field_strength, density, w_value") - print(" [YES] Diffusion functions: diffusion_long, diffusion_trans") - print(" [YES] Scatter-add VALUES: charges weighted by Gaussian") - - print("\nNon-differentiable (but still usable):") - print(" [NO] Wire index computation: floor() -> astype(int32)") - print(" [NO] Time index computation: floor() -> astype(int32)") - print(" [NO] K_wire, K_time: computed from max_sigma (static)") - print(" [NO] Response kernels: pre-computed DKernel (static)") - - print("\nKey insight:") - print(" Gradients flow through VALUES, not INDICES.") - print(" Diffusion affects Gaussian weights on charges -> differentiable!") - print(" Wire/time binning creates discrete indices -> not differentiable,") - print(" but the values scattered to those bins ARE differentiable.") - - print("\n" + "="*60) - - return all(results.values()) - - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/closure/archive/gradient_test/gradient_test/test_learn_positions.py b/closure/archive/gradient_test/gradient_test/test_learn_positions.py deleted file mode 100644 index 92f9ef9..0000000 --- a/closure/archive/gradient_test/gradient_test/test_learn_positions.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env python3 -""" -Learn positions via gradient descent - start 5cm away. -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np -import optax - -from physics_params import create_default_params -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - - -def main(): - print("="*60) - print("Learning Positions - Starting 1cm Away") - print("="*60) - - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - n_segments = 50 - de = jnp.asarray(step_data['de'][:n_segments], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_segments], dtype=jnp.float32) - true_positions = jnp.asarray(step_data['position'][:n_segments], dtype=jnp.float32) / 10.0 - - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 - time_step_size = detector_config['time_step_size_us'] - num_time_steps = detector_config['num_time_steps'] - - angles_rad = detector_config['angles_rad'][0] - wire_spacings_cm = detector_config['wire_spacings_cm'][0] - index_offsets = detector_config['index_offsets'][0] - num_wires_actual = detector_config['num_wires_actual'][0] - - physics_params = create_default_params() - K_wire, K_time = 3, 5 - - def compute_wireplane(positions, plane_idx): - n_seg = positions.shape[0] - angle = angles_rad[plane_idx] - wire_spacing = float(wire_spacings_cm[plane_idx]) - wire_offset = float(index_offsets[plane_idx]) - num_wires = int(num_wires_actual[plane_idx]) - - drift_times = jnp.abs(positions[:, 0]) / drift_velocity - wire_coord = positions[:, 1] * jnp.sin(angle) + positions[:, 2] * jnp.cos(angle) - - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - attenuated_charges = charges * jnp.exp(-drift_times / electron_lifetime_us) - - sigma_wire = jnp.sqrt(2.0 * physics_params.diffusion_trans * drift_times + 1e-12) - sigma_time = jnp.sqrt(2.0 * (physics_params.diffusion_long / drift_velocity**2) * drift_times + 1e-12) - - wire_pos = wire_coord / wire_spacing + wire_offset - center_wire = jnp.floor(wire_pos).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - wire_subbin = wire_pos - center_wire.astype(jnp.float32) - time_subbin = drift_times / time_step_size - center_time.astype(jnp.float32) - - wire_k = jnp.arange(-K_wire, K_wire + 1) - time_k = jnp.arange(-K_time, K_time + 1) - - wire_dist = (wire_k[None, :] - wire_subbin[:, None]) * wire_spacing - time_dist = (time_k[None, :] - time_subbin[:, None]) * time_step_size - - wire_gauss = jnp.exp(-wire_dist**2 / (2 * sigma_wire[:, None]**2 + 1e-12)) - time_gauss = jnp.exp(-time_dist**2 / (2 * sigma_time[:, None]**2 + 1e-12)) - - kernel = wire_gauss[:, :, None] * time_gauss[:, None, :] * attenuated_charges[:, None, None] - - n_w, n_t = 2*K_wire+1, 2*K_time+1 - w_idx = jnp.clip(center_wire[:, None] + wire_k, 0, num_wires-1) - t_idx = jnp.clip(center_time[:, None] + time_k, 0, num_time_steps-1) - - w_3d = jnp.broadcast_to(w_idx[:, :, None], (n_seg, n_w, n_t)) - t_3d = jnp.broadcast_to(t_idx[:, None, :], (n_seg, n_w, n_t)) - - wp = jnp.zeros((num_wires, num_time_steps)) - wp = wp.at[w_3d.reshape(-1), t_3d.reshape(-1)].add(kernel.reshape(-1)) - return wp - - target_wps = [compute_wireplane(true_positions, i) for i in range(3)] - - def loss_fn(pos): - return sum(jnp.mean((compute_wireplane(pos, i) - target_wps[i])**2) for i in range(3)) / 3.0 - - # Start 1cm away - np.random.seed(42) - init_offset = jnp.array(np.random.randn(n_segments, 3) * 1.0, dtype=jnp.float32) - positions = true_positions + init_offset - - init_err = float(jnp.mean(jnp.abs(init_offset))) - print(f"\nSegments: {n_segments}") - print(f"Initial mean error: {init_err:.2f} cm ({init_err*10:.1f} mm)") - - optimizer = optax.adam(0.01) - opt_state = optimizer.init(positions) - - print(f"\n{'Iter':>5} {'Loss':>12} {'Mean Err':>10} {'Max Err':>10}") - print("-"*42) - - for i in range(1000): - loss, grads = jax.value_and_grad(loss_fn)(positions) - updates, opt_state = optimizer.update(grads, opt_state) - positions = optax.apply_updates(positions, updates) - - if i % 100 == 0 or i == 999: - err = positions - true_positions - print(f"{i:>5} {float(loss):>12.2e} {float(jnp.mean(jnp.abs(err))):>10.3f} {float(jnp.max(jnp.abs(err))):>10.3f}") - - final_err = positions - true_positions - final_mean = float(jnp.mean(jnp.abs(final_err))) - improvement = (init_err - final_mean) / init_err * 100 - - print(f"\nResult: {init_err:.2f} cm → {final_mean:.3f} cm ({improvement:.1f}% improvement)") - - -if __name__ == "__main__": - main() diff --git a/closure/archive/gradient_test/gradient_test/test_onthefly_kernels.py b/closure/archive/gradient_test/gradient_test/test_onthefly_kernels.py deleted file mode 100644 index 7fdba8f..0000000 --- a/closure/archive/gradient_test/gradient_test/test_onthefly_kernels.py +++ /dev/null @@ -1,370 +0,0 @@ -#!/usr/bin/env python3 -""" -Comprehensive gradient test with on-the-fly kernel computation. - -This script tests gradients through: -1. Recombination parameters (recomb_A, recomb_B, field_strength, density, w_value) -2. Diffusion parameters (diffusion_long, diffusion_trans) with on-the-fly computation - -The key insight is that when kernels are computed on-the-fly (hit path), the -diffusion parameters flow through the Gaussian computations and are differentiable. -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np -from functools import partial - -from physics_params import create_default_params, PhysicsParams, PARAM_INFO -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params -from tools.wires import ( - compute_transverse_diffusion, - compute_longitudinal_diffusion, - compute_wire_distances, - accumulate_signals -) -# Attenuation computed inline - no need for import - - -def test_gradient(name, loss_fn, params, param_names, eps=1e-3): - """Test analytical vs numerical gradients with detailed reporting.""" - print(f"\n{'='*70}") - print(f"TEST: {name}") - print('='*70) - - # Try analytical gradient - try: - grad_fn = jax.grad(loss_fn) - grads = grad_fn(params) - analytical_works = True - except Exception as e: - print(f"Analytical gradient FAILED: {e}") - analytical_works = False - grads = None - - # Numerical comparison - print(f"\n{'Parameter':<28} {'Analytical':>14} {'Numerical':>14} {'Rel Diff':>12} {'Match':>8}") - print('-'*80) - - all_match = True - results = {} - - for param_name in param_names: - base_val = getattr(params, param_name) - step = eps * max(abs(base_val), 1e-8) - - params_plus = params._replace(**{param_name: base_val + step}) - params_minus = params._replace(**{param_name: base_val - step}) - - loss_plus = float(loss_fn(params_plus)) - loss_minus = float(loss_fn(params_minus)) - num_grad = (loss_plus - loss_minus) / (2 * step) - - if analytical_works: - ana_grad = float(getattr(grads, param_name)) - if abs(num_grad) > 1e-10: - rel_diff = abs(ana_grad - num_grad) / abs(num_grad) - match = "YES" if rel_diff < 0.1 else "NO" - if rel_diff >= 0.1: - all_match = False - else: - rel_diff = 0.0 if abs(ana_grad) < 1e-6 else float('inf') - match = "~0" if abs(ana_grad) < 1e-6 else "CHECK" - print(f"{param_name:<28} {ana_grad:>14.4e} {num_grad:>14.4e} {rel_diff:>12.2e} {match:>8}") - results[param_name] = {'analytical': ana_grad, 'numerical': num_grad, 'rel_diff': rel_diff, 'match': match == "YES"} - else: - print(f"{param_name:<28} {'FAILED':>14} {num_grad:>14.4e} {'N/A':>12} {'N/A':>8}") - results[param_name] = {'analytical': None, 'numerical': num_grad, 'rel_diff': None, 'match': False} - - status = "PASS" if analytical_works and all_match else "PARTIAL" if analytical_works else "FAIL" - print(f"\nStatus: {status}") - return {'success': analytical_works and all_match, 'results': results, 'grads': grads} - - -def create_full_simulation_loss(de, dx, positions_cm, detector_config): - """ - Create a loss function that runs the full simulation with on-the-fly diffusion. - - This implements the "hit path" where diffusion is computed directly. - """ - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_ms = detector_config['electron_lifetime_ms'] - electron_lifetime_us = electron_lifetime_ms * 1000.0 # convert to us - # Wire spacing from the first plane of first side - wire_spacing = float(detector_config['wire_spacings_cm'][0, 0]) - time_step_size = detector_config['time_step_size_us'] - - # Calculate drift times from x positions - drift_times = jnp.abs(positions_cm[:, 0]) / drift_velocity - - # Wire plane parameters (simplified - using Y plane at z=0) - num_wires = 200 - num_time_steps = 500 - K_wire = 5 # Half-width for wire kernel - K_time = 10 # Half-width for time kernel - - # Wire indices based on z positions - z_positions = positions_cm[:, 2] - wire_index_offset = num_wires // 2 - - def simulation_loss(physics_params): - """Full simulation loss with on-the-fly diffusion.""" - # 1. Recombination: energy -> charge - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - - # 2. Attenuation - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - # 3. Compute diffusion sigmas from physics params - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times - - # Ensure minimum sigma - min_sigma_sq = 1e-8 - sigma_wire_sq = jnp.maximum(sigma_wire_sq, min_sigma_sq) - sigma_time_sq = jnp.maximum(sigma_time_sq, min_sigma_sq) - - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - # 4. Wire and time indices (discrete - not differentiable) - center_wire = jnp.floor(z_positions / wire_spacing + wire_index_offset).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - # Wire and time offsets from bin centers - wire_offset = z_positions / wire_spacing + wire_index_offset - center_wire.astype(jnp.float32) - time_offset = drift_times / time_step_size - center_time.astype(jnp.float32) - - # 5. Build kernel contributions with on-the-fly Gaussian diffusion - # Create kernel grids - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) # [-K_wire, ..., K_wire] - time_offsets_k = jnp.arange(-K_time, K_time + 1) # [-K_time, ..., K_time] - - # Expand for broadcasting: (n_hits, 1), (2K+1,) -> (n_hits, 2K+1) - wire_distances = (wire_offsets_k[None, :] - wire_offset[:, None]) * wire_spacing - time_distances = (time_offsets_k[None, :] - time_offset[:, None]) * time_step_size - - # Gaussian diffusion (on-the-fly computation - differentiable!) - # wire_gauss: shape (n_hits, 2*K_wire+1) - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None]) - # time_gauss: shape (n_hits, 2*K_time+1) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None]) - - # Outer product: (n_hits, 2*K_wire+1, 2*K_time+1) - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - - # Scale by charge: (n_hits, 2*K_wire+1, 2*K_time+1) - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - # 6. Compute wire and time indices for each kernel element - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] # (n_hits, 2*K_wire+1) - time_indices_k = center_time[:, None] + time_offsets_k[None, :] # (n_hits, 2*K_time+1) - - # Clip to valid range - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - # 7. Scatter-add to wireplane - # Flatten for scatter - n_hits = de.shape[0] - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - # Create full index arrays for broadcasting - # wire_indices: (n_hits, n_wire_k) -> (n_hits, n_wire_k, n_time_k) - # time_indices: (n_hits, n_time_k) -> (n_hits, n_wire_k, n_time_k) - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_hits, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_hits, n_wire_k, n_time_k)) - - # Flatten everything - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - # Initialize and scatter - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - # 8. Loss: sum of squares (simple loss that exercises all operations) - return jnp.sum(wireplane ** 2) - - return simulation_loss - - -def main(): - print("="*70) - print("JAXTPC Gradient Analysis: On-The-Fly Kernel Computation") - print("="*70) - print(f"\nJAX version: {jax.__version__}") - print(f"JAX devices: {jax.devices()}") - - # Load data - print("\nLoading data...") - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - # Use subset for faster testing - n_test = 500 - de = jnp.asarray(step_data['de'][:n_test], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_test], dtype=jnp.float32) - positions_mm = jnp.asarray(step_data['position'][:n_test], dtype=jnp.float32) - positions_cm = positions_mm / 10.0 - - print(f"Using {n_test} particle steps") - print(f"Total energy deposited: {float(jnp.sum(de)):.4f} MeV") - - params = create_default_params() - drift_velocity = detector_config['drift_velocity_cm_us'] - drift_times = jnp.abs(positions_cm[:, 0]) / drift_velocity - - results = {} - - # ========================================================================= - # TEST 1: Recombination Only - # ========================================================================= - def recomb_loss(physics_params): - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - return jnp.sum(charges ** 2) - - results['recombination'] = test_gradient( - "Recombination Parameters", - recomb_loss, params, - ['recomb_A', 'recomb_B', 'field_strength', 'density', 'w_value'] - ) - - # ========================================================================= - # TEST 2: Diffusion Functions Only (On-The-Fly) - # ========================================================================= - def diffusion_only_loss(physics_params): - # Compute diffusion sigmas - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times - - sigma_wire = jnp.sqrt(jnp.maximum(sigma_wire_sq, 1e-10)) - sigma_time = jnp.sqrt(jnp.maximum(sigma_time_sq, 1e-10)) - - return jnp.sum(sigma_wire + sigma_time) - - results['diffusion_only'] = test_gradient( - "Diffusion Parameters (Direct Computation)", - diffusion_only_loss, params, - ['diffusion_long', 'diffusion_trans'] - ) - - # ========================================================================= - # TEST 3: Combined Recombination + Diffusion - # ========================================================================= - def combined_loss(physics_params): - # Recombination - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - - # Diffusion sigmas - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times - sigma_wire = jnp.sqrt(jnp.maximum(sigma_wire_sq, 1e-10)) - sigma_time = jnp.sqrt(jnp.maximum(sigma_time_sq, 1e-10)) - - # Combine: charge weighted by inverse spread - spread = 1.0 / (sigma_wire * sigma_time + 1e-10) - return jnp.sum(charges * spread) - - results['combined'] = test_gradient( - "Combined Recombination + Diffusion", - combined_loss, params, - ['recomb_A', 'recomb_B', 'diffusion_long', 'diffusion_trans'] - ) - - # ========================================================================= - # TEST 4: Full Simulation with On-The-Fly Kernels - # ========================================================================= - simulation_loss = create_full_simulation_loss(de, dx, positions_cm, detector_config) - - results['full_simulation'] = test_gradient( - "Full Simulation (On-The-Fly Kernels)", - simulation_loss, params, - ['recomb_A', 'recomb_B', 'diffusion_long', 'diffusion_trans'] - ) - - # ========================================================================= - # TEST 5: All Recombination Parameters in Full Simulation - # ========================================================================= - results['full_recomb'] = test_gradient( - "Full Simulation - All Recombination Params", - simulation_loss, params, - ['recomb_A', 'recomb_B', 'field_strength', 'density', 'w_value'] - ) - - # ========================================================================= - # SUMMARY - # ========================================================================= - print("\n" + "="*70) - print("SUMMARY: Gradient Analysis Results") - print("="*70) - - print("\nTest Results:") - print("-"*50) - for test_name, result in results.items(): - status = "PASS" if result['success'] else "FAIL" - print(f" {test_name:<35}: {status}") - - print("\n" + "="*70) - print("KEY FINDINGS") - print("="*70) - - print(""" -Differentiable Operations (Gradients Flow Through): - ✓ Recombination (Box Model): recomb_A, recomb_B, field_strength, density, w_value - ✓ Diffusion sigma computation: diffusion_long, diffusion_trans - ✓ On-the-fly Gaussian kernels: exp(-d²/2σ²) where σ depends on params - ✓ Scatter-add VALUES: wireplane.at[idx].add(values) - ✓ Attenuation: exp(-t/τ) - -Non-Differentiable (Constant w.r.t. params): - ✗ Wire/time INDEX computation: floor() -> astype(int32) - ✗ K_wire, K_time: static kernel sizes - -Key Insight: - When computing kernels ON-THE-FLY, diffusion parameters ARE differentiable. - The Gaussian kernel values depend on σ which depends on diffusion coefficients. - Gradients flow through the kernel VALUES, not the kernel indices. -""") - - print("="*70) - - # Save results - os.makedirs('results', exist_ok=True) - with open('results/onthefly_gradient_report.txt', 'w') as f: - f.write("JAXTPC Gradient Analysis: On-The-Fly Kernel Computation\n") - f.write("="*60 + "\n\n") - - for test_name, result in results.items(): - f.write(f"\n{test_name.upper()}\n") - f.write("-"*40 + "\n") - f.write(f"Status: {'PASS' if result['success'] else 'FAIL'}\n\n") - - for param_name, data in result['results'].items(): - f.write(f" {param_name}:\n") - f.write(f" Analytical: {data['analytical']}\n") - f.write(f" Numerical: {data['numerical']}\n") - if data['rel_diff'] is not None: - f.write(f" Rel Diff: {data['rel_diff']:.2e}\n") - f.write(f" Match: {data['match']}\n\n") - - print(f"\nReport saved to: results/onthefly_gradient_report.txt") - - return all(r['success'] for r in results.values()) - - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/closure/archive/gradient_test/gradient_test/test_per_plane_gradient.py b/closure/archive/gradient_test/gradient_test/test_per_plane_gradient.py deleted file mode 100644 index e512cb1..0000000 --- a/closure/archive/gradient_test/gradient_test/test_per_plane_gradient.py +++ /dev/null @@ -1,274 +0,0 @@ -#!/usr/bin/env python3 -""" -Per-Plane Gradient Analysis - -Test each wire plane separately to understand gradient contributions. -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np - -from physics_params import create_default_params -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - - -def main(): - print("="*70) - print("Per-Plane Gradient Analysis") - print("="*70) - - # Load data - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - n_test = 50 - de = jnp.asarray(step_data['de'][:n_test], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_test], dtype=jnp.float32) - positions_cm = jnp.asarray(step_data['position'][:n_test], dtype=jnp.float32) / 10.0 - - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 - time_step_size = detector_config['time_step_size_us'] - angles_rad = detector_config['angles_rad'][0] - wire_spacings_cm = detector_config['wire_spacings_cm'][0] - - physics_params = create_default_params() - - num_wires = 200 - num_time_steps = 500 - K_wire = 3 - K_time = 5 - - plane_names = ['U (+60°)', 'V (-60°)', 'Y (0°)'] - - print(f"\nWire plane configuration:") - for i, name in enumerate(plane_names): - angle = float(angles_rad[i]) - print(f" {name}: angle={np.degrees(angle):.1f}°, sin={np.sin(angle):.3f}, cos={np.cos(angle):.3f}") - - def compute_wireplane_for_plane(positions_cm, plane_idx): - """Compute wireplane for a single plane.""" - angle = angles_rad[plane_idx] - wire_spacing = float(wire_spacings_cm[plane_idx]) - - x_pos = positions_cm[:, 0] - y_pos = positions_cm[:, 1] - z_pos = positions_cm[:, 2] - - drift_times = jnp.abs(x_pos) / drift_velocity - - # Wire coordinate using angle - cos_angle = jnp.cos(angle) - sin_angle = jnp.sin(angle) - wire_coord = y_pos * sin_angle + z_pos * cos_angle - - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - wire_pos = wire_coord / wire_spacing + num_wires // 2 - center_wire = jnp.floor(wire_pos).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - wire_offset = wire_pos - center_wire.astype(jnp.float32) - time_offset = drift_times / time_step_size - center_time.astype(jnp.float32) - - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) - time_offsets_k = jnp.arange(-K_time, K_time + 1) - - wire_distances = (wire_offsets_k[None, :] - wire_offset[:, None]) * wire_spacing - time_distances = (time_offsets_k[None, :] - time_offset[:, None]) * time_step_size - - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None] + 1e-12) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None] + 1e-12) - - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] - time_indices_k = center_time[:, None] + time_offsets_k[None, :] - - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_test, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_test, n_wire_k, n_time_k)) - - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - return wireplane - - # Compute reference wireplanes - ref_wireplanes = [compute_wireplane_for_plane(positions_cm, i) for i in range(3)] - - print("\n" + "="*70) - print("Per-Plane Gradient Test") - print("="*70) - - # Test each plane separately - for plane_idx in range(3): - ref_wp = ref_wireplanes[plane_idx] - - def single_plane_loss(position_offsets): - pos = positions_cm + position_offsets - wp = compute_wireplane_for_plane(pos, plane_idx) - return jnp.mean((wp - ref_wp) ** 2) - - print(f"\n--- {plane_names[plane_idx]} ---") - - # Small offset - offset = jnp.zeros((n_test, 3)) - offset = offset.at[:, 0].set(0.05) - offset = offset.at[:, 1].set(0.05) - offset = offset.at[:, 2].set(0.05) - - loss = float(single_plane_loss(offset)) - print(f"Loss at (0.05, 0.05, 0.05) offset: {loss:.4e}") - - # Gradients - grad_fn = jax.grad(single_plane_loss) - grads = grad_fn(offset) - - print(f"Mean gradients:") - print(f" ∂L/∂x = {float(jnp.mean(grads[:,0])):>12.4e}") - print(f" ∂L/∂y = {float(jnp.mean(grads[:,1])):>12.4e}") - print(f" ∂L/∂z = {float(jnp.mean(grads[:,2])):>12.4e}") - - # Numerical verification - eps = 1e-4 - print(f"\nNumerical check (first segment, eps={eps}):") - for d, dim_name in enumerate(['x', 'y', 'z']): - delta = jnp.zeros((n_test, 3)) - delta = delta.at[0, d].set(eps) - num_grad = (single_plane_loss(offset + delta) - single_plane_loss(offset - delta)) / (2 * eps) - ana_grad = float(grads[0, d]) - - if abs(float(num_grad)) > 1e-12: - rel_diff = abs(ana_grad - float(num_grad)) / abs(float(num_grad)) - status = "MATCH" if rel_diff < 0.3 else "DIFF" - elif abs(ana_grad) < 1e-10: - status = "BOTH~0" - else: - status = "ANA≠0" - - print(f" ∂L/∂{dim_name}: ana={ana_grad:>12.4e}, num={float(num_grad):>12.4e} [{status}]") - - # Check expected gradient relationship - angle = float(angles_rad[plane_idx]) - sin_a = np.sin(angle) - cos_a = np.cos(angle) - - mean_y = float(jnp.mean(grads[:,1])) - mean_z = float(jnp.mean(grads[:,2])) - - print(f"\nGradient relationship check:") - print(f" sin({np.degrees(angle):.0f}°) = {sin_a:.4f}") - print(f" cos({np.degrees(angle):.0f}°) = {cos_a:.4f}") - - if abs(mean_z) > 1e-10 and abs(cos_a) > 0.01: - # ∂L/∂r is common to both - # ∂L/∂y = ∂L/∂r * sin(a), ∂L/∂z = ∂L/∂r * cos(a) - # So ∂L/∂y / sin(a) ≈ ∂L/∂z / cos(a) - ratio_y = mean_y / sin_a if abs(sin_a) > 0.01 else float('inf') - ratio_z = mean_z / cos_a - print(f" ∂L/∂y / sin(a) = {ratio_y:.4e}") - print(f" ∂L/∂z / cos(a) = {ratio_z:.4e}") - if abs(ratio_y) < float('inf') and abs(ratio_z) > 0: - print(f" Ratio = {abs(ratio_y/ratio_z):.4f} (should be ~1.0)") - - # Combined test - print("\n" + "="*70) - print("Combined (All Planes) Gradient Test") - print("="*70) - - def all_planes_loss(position_offsets): - pos = positions_cm + position_offsets - total_loss = 0.0 - for i in range(3): - wp = compute_wireplane_for_plane(pos, i) - total_loss += jnp.mean((wp - ref_wireplanes[i]) ** 2) - return total_loss / 3.0 - - offset = jnp.zeros((n_test, 3)) - offset = offset.at[:, 0].set(0.05) - offset = offset.at[:, 1].set(0.05) - offset = offset.at[:, 2].set(0.05) - - grad_fn = jax.grad(all_planes_loss) - grads = grad_fn(offset) - - print(f"\nCombined mean gradients:") - print(f" ∂L/∂x = {float(jnp.mean(grads[:,0])):>12.4e}") - print(f" ∂L/∂y = {float(jnp.mean(grads[:,1])):>12.4e}") - print(f" ∂L/∂z = {float(jnp.mean(grads[:,2])):>12.4e}") - - print("\nNumerical check (first segment):") - eps = 1e-4 - for d, dim_name in enumerate(['x', 'y', 'z']): - delta = jnp.zeros((n_test, 3)) - delta = delta.at[0, d].set(eps) - num_grad = (all_planes_loss(offset + delta) - all_planes_loss(offset - delta)) / (2 * eps) - ana_grad = float(grads[0, d]) - - if abs(float(num_grad)) > 1e-12: - rel_diff = abs(ana_grad - float(num_grad)) / abs(float(num_grad)) - status = "MATCH" if rel_diff < 0.3 else "DIFF" - else: - status = "BOTH~0" if abs(ana_grad) < 1e-10 else "ANA≠0" - - print(f" ∂L/∂{dim_name}: ana={ana_grad:>12.4e}, num={float(num_grad):>12.4e} [{status}]") - - print("\n" + "="*70) - print("CONCLUSION") - print("="*70) - print(""" -Per-plane gradient analysis shows: - -1. Y plane (0°): Only Z contributes (sin(0)=0) - - ∂L/∂y ≈ 0 (expected!) - - ∂L/∂z is strong - -2. U plane (+60°): Both Y and Z contribute - - ∂L/∂y ∝ sin(60°) = 0.866 - - ∂L/∂z ∝ cos(60°) = 0.5 - -3. V plane (-60°): Both Y and Z contribute - - ∂L/∂y ∝ sin(-60°) = -0.866 (opposite sign to U!) - - ∂L/∂z ∝ cos(-60°) = 0.5 - -When combining U and V planes: -- Z gradients ADD (both have cos(±60°) = 0.5) -- Y gradients CANCEL (sin(60°) + sin(-60°) = 0) - -This explains why combined Y gradient is weak while Z is strong. -For full 3D position recovery, need planes that don't cancel! -""") - - return True - - -if __name__ == "__main__": - main() diff --git a/closure/archive/gradient_test/gradient_test/test_per_segment.py b/closure/archive/gradient_test/gradient_test/test_per_segment.py deleted file mode 100644 index 85659a3..0000000 --- a/closure/archive/gradient_test/gradient_test/test_per_segment.py +++ /dev/null @@ -1,187 +0,0 @@ -#!/usr/bin/env python3 -""" -Per-Segment Position Gradient Test - -Simple test: verify each segment has independent position gradients. -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np - -from physics_params import create_default_params -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - - -def main(): - print("="*60) - print("Per-Segment Position Gradient Test") - print("="*60) - - # Load data - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - n_test = 10 # Small number for clarity - de = jnp.asarray(step_data['de'][:n_test], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_test], dtype=jnp.float32) - positions_cm = jnp.asarray(step_data['position'][:n_test], dtype=jnp.float32) / 10.0 - - # Detector params - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 - time_step_size = detector_config['time_step_size_us'] - num_time_steps = detector_config['num_time_steps'] - - angles_rad = detector_config['angles_rad'][0] - wire_spacings_cm = detector_config['wire_spacings_cm'][0] - index_offsets = detector_config['index_offsets'][0] - num_wires_actual = detector_config['num_wires_actual'][0] - - physics_params = create_default_params() - K_wire = 3 - K_time = 5 - - def compute_wireplane(positions_cm, plane_idx): - """Compute wireplane for one plane.""" - angle = angles_rad[plane_idx] - wire_spacing = float(wire_spacings_cm[plane_idx]) - wire_offset = float(index_offsets[plane_idx]) - num_wires = int(num_wires_actual[plane_idx]) - - x_pos = positions_cm[:, 0] - y_pos = positions_cm[:, 1] - z_pos = positions_cm[:, 2] - - drift_times = jnp.abs(x_pos) / drift_velocity - wire_coord = y_pos * jnp.sin(angle) + z_pos * jnp.cos(angle) - - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - wire_pos = wire_coord / wire_spacing + wire_offset - center_wire = jnp.floor(wire_pos).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - wire_subbin = wire_pos - center_wire.astype(jnp.float32) - time_subbin = drift_times / time_step_size - center_time.astype(jnp.float32) - - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) - time_offsets_k = jnp.arange(-K_time, K_time + 1) - - wire_distances = (wire_offsets_k[None, :] - wire_subbin[:, None]) * wire_spacing - time_distances = (time_offsets_k[None, :] - time_subbin[:, None]) * time_step_size - - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None] + 1e-12) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None] + 1e-12) - - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] - time_indices_k = center_time[:, None] + time_offsets_k[None, :] - - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_test, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_test, n_wire_k, n_time_k)) - - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - return wireplane - - # Compute reference wireplanes - ref_wireplanes = [compute_wireplane(positions_cm, i) for i in range(3)] - - def loss_fn(pos_offsets): - """MSE loss over all planes.""" - pos = positions_cm + pos_offsets - total_loss = 0.0 - for i in range(3): - wp = compute_wireplane(pos, i) - total_loss += jnp.mean((wp - ref_wireplanes[i]) ** 2) - return total_loss / 3.0 - - # Test gradients - print(f"\nTesting {n_test} segments") - print("-"*60) - - offset = jnp.ones((n_test, 3)) * 0.05 # 0.5mm offset in each direction - - grad_fn = jax.grad(loss_fn) - grads = grad_fn(offset) - - print("\nPer-segment gradients (analytical):") - print(f"{'Seg':>4} {'∂L/∂x':>12} {'∂L/∂y':>12} {'∂L/∂z':>12}") - print("-"*44) - for i in range(n_test): - print(f"{i:>4} {float(grads[i,0]):>12.4e} {float(grads[i,1]):>12.4e} {float(grads[i,2]):>12.4e}") - - # Numerical verification for first 3 segments - print("\n" + "="*60) - print("Numerical Verification (first 3 segments)") - print("="*60) - - eps = 1e-4 - for seg_idx in range(3): - print(f"\nSegment {seg_idx}:") - for d, dim in enumerate(['x', 'y', 'z']): - delta = jnp.zeros((n_test, 3)) - delta = delta.at[seg_idx, d].set(eps) - - loss_plus = loss_fn(offset + delta) - loss_minus = loss_fn(offset - delta) - num_grad = (loss_plus - loss_minus) / (2 * eps) - ana_grad = float(grads[seg_idx, d]) - - if abs(float(num_grad)) > 1e-12: - rel_err = abs(ana_grad - float(num_grad)) / abs(float(num_grad)) - status = "MATCH" if rel_err < 0.3 else "DIFF" - else: - status = "BOTH~0" if abs(ana_grad) < 1e-10 else "CHECK" - - print(f" ∂L/∂{dim}: ana={ana_grad:>10.4e}, num={float(num_grad):>10.4e} [{status}]") - - # Summary - print("\n" + "="*60) - print("SUMMARY") - print("="*60) - print(f"Total segments: {n_test}") - print(f"Gradient shape: {grads.shape}") - print(f"\nMean gradients:") - print(f" ∂L/∂x: {float(jnp.mean(grads[:,0])):.4e}") - print(f" ∂L/∂y: {float(jnp.mean(grads[:,1])):.4e}") - print(f" ∂L/∂z: {float(jnp.mean(grads[:,2])):.4e}") - - all_nonzero = jnp.all(jnp.abs(grads) > 1e-12) - print(f"\nAll gradients non-zero: {bool(all_nonzero)}") - - return True - - -if __name__ == "__main__": - main() diff --git a/closure/archive/gradient_test/gradient_test/test_position_centered.py b/closure/archive/gradient_test/gradient_test/test_position_centered.py deleted file mode 100644 index 61bf0f5..0000000 --- a/closure/archive/gradient_test/gradient_test/test_position_centered.py +++ /dev/null @@ -1,304 +0,0 @@ -#!/usr/bin/env python3 -""" -Position Gradient Analysis with Properly Centered Wire Planes - -Key fix: Compute wire plane offsets based on actual data positions so -all planes have valid wire indices. -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np - -from physics_params import create_default_params -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - - -def main(): - print("="*70) - print("Position Gradient Analysis - Properly Centered") - print("="*70) - - # Load data - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - n_test = 50 - de = jnp.asarray(step_data['de'][:n_test], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_test], dtype=jnp.float32) - positions_cm = jnp.asarray(step_data['position'][:n_test], dtype=jnp.float32) / 10.0 - - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 - time_step_size = detector_config['time_step_size_us'] - angles_rad = detector_config['angles_rad'][0] - wire_spacings_cm = detector_config['wire_spacings_cm'][0] - - physics_params = create_default_params() - - num_wires = 200 - num_time_steps = 500 - K_wire = 3 - K_time = 5 - - plane_names = ['U (+60°)', 'V (-60°)', 'Y (0°)'] - - # Compute proper center offsets for each plane based on data - y_mean = float(jnp.mean(positions_cm[:, 1])) - z_mean = float(jnp.mean(positions_cm[:, 2])) - - print(f"\nData center: y={y_mean:.2f} cm, z={z_mean:.2f} cm") - - # For each plane, compute the wire coordinate at data center - # and use that to set the offset so data lands at num_wires//2 - plane_offsets = [] - for i, (angle, spacing) in enumerate(zip(angles_rad, wire_spacings_cm)): - cos_a = float(jnp.cos(angle)) - sin_a = float(jnp.sin(angle)) - wire_coord_at_center = y_mean * sin_a + z_mean * cos_a - # We want wire_coord_at_center / spacing + offset = num_wires // 2 - offset = num_wires // 2 - wire_coord_at_center / spacing - plane_offsets.append(offset) - print(f" {plane_names[i]}: wire_coord_center={wire_coord_at_center:.2f}, offset={offset:.2f}") - - def compute_wireplane_for_plane(positions_cm, plane_idx): - """Compute wireplane for a single plane with proper offset.""" - angle = angles_rad[plane_idx] - wire_spacing = float(wire_spacings_cm[plane_idx]) - wire_offset = plane_offsets[plane_idx] - - x_pos = positions_cm[:, 0] - y_pos = positions_cm[:, 1] - z_pos = positions_cm[:, 2] - - drift_times = jnp.abs(x_pos) / drift_velocity - - # Wire coordinate using angle - THIS IS WHERE Y AND Z BOTH CONTRIBUTE - cos_angle = jnp.cos(angle) - sin_angle = jnp.sin(angle) - wire_coord = y_pos * sin_angle + z_pos * cos_angle - - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - # Wire position with proper offset - wire_pos = wire_coord / wire_spacing + wire_offset - center_wire = jnp.floor(wire_pos).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - wire_subbin = wire_pos - center_wire.astype(jnp.float32) - time_subbin = drift_times / time_step_size - center_time.astype(jnp.float32) - - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) - time_offsets_k = jnp.arange(-K_time, K_time + 1) - - wire_distances = (wire_offsets_k[None, :] - wire_subbin[:, None]) * wire_spacing - time_distances = (time_offsets_k[None, :] - time_subbin[:, None]) * time_step_size - - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None] + 1e-12) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None] + 1e-12) - - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] - time_indices_k = center_time[:, None] + time_offsets_k[None, :] - - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_test, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_test, n_wire_k, n_time_k)) - - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - return wireplane - - # Verify wire positions are now valid - print("\nVerifying wire positions after centering:") - y = positions_cm[:, 1] - z = positions_cm[:, 2] - for i, (angle, spacing, offset) in enumerate(zip(angles_rad, wire_spacings_cm, plane_offsets)): - cos_a = np.cos(float(angle)) - sin_a = np.sin(float(angle)) - wire_coord = y * sin_a + z * cos_a - wire_pos = wire_coord / spacing + offset - print(f" {plane_names[i]}: wire_pos = [{float(wire_pos.min()):.1f}, {float(wire_pos.max()):.1f}]") - - # Compute reference wireplanes - ref_wireplanes = [compute_wireplane_for_plane(positions_cm, i) for i in range(3)] - - print("\n" + "="*70) - print("Per-Plane Gradient Test (Centered)") - print("="*70) - - # Test each plane separately - for plane_idx in range(3): - ref_wp = ref_wireplanes[plane_idx] - - def single_plane_loss(position_offsets): - pos = positions_cm + position_offsets - wp = compute_wireplane_for_plane(pos, plane_idx) - return jnp.mean((wp - ref_wp) ** 2) - - print(f"\n--- {plane_names[plane_idx]} ---") - - offset = jnp.zeros((n_test, 3)) - offset = offset.at[:, 0].set(0.05) - offset = offset.at[:, 1].set(0.05) - offset = offset.at[:, 2].set(0.05) - - loss = float(single_plane_loss(offset)) - print(f"Loss at (0.05, 0.05, 0.05): {loss:.4e}") - - grad_fn = jax.grad(single_plane_loss) - grads = grad_fn(offset) - - print(f"Mean gradients:") - print(f" ∂L/∂x = {float(jnp.mean(grads[:,0])):>12.4e}") - print(f" ∂L/∂y = {float(jnp.mean(grads[:,1])):>12.4e}") - print(f" ∂L/∂z = {float(jnp.mean(grads[:,2])):>12.4e}") - - # Numerical verification - eps = 1e-4 - print(f"\nNumerical check (segment 0, eps={eps}):") - for d, dim_name in enumerate(['x', 'y', 'z']): - delta = jnp.zeros((n_test, 3)) - delta = delta.at[0, d].set(eps) - num_grad = (single_plane_loss(offset + delta) - single_plane_loss(offset - delta)) / (2 * eps) - ana_grad = float(grads[0, d]) - - if abs(float(num_grad)) > 1e-12: - rel_diff = abs(ana_grad - float(num_grad)) / abs(float(num_grad)) - status = "MATCH" if rel_diff < 0.5 else "DIFF" - elif abs(ana_grad) < 1e-10: - status = "BOTH~0" - else: - status = "ANA≠0" - - print(f" ∂L/∂{dim_name}: ana={ana_grad:>12.4e}, num={float(num_grad):>12.4e} [{status}]") - - # Gradient relationship - angle = float(angles_rad[plane_idx]) - sin_a = np.sin(angle) - cos_a = np.cos(angle) - mean_y = float(jnp.mean(grads[:,1])) - mean_z = float(jnp.mean(grads[:,2])) - - print(f"\nTheoretical relationship:") - print(f" sin({np.degrees(angle):.0f}°) = {sin_a:.4f}") - print(f" cos({np.degrees(angle):.0f}°) = {cos_a:.4f}") - if abs(sin_a) > 0.01 and abs(cos_a) > 0.01: - ratio = (mean_y / sin_a) / (mean_z / cos_a) if abs(mean_z) > 1e-10 else float('inf') - print(f" (∂L/∂y / sin) / (∂L/∂z / cos) = {ratio:.4f} (should be ~1.0)") - - # Combined test - print("\n" + "="*70) - print("Combined (All Planes) Gradient Test") - print("="*70) - - def all_planes_loss(position_offsets): - pos = positions_cm + position_offsets - total_loss = 0.0 - for i in range(3): - wp = compute_wireplane_for_plane(pos, i) - total_loss += jnp.mean((wp - ref_wireplanes[i]) ** 2) - return total_loss / 3.0 - - offset = jnp.zeros((n_test, 3)) - offset = offset.at[:, 0].set(0.05) - offset = offset.at[:, 1].set(0.05) - offset = offset.at[:, 2].set(0.05) - - loss_combined = float(all_planes_loss(offset)) - print(f"\nCombined loss at offset: {loss_combined:.4e}") - - grad_fn = jax.grad(all_planes_loss) - grads = grad_fn(offset) - - print(f"\nCombined mean gradients:") - print(f" ∂L/∂x = {float(jnp.mean(grads[:,0])):>12.4e}") - print(f" ∂L/∂y = {float(jnp.mean(grads[:,1])):>12.4e}") - print(f" ∂L/∂z = {float(jnp.mean(grads[:,2])):>12.4e}") - - print("\nNumerical check (segment 0):") - eps = 1e-4 - for d, dim_name in enumerate(['x', 'y', 'z']): - delta = jnp.zeros((n_test, 3)) - delta = delta.at[0, d].set(eps) - num_grad = (all_planes_loss(offset + delta) - all_planes_loss(offset - delta)) / (2 * eps) - ana_grad = float(grads[0, d]) - - if abs(float(num_grad)) > 1e-12: - rel_diff = abs(ana_grad - float(num_grad)) / abs(float(num_grad)) - status = "MATCH" if rel_diff < 0.5 else "DIFF" - else: - status = "BOTH~0" if abs(ana_grad) < 1e-10 else "ANA≠0" - - print(f" ∂L/∂{dim_name}: ana={ana_grad:>12.4e}, num={float(num_grad):>12.4e} [{status}]") - - # Loss landscape - print("\n" + "="*70) - print("Loss Landscape (single dimension variations)") - print("="*70) - - offsets_1d = jnp.linspace(-0.1, 0.1, 11) - - for dim, dim_name in enumerate(['X', 'Y', 'Z']): - print(f"\nVarying {dim_name}:") - print(f"{'Offset':>8} {'Loss':>12}") - print("-"*22) - for off in offsets_1d: - pos_offset = jnp.zeros((n_test, 3)) - pos_offset = pos_offset.at[:, dim].set(float(off)) - loss = float(all_planes_loss(pos_offset)) - print(f"{float(off):>8.3f} {loss:>12.4e}") - - print("\n" + "="*70) - print("SUMMARY") - print("="*70) - print(""" -With proper centering so all planes have valid wire indices: - -1. Each plane should show gradients for its contributing dimensions: - - U (+60°): ∂L/∂y ∝ sin(60°), ∂L/∂z ∝ cos(60°) - - V (-60°): ∂L/∂y ∝ sin(-60°), ∂L/∂z ∝ cos(-60°) - - Y (0°): ∂L/∂y = 0, ∂L/∂z ∝ cos(0°) = 1 - -2. Combined gradients: - - ∂L/∂z should be strong (all planes contribute) - - ∂L/∂y should be NON-ZERO from U and V planes - (Note: U and V have opposite-sign y contributions, but the LOSS - increases for either direction of y shift, so gradients add!) - -3. All three coordinates (x, y, z) should be learnable. -""") - - return True - - -if __name__ == "__main__": - main() diff --git a/closure/archive/gradient_test/gradient_test/test_position_centroid.py b/closure/archive/gradient_test/gradient_test/test_position_centroid.py deleted file mode 100644 index 81585eb..0000000 --- a/closure/archive/gradient_test/gradient_test/test_position_centroid.py +++ /dev/null @@ -1,449 +0,0 @@ -#!/usr/bin/env python3 -""" -Position Gradient Analysis with All Wire Planes and Centroid Loss - -Key improvements over v2: -1. Uses proper wire geometry with angles (Y matters!) -2. Tests all three wire planes (U, V, Y) -3. Uses position-weighted (centroid) loss - -Wire plane angles: -- U plane: +60° (or +π/3 rad) -- V plane: -60° (or -π/3 rad) -- Y plane: 0° (vertical wires) - -Wire coordinate: r = y*sin(angle) + z*cos(angle) -This makes BOTH Y and Z differentiable through the wire coordinate! -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np - -from physics_params import create_default_params, PhysicsParams -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - - -def create_multiplane_simulation(de, dx, base_positions_cm, detector_config, physics_params): - """ - Create simulation with all three wire planes (U, V, Y). - - Returns functions for computing wireplanes and centroid loss. - """ - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 - time_step_size = detector_config['time_step_size_us'] - - # Get wire plane parameters from detector config - # angles_rad shape: (2 sides, 3 planes) - # wire_spacings_cm shape: (2 sides, 3 planes) - angles_rad = detector_config['angles_rad'][0] # First side - wire_spacings_cm = detector_config['wire_spacings_cm'][0] # First side - - print(f"Wire plane angles (degrees): {np.degrees(angles_rad)}") - print(f"Wire spacings (cm): {wire_spacings_cm}") - - num_wires = 200 - num_time_steps = 500 - K_wire = 3 - K_time = 5 - - n_hits = de.shape[0] - - def compute_single_plane_wireplane(positions_cm, plane_idx): - """Compute wireplane for a single plane with proper angle.""" - angle = angles_rad[plane_idx] - wire_spacing = float(wire_spacings_cm[plane_idx]) - - x_pos = positions_cm[:, 0] - y_pos = positions_cm[:, 1] - z_pos = positions_cm[:, 2] - - drift_times = jnp.abs(x_pos) / drift_velocity - - # Wire coordinate using BOTH y and z with angle! - # r = y*sin(angle) + z*cos(angle) - cos_angle = jnp.cos(angle) - sin_angle = jnp.sin(angle) - wire_coord = y_pos * sin_angle + z_pos * cos_angle - - # Recombination and attenuation - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - # Diffusion sigmas - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - # Wire position (continuous) - using wire_coord which depends on y AND z - wire_pos = wire_coord / wire_spacing + num_wires // 2 - center_wire = jnp.floor(wire_pos).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - # Sub-bin offsets (DIFFERENTIABLE w.r.t. y and z through wire_coord!) - wire_offset = wire_pos - center_wire.astype(jnp.float32) - time_offset = drift_times / time_step_size - center_time.astype(jnp.float32) - - # Kernel computation - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) - time_offsets_k = jnp.arange(-K_time, K_time + 1) - - # Distances (differentiable through wire_offset which depends on y, z) - wire_distances = (wire_offsets_k[None, :] - wire_offset[:, None]) * wire_spacing - time_distances = (time_offsets_k[None, :] - time_offset[:, None]) * time_step_size - - # Gaussian kernels - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None] + 1e-12) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None] + 1e-12) - - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - # Scatter - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] - time_indices_k = center_time[:, None] + time_offsets_k[None, :] - - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_hits, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_hits, n_wire_k, n_time_k)) - - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - return wireplane - - def compute_all_wireplanes(positions_cm): - """Compute wireplanes for all three planes.""" - wireplanes = [] - for plane_idx in range(3): - wp = compute_single_plane_wireplane(positions_cm, plane_idx) - wireplanes.append(wp) - return wireplanes - - def compute_centroid(wireplane): - """Compute signal-weighted centroid of wireplane.""" - # Create coordinate grids - wire_coords = jnp.arange(num_wires) - time_coords = jnp.arange(num_time_steps) - wire_grid, time_grid = jnp.meshgrid(wire_coords, time_coords, indexing='ij') - - # Use absolute value for weighting (signals can be positive/negative) - weights = jnp.abs(wireplane) + 1e-12 - total_weight = jnp.sum(weights) - - centroid_wire = jnp.sum(wire_grid * weights) / total_weight - centroid_time = jnp.sum(time_grid * weights) / total_weight - - return centroid_wire, centroid_time - - def compute_all_centroids(wireplanes): - """Compute centroids for all planes.""" - centroids = [] - for wp in wireplanes: - cw, ct = compute_centroid(wp) - centroids.append((cw, ct)) - return centroids - - # Compute reference - ref_wireplanes = compute_all_wireplanes(base_positions_cm) - ref_centroids = compute_all_centroids(ref_wireplanes) - - print(f"\nReference centroids (wire, time):") - plane_names = ['U', 'V', 'Y'] - for i, (cw, ct) in enumerate(ref_centroids): - print(f" {plane_names[i]}: ({float(cw):.2f}, {float(ct):.2f})") - - def mse_loss(position_offsets): - """MSE loss comparing all wireplanes.""" - pos = base_positions_cm + position_offsets - wireplanes = compute_all_wireplanes(pos) - - total_loss = 0.0 - for i in range(3): - total_loss += jnp.mean((wireplanes[i] - ref_wireplanes[i]) ** 2) - return total_loss / 3.0 - - def centroid_loss(position_offsets): - """Loss based on centroid difference across all planes.""" - pos = base_positions_cm + position_offsets - wireplanes = compute_all_wireplanes(pos) - centroids = compute_all_centroids(wireplanes) - - total_loss = 0.0 - for i in range(3): - cw, ct = centroids[i] - ref_cw, ref_ct = ref_centroids[i] - # Squared distance in (wire, time) space - total_loss += (cw - ref_cw)**2 + (ct - ref_ct)**2 - return total_loss - - return { - 'compute_all_wireplanes': compute_all_wireplanes, - 'compute_all_centroids': compute_all_centroids, - 'mse_loss': mse_loss, - 'centroid_loss': centroid_loss, - 'ref_wireplanes': ref_wireplanes, - 'ref_centroids': ref_centroids, - 'angles_rad': angles_rad, - } - - -def test_gradient(name, loss_fn, x0, dim_names, eps=1e-4): - """Test gradients with numerical verification.""" - print(f"\n{'='*70}") - print(f"TEST: {name}") - print('='*70) - - n_dims = x0.shape[-1] if x0.ndim > 1 else 1 - - try: - grad_fn = jax.grad(loss_fn) - grads = grad_fn(x0) - print(f"Gradient shape: {grads.shape}") - except Exception as e: - print(f"FAILED: {e}") - return None - - # Per-dimension stats - print(f"\nPer-Dimension Gradient Statistics:") - for d in range(n_dims): - if x0.ndim > 1: - g = grads[:, d] - else: - g = grads - print(f" {dim_names[d]:>12}: min={float(jnp.min(g)):>12.4e}, max={float(jnp.max(g)):>12.4e}") - print(f" mean={float(jnp.mean(g)):>12.4e}, std={float(jnp.std(g)):>12.4e}") - - # Numerical verification - print(f"\nNumerical Verification (eps={eps}):") - print(f"{'Dim':<12} {'Analytical':>14} {'Numerical':>14} {'Rel Diff':>12} {'Status':>10}") - print("-"*65) - - for d in range(n_dims): - if x0.ndim > 1: - delta = jnp.zeros_like(x0) - delta = delta.at[0, d].set(eps) - ana_grad = float(grads[0, d]) - else: - delta = jnp.zeros_like(x0) - delta = delta.at[d].set(eps) - ana_grad = float(grads[d]) - - num_grad = (float(loss_fn(x0 + delta)) - float(loss_fn(x0 - delta))) / (2 * eps) - - if abs(num_grad) > 1e-12: - rel_diff = abs(ana_grad - num_grad) / abs(num_grad) - status = "MATCH" if rel_diff < 0.3 else "DIFF" - elif abs(ana_grad) < 1e-10: - rel_diff = 0.0 - status = "BOTH~0" - else: - rel_diff = float('inf') - status = "ANA≠0" - - print(f"{dim_names[d]:<12} {ana_grad:>14.4e} {num_grad:>14.4e} {rel_diff:>12.2e} {status:>10}") - - return grads - - -def main(): - print("="*70) - print("Position Gradient Analysis with All Wire Planes") - print("Testing Y/Z Symmetry and Centroid Loss") - print("="*70) - - # Load data - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - n_test = 50 - de = jnp.asarray(step_data['de'][:n_test], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_test], dtype=jnp.float32) - positions_mm = jnp.asarray(step_data['position'][:n_test], dtype=jnp.float32) - positions_cm = positions_mm / 10.0 - - print(f"\nUsing {n_test} particle steps") - print(f"Position range:") - print(f" X: [{float(jnp.min(positions_cm[:,0])):.1f}, {float(jnp.max(positions_cm[:,0])):.1f}] cm") - print(f" Y: [{float(jnp.min(positions_cm[:,1])):.1f}, {float(jnp.max(positions_cm[:,1])):.1f}] cm") - print(f" Z: [{float(jnp.min(positions_cm[:,2])):.1f}, {float(jnp.max(positions_cm[:,2])):.1f}] cm") - - physics_params = create_default_params() - - # Create simulation - sim = create_multiplane_simulation(de, dx, positions_cm, detector_config, physics_params) - - # ========================================================================= - # TEST 1: Global Shift with MSE Loss (All Planes) - # ========================================================================= - print("\n" + "="*70) - print("TEST 1: Global Shift with MSE Loss (All 3 Planes)") - print("="*70) - - # Test with small offset - offset_small = jnp.zeros((n_test, 3)) - offset_small = offset_small.at[:, 0].set(0.05) # 0.05 cm x offset - offset_small = offset_small.at[:, 1].set(0.05) # 0.05 cm y offset - offset_small = offset_small.at[:, 2].set(0.05) # 0.05 cm z offset - - loss_at_zero = sim['mse_loss'](jnp.zeros((n_test, 3))) - loss_at_small = sim['mse_loss'](offset_small) - print(f"\nLoss at zero offset: {float(loss_at_zero):.4e}") - print(f"Loss at small offset: {float(loss_at_small):.4e}") - - grads_mse = test_gradient( - "MSE Loss - All Planes", - sim['mse_loss'], - offset_small, - ['x (drift)', 'y', 'z'], - eps=1e-4 - ) - - # ========================================================================= - # TEST 2: Centroid Loss - # ========================================================================= - print("\n" + "="*70) - print("TEST 2: Centroid Loss (Position-Weighted)") - print("="*70) - - loss_centroid_zero = sim['centroid_loss'](jnp.zeros((n_test, 3))) - loss_centroid_small = sim['centroid_loss'](offset_small) - print(f"\nCentroid loss at zero offset: {float(loss_centroid_zero):.4e}") - print(f"Centroid loss at small offset: {float(loss_centroid_small):.4e}") - - grads_centroid = test_gradient( - "Centroid Loss - All Planes", - sim['centroid_loss'], - offset_small, - ['x (drift)', 'y', 'z'], - eps=1e-4 - ) - - # ========================================================================= - # TEST 3: Compare Y vs Z gradients (should be related by angle) - # ========================================================================= - print("\n" + "="*70) - print("TEST 3: Y vs Z Gradient Relationship") - print("="*70) - - if grads_mse is not None: - print("\nFor angled wires, Y and Z gradients should relate through:") - print(" wire_coord = y*sin(angle) + z*cos(angle)") - print(" ∂L/∂y = (∂L/∂r) * sin(angle)") - print(" ∂L/∂z = (∂L/∂r) * cos(angle)") - print(" So: (∂L/∂y) / (∂L/∂z) ≈ tan(angle)") - - angles = sim['angles_rad'] - plane_names = ['U', 'V', 'Y'] - - mean_y_grad = float(jnp.mean(grads_mse[:, 1])) - mean_z_grad = float(jnp.mean(grads_mse[:, 2])) - - print(f"\nMean gradients: ∂L/∂y = {mean_y_grad:.4e}, ∂L/∂z = {mean_z_grad:.4e}") - - if abs(mean_z_grad) > 1e-10: - ratio = mean_y_grad / mean_z_grad - print(f"Ratio ∂L/∂y / ∂L/∂z = {ratio:.4f}") - - print("\nExpected tan(angle) for each plane:") - for i, angle in enumerate(angles): - tan_angle = float(jnp.tan(angle)) - print(f" {plane_names[i]}: angle={float(jnp.degrees(angle)):.1f}°, tan={tan_angle:.4f}") - - # ========================================================================= - # TEST 4: Gradient at different offsets (loss landscape) - # ========================================================================= - print("\n" + "="*70) - print("TEST 4: Loss Landscape (varying single dimension)") - print("="*70) - - offsets_1d = jnp.linspace(-0.2, 0.2, 11) # -0.2 to +0.2 cm - - for dim, dim_name in enumerate(['X', 'Y', 'Z']): - print(f"\nVarying {dim_name} offset:") - print(f"{'Offset (cm)':<12} {'MSE Loss':>14} {'Centroid Loss':>14}") - print("-"*45) - - for offset in offsets_1d: - pos_offset = jnp.zeros((n_test, 3)) - pos_offset = pos_offset.at[:, dim].set(float(offset)) - - mse = float(sim['mse_loss'](pos_offset)) - cent = float(sim['centroid_loss'](pos_offset)) - print(f"{float(offset):>12.3f} {mse:>14.4e} {cent:>14.4e}") - - # ========================================================================= - # SUMMARY - # ========================================================================= - print("\n" + "="*70) - print("SUMMARY") - print("="*70) - print(""" -KEY FINDINGS: - -1. Y AND Z ARE BOTH DIFFERENTIABLE: - - Wire coordinate: r = y*sin(angle) + z*cos(angle) - - Both y and z flow through this to affect Gaussian kernel weights - - For Y plane (angle=0°): only z matters (cos(0)=1, sin(0)=0) - - For U/V planes (angle=±60°): both y and z contribute - -2. GRADIENT RELATIONSHIP: - - ∂L/∂y ∝ sin(angle) * ∂L/∂r - - ∂L/∂z ∝ cos(angle) * ∂L/∂r - - Ratio ∂L/∂y / ∂L/∂z ≈ tan(angle) for each plane - -3. ALL THREE PLANES CONTRIBUTE: - - U plane (60°): y and z both contribute - - V plane (-60°): y and z both contribute - - Y plane (0°): mainly z contributes - -4. POSITION-WEIGHTED (CENTROID) LOSS: - - Computes signal-weighted mean position - - Differentiable through soft argmax-like computation - - More robust than pixel-wise MSE for position recovery - -CONCLUSION: -Both Y and Z positions are learnable. The previous test showing -Z-only gradients was an artifact of using angle=0 (Y plane only). -With all three planes, the full 3D position is recoverable. -""") - - # Save report - os.makedirs('results', exist_ok=True) - with open('results/centroid_gradient_report.txt', 'w') as f: - f.write("Position Gradient Analysis - All Wire Planes\n") - f.write("="*60 + "\n\n") - f.write("Wire plane angles:\n") - for i, angle in enumerate(sim['angles_rad']): - f.write(f" {['U','V','Y'][i]}: {float(jnp.degrees(angle)):.1f}°\n") - f.write("\nAll position components (x, y, z) are DIFFERENTIABLE.\n") - - print(f"\nReport saved to: results/centroid_gradient_report.txt") - - return True - - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/closure/archive/gradient_test/gradient_test/test_position_gradients.py b/closure/archive/gradient_test/gradient_test/test_position_gradients.py deleted file mode 100644 index 32f67a3..0000000 --- a/closure/archive/gradient_test/gradient_test/test_position_gradients.py +++ /dev/null @@ -1,682 +0,0 @@ -#!/usr/bin/env python3 -""" -Test gradients for input position transformations. - -This tests whether we can learn: -1. Global shift (dx, dy, dz) applied to all positions -2. Global rotation (theta, phi) about the center -3. Per-segment position offsets (N x 3 learnable positions) - -The goal is to verify if gradient-based optimization can recover -the true particle positions from the simulation output. -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np -from typing import NamedTuple - -from physics_params import create_default_params, PhysicsParams -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - - -# ============================================================================= -# Transform Parameter Containers -# ============================================================================= - -class GlobalTransformParams(NamedTuple): - """Global shift and rotation parameters.""" - # Shift in cm - shift_x: float - shift_y: float - shift_z: float - # Rotation angles (parameterized for smooth gradients) - # We use sin/cos directly to avoid discontinuities - cos_theta: float # cos of polar angle - sin_theta: float # sin of polar angle - cos_phi: float # cos of azimuthal angle - sin_phi: float # sin of azimuthal angle - - -def create_identity_transform() -> GlobalTransformParams: - """Create identity transform (no shift, no rotation).""" - return GlobalTransformParams( - shift_x=0.0, - shift_y=0.0, - shift_z=0.0, - cos_theta=1.0, # theta=0 -> no rotation - sin_theta=0.0, - cos_phi=1.0, # phi=0 - sin_phi=0.0, - ) - - -def create_small_transform() -> GlobalTransformParams: - """Create a small transform for testing.""" - theta = 0.1 # ~6 degrees - phi = 0.2 # ~11 degrees - return GlobalTransformParams( - shift_x=0.5, # 0.5 cm shift - shift_y=0.3, - shift_z=-0.2, - cos_theta=float(jnp.cos(theta)), - sin_theta=float(jnp.sin(theta)), - cos_phi=float(jnp.cos(phi)), - sin_phi=float(jnp.sin(phi)), - ) - - -# ============================================================================= -# Transform Functions -# ============================================================================= - -@jax.jit -def apply_shift(positions_cm, shift_x, shift_y, shift_z): - """Apply translation to positions.""" - shift = jnp.array([shift_x, shift_y, shift_z]) - return positions_cm + shift - - -@jax.jit -def apply_rotation_about_center(positions_cm, center_cm, cos_theta, sin_theta, cos_phi, sin_phi): - """ - Apply rotation about a center point. - - Uses Rodrigues' rotation formula with axis defined by (theta, phi). - For small angles, this is approximately: - - theta: rotation in the xz plane - - phi: rotation in the xy plane - """ - # Center the positions - centered = positions_cm - center_cm - - # Build rotation matrix from Euler-like angles - # Rz(phi) @ Ry(theta) rotation - # This gives rotation first around y-axis by theta, then around z-axis by phi - - # Ry(theta) components - r11 = cos_theta - r13 = sin_theta - r31 = -sin_theta - r33 = cos_theta - - # Combined Rz(phi) @ Ry(theta) - # Rz = [[cos_phi, -sin_phi, 0], [sin_phi, cos_phi, 0], [0, 0, 1]] - # Full rotation matrix: - R = jnp.array([ - [cos_phi * cos_theta, -sin_phi, cos_phi * sin_theta], - [sin_phi * cos_theta, cos_phi, sin_phi * sin_theta], - [-sin_theta, 0.0, cos_theta] - ]) - - # Apply rotation - rotated = jnp.dot(centered, R.T) - - # Translate back - return rotated + center_cm - - -@jax.jit -def apply_global_transform(positions_cm, center_cm, transform_params: GlobalTransformParams): - """Apply full global transform: shift then rotate.""" - # First shift - shifted = apply_shift( - positions_cm, - transform_params.shift_x, - transform_params.shift_y, - transform_params.shift_z - ) - - # Then rotate about center - rotated = apply_rotation_about_center( - shifted, center_cm, - transform_params.cos_theta, - transform_params.sin_theta, - transform_params.cos_phi, - transform_params.sin_phi - ) - - return rotated - - -# ============================================================================= -# Simulation with Transforms -# ============================================================================= - -def create_simulation_with_transform(de, dx, base_positions_cm, center_cm, detector_config, physics_params): - """ - Create a simulation loss that takes transform parameters. - - The loss measures how well the transformed positions produce expected signals. - """ - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 - wire_spacing = float(detector_config['wire_spacings_cm'][0, 0]) - time_step_size = detector_config['time_step_size_us'] - - num_wires = 200 - num_time_steps = 500 - K_wire = 3 - K_time = 5 - wire_index_offset = num_wires // 2 - - # Pre-compute reference wireplane with identity transform - identity_transform = create_identity_transform() - - def compute_wireplane(positions_cm): - """Compute wireplane from positions.""" - drift_times = jnp.abs(positions_cm[:, 0]) / drift_velocity - z_positions = positions_cm[:, 2] - - # Recombination - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - - # Attenuation - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - # Diffusion - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - # Indices - center_wire = jnp.floor(z_positions / wire_spacing + wire_index_offset).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - # Kernel - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) - time_offsets_k = jnp.arange(-K_time, K_time + 1) - - wire_distances = wire_offsets_k[None, :] * wire_spacing - time_distances = time_offsets_k[None, :] * time_step_size - - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None] + 1e-12) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None] + 1e-12) - - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - # Scatter - n_hits = de.shape[0] - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] - time_indices_k = center_time[:, None] + time_offsets_k[None, :] - - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_hits, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_hits, n_wire_k, n_time_k)) - - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - return wireplane - - def transform_loss(transform_params: GlobalTransformParams): - """Loss comparing transformed positions to reference.""" - # Apply transform - transformed_positions = apply_global_transform( - base_positions_cm, center_cm, transform_params - ) - - # Compute wireplane - wireplane = compute_wireplane(transformed_positions) - - # Simple loss: sum of squares (could compare to reference) - return jnp.mean(wireplane ** 2) - - return transform_loss, compute_wireplane - - -def create_simulation_with_position_offsets(de, dx, base_positions_cm, detector_config, physics_params): - """ - Create simulation where each segment has learnable position offsets. - - This tests if we can get gradients for N x 3 position parameters. - """ - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 - wire_spacing = float(detector_config['wire_spacings_cm'][0, 0]) - time_step_size = detector_config['time_step_size_us'] - - num_wires = 200 - num_time_steps = 500 - K_wire = 3 - K_time = 5 - wire_index_offset = num_wires // 2 - - def position_offset_loss(position_offsets): - """ - Loss function where position_offsets is (N, 3) array. - - Each row is (dx, dy, dz) offset for that segment. - """ - # Apply per-segment offsets - positions_cm = base_positions_cm + position_offsets - - drift_times = jnp.abs(positions_cm[:, 0]) / drift_velocity - z_positions = positions_cm[:, 2] - - # Recombination - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - - # Attenuation - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - # Diffusion - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - # Indices - center_wire = jnp.floor(z_positions / wire_spacing + wire_index_offset).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - # Kernel - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) - time_offsets_k = jnp.arange(-K_time, K_time + 1) - - wire_distances = wire_offsets_k[None, :] * wire_spacing - time_distances = time_offsets_k[None, :] * time_step_size - - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None] + 1e-12) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None] + 1e-12) - - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - # Scatter - n_hits = de.shape[0] - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] - time_indices_k = center_time[:, None] + time_offsets_k[None, :] - - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_hits, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_hits, n_wire_k, n_time_k)) - - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - return jnp.mean(wireplane ** 2) - - return position_offset_loss - - -# ============================================================================= -# Gradient Testing -# ============================================================================= - -def test_transform_gradients(name, loss_fn, params, param_names, eps=1e-3): - """Test gradients for transform parameters.""" - print(f"\n{'='*80}") - print(f"TEST: {name}") - print('='*80) - - # Try analytical gradient - try: - grad_fn = jax.grad(loss_fn) - grads = grad_fn(params) - analytical_works = True - except Exception as e: - print(f"Analytical gradient FAILED: {e}") - analytical_works = False - grads = None - - print(f"\n{'Parameter':<20} {'Analytical':>14} {'Numerical':>14} {'Rel Diff':>12} {'Status':>10}") - print("-"*75) - - all_match = True - - for param_name in param_names: - base_val = getattr(params, param_name) - step = eps * max(abs(base_val), 0.01) # Ensure reasonable step for small values - - params_plus = params._replace(**{param_name: base_val + step}) - params_minus = params._replace(**{param_name: base_val - step}) - - loss_plus = float(loss_fn(params_plus)) - loss_minus = float(loss_fn(params_minus)) - num_grad = (loss_plus - loss_minus) / (2 * step) - - if analytical_works: - ana_grad = float(getattr(grads, param_name)) - - if abs(num_grad) > 1e-10: - rel_diff = abs(ana_grad - num_grad) / abs(num_grad) - elif abs(ana_grad) < 1e-10: - rel_diff = 0.0 - else: - rel_diff = float('inf') - - match = rel_diff < 0.3 # 30% tolerance - if not match: - all_match = False - - status = "PASS" if match else "FAIL" - print(f"{param_name:<20} {ana_grad:>14.4e} {num_grad:>14.4e} {rel_diff:>12.2e} {status:>10}") - else: - print(f"{param_name:<20} {'FAILED':>14} {num_grad:>14.4e} {'N/A':>12} {'N/A':>10}") - - status = "PASS" if analytical_works and all_match else "PARTIAL" if analytical_works else "FAIL" - print(f"\nOverall Status: {status}") - return analytical_works and all_match - - -def test_position_offset_gradients(loss_fn, n_segments, eps=1e-3): - """Test gradients for per-segment position offsets.""" - print(f"\n{'='*80}") - print(f"TEST: Per-Segment Position Offsets (N={n_segments} x 3)") - print('='*80) - - # Start with zero offsets - position_offsets = jnp.zeros((n_segments, 3)) - - # Try analytical gradient - try: - grad_fn = jax.grad(loss_fn) - grads = grad_fn(position_offsets) - analytical_works = True - print(f"\nAnalytical gradient computed successfully!") - print(f"Gradient shape: {grads.shape}") - except Exception as e: - print(f"Analytical gradient FAILED: {e}") - analytical_works = False - grads = None - return False - - # Check gradient statistics - print(f"\nGradient Statistics:") - print(f" Min: {float(jnp.min(grads)):>12.4e}") - print(f" Max: {float(jnp.max(grads)):>12.4e}") - print(f" Mean: {float(jnp.mean(grads)):>12.4e}") - print(f" Std: {float(jnp.std(grads)):>12.4e}") - - # Check for NaN/Inf - has_nan = bool(jnp.any(jnp.isnan(grads))) - has_inf = bool(jnp.any(jnp.isinf(grads))) - print(f" Has NaN: {has_nan}") - print(f" Has Inf: {has_inf}") - - # Per-dimension statistics - print(f"\nPer-Dimension Gradient Stats:") - dim_names = ['x (drift)', 'y', 'z (wire)'] - for d in range(3): - g = grads[:, d] - print(f" {dim_names[d]:>12}: mean={float(jnp.mean(g)):>12.4e}, std={float(jnp.std(g)):>12.4e}") - - # Numerical verification for a few samples - print(f"\nNumerical Verification (random samples):") - print(f"{'Segment':<10} {'Dim':<8} {'Analytical':>14} {'Numerical':>14} {'Rel Diff':>12}") - print("-"*65) - - # Test 5 random segments - rng = np.random.default_rng(42) - test_indices = rng.choice(n_segments, size=min(5, n_segments), replace=False) - - all_match = True - for idx in test_indices: - for dim in range(3): - base_offsets = position_offsets - - # Create perturbation - delta = jnp.zeros((n_segments, 3)) - delta = delta.at[idx, dim].set(eps) - - loss_plus = float(loss_fn(base_offsets + delta)) - loss_minus = float(loss_fn(base_offsets - delta)) - num_grad = (loss_plus - loss_minus) / (2 * eps) - - ana_grad = float(grads[idx, dim]) - - if abs(num_grad) > 1e-10: - rel_diff = abs(ana_grad - num_grad) / abs(num_grad) - elif abs(ana_grad) < 1e-10: - rel_diff = 0.0 - else: - rel_diff = float('inf') - - match = rel_diff < 0.3 - if not match: - all_match = False - - print(f"{idx:<10} {dim_names[dim]:<8} {ana_grad:>14.4e} {num_grad:>14.4e} {rel_diff:>12.2e}") - - status = "PASS" if all_match else "PARTIAL" - print(f"\nOverall Status: {status}") - - return analytical_works and all_match - - -# ============================================================================= -# Main -# ============================================================================= - -def main(): - print("="*80) - print("JAXTPC Position Gradient Analysis") - print("Testing Learnable Shift, Rotation, and Per-Segment Positions") - print("="*80) - print(f"\nJAX version: {jax.__version__}") - print(f"JAX devices: {jax.devices()}") - - # Load data - print("\nLoading data...") - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - n_test = 100 - de = jnp.asarray(step_data['de'][:n_test], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_test], dtype=jnp.float32) - positions_mm = jnp.asarray(step_data['position'][:n_test], dtype=jnp.float32) - positions_cm = positions_mm / 10.0 - - print(f"Using {n_test} particle steps") - - # Compute center of positions - center_cm = jnp.mean(positions_cm, axis=0) - print(f"Position center: ({float(center_cm[0]):.2f}, {float(center_cm[1]):.2f}, {float(center_cm[2]):.2f}) cm") - - physics_params = create_default_params() - - results = {} - - # ========================================================================= - # TEST 1: Pure Shift Only - # ========================================================================= - print("\n" + "="*80) - print("SECTION 1: Pure Translation (Shift)") - print("="*80) - - def shift_only_loss(shift_params): - """Test just translation.""" - shifted = positions_cm + jnp.array([shift_params.shift_x, shift_params.shift_y, shift_params.shift_z]) - # Simple loss: sum of squared distances from center - return jnp.mean(jnp.sum((shifted - center_cm)**2, axis=1)) - - class ShiftParams(NamedTuple): - shift_x: float - shift_y: float - shift_z: float - - shift_params = ShiftParams(shift_x=0.0, shift_y=0.0, shift_z=0.0) - results['pure_shift'] = test_transform_gradients( - "Pure Translation (Simple Loss)", - shift_only_loss, shift_params, - ['shift_x', 'shift_y', 'shift_z'] - ) - - # ========================================================================= - # TEST 2: Pure Rotation Only - # ========================================================================= - print("\n" + "="*80) - print("SECTION 2: Pure Rotation") - print("="*80) - - class RotationParams(NamedTuple): - cos_theta: float - sin_theta: float - cos_phi: float - sin_phi: float - - def rotation_only_loss(rot_params): - """Test just rotation about center.""" - rotated = apply_rotation_about_center( - positions_cm, center_cm, - rot_params.cos_theta, rot_params.sin_theta, - rot_params.cos_phi, rot_params.sin_phi - ) - # Loss: change in positions - return jnp.mean(jnp.sum((rotated - positions_cm)**2, axis=1)) - - rot_params = RotationParams(cos_theta=1.0, sin_theta=0.0, cos_phi=1.0, sin_phi=0.0) - results['pure_rotation'] = test_transform_gradients( - "Pure Rotation (Simple Loss)", - rotation_only_loss, rot_params, - ['cos_theta', 'sin_theta', 'cos_phi', 'sin_phi'] - ) - - # ========================================================================= - # TEST 3: Full Transform Through Simulation - # ========================================================================= - print("\n" + "="*80) - print("SECTION 3: Global Transform Through Full Simulation") - print("="*80) - - transform_loss_fn, _ = create_simulation_with_transform( - de, dx, positions_cm, center_cm, detector_config, physics_params - ) - - transform_params = create_identity_transform() - results['full_transform'] = test_transform_gradients( - "Full Simulation with Global Transform", - transform_loss_fn, transform_params, - ['shift_x', 'shift_y', 'shift_z', 'cos_theta', 'sin_theta', 'cos_phi', 'sin_phi'] - ) - - # ========================================================================= - # TEST 4: Per-Segment Position Offsets - # ========================================================================= - print("\n" + "="*80) - print("SECTION 4: Per-Segment Position Offsets (N x 3)") - print("="*80) - - position_loss_fn = create_simulation_with_position_offsets( - de, dx, positions_cm, detector_config, physics_params - ) - - results['per_segment'] = test_position_offset_gradients(position_loss_fn, n_test) - - # ========================================================================= - # TEST 5: Larger N (stress test) - # ========================================================================= - print("\n" + "="*80) - print("SECTION 5: Larger N Stress Test") - print("="*80) - - n_large = 500 - de_large = jnp.asarray(step_data['de'][:n_large], dtype=jnp.float32) - dx_large = jnp.asarray(step_data['dx'][:n_large], dtype=jnp.float32) - positions_large = jnp.asarray(step_data['position'][:n_large], dtype=jnp.float32) / 10.0 - - print(f"Testing with N={n_large} segments...") - - position_loss_fn_large = create_simulation_with_position_offsets( - de_large, dx_large, positions_large, detector_config, physics_params - ) - - results['per_segment_large'] = test_position_offset_gradients(position_loss_fn_large, n_large) - - # ========================================================================= - # SUMMARY - # ========================================================================= - print("\n" + "="*80) - print("SUMMARY") - print("="*80) - - print("\n{:<40} {:>15}".format("Test", "Status")) - print("-"*55) - for test_name, passed in results.items(): - status = "PASS" if passed else "FAIL/PARTIAL" - print(f"{test_name:<40} {status:>15}") - - print("\n" + "="*80) - print("KEY FINDINGS") - print("="*80) - print(""" -POSITION GRADIENTS SUMMARY: - -✓ Global Shift (shift_x, shift_y, shift_z): - - Fully differentiable through the simulation - - Gradients are accurate and flow correctly - -✓ Global Rotation (cos_theta, sin_theta, cos_phi, sin_phi): - - Differentiable through rotation matrices - - sin/cos parameterization avoids angle discontinuities - -✓ Per-Segment Position Offsets (N x 3 array): - - JAX handles gradients for arbitrary-sized position arrays - - Each segment's (dx, dy, dz) offset is independently differentiable - - Gradients have correct structure and magnitude - -IMPLICATIONS: -- Input particle positions CAN be learned through gradient descent -- Both global transforms and per-segment adjustments are supported -- This enables inverse problems: infer particle trajectory from signals - -GRADIENT FLOW PATH: - positions_cm → drift_times → {attenuation, diffusion} - → z_positions → wire indices (discrete, but values are diff.) - → kernel weights → scatter-add → loss -""") - - # Save report - os.makedirs('results', exist_ok=True) - with open('results/position_gradient_report.txt', 'w') as f: - f.write("JAXTPC Position Gradient Analysis Report\n") - f.write("="*60 + "\n\n") - f.write("All position-related parameters are DIFFERENTIABLE.\n\n") - f.write("Tested Parameters:\n") - f.write(" - Global shift (x, y, z)\n") - f.write(" - Global rotation (cos/sin theta, cos/sin phi)\n") - f.write(" - Per-segment offsets (N x 3 array)\n\n") - f.write("Results:\n") - for test_name, passed in results.items(): - f.write(f" {test_name}: {'PASS' if passed else 'FAIL/PARTIAL'}\n") - - print(f"\nReport saved to: results/position_gradient_report.txt") - - return all(results.values()) - - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/closure/archive/gradient_test/gradient_test/test_position_gradients_v2.py b/closure/archive/gradient_test/gradient_test/test_position_gradients_v2.py deleted file mode 100644 index bbd3ba4..0000000 --- a/closure/archive/gradient_test/gradient_test/test_position_gradients_v2.py +++ /dev/null @@ -1,401 +0,0 @@ -#!/usr/bin/env python3 -""" -Position Gradient Analysis V2: Understanding Which Positions Are Differentiable - -Key insight from V1: -- x position (drift direction): Differentiable through drift_time → attenuation, diffusion -- y position: Not used in simplified sim (would affect angles in full sim) -- z position (wire direction): Only affects discrete wire INDEX, not differentiable - -This test explores: -1. Why x is differentiable (through values) -2. Why z is NOT differentiable (discrete indices) -3. How to make z-like positions differentiable (sub-bin offsets) -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np -from typing import NamedTuple - -from physics_params import create_default_params, PhysicsParams -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - - -def test_simple_gradient(name, loss_fn, x0, eps=1e-3): - """Test gradient for a simple scalar or array input.""" - print(f"\n{'='*70}") - print(f"TEST: {name}") - print('='*70) - - try: - grad_fn = jax.grad(loss_fn) - grads = grad_fn(x0) - analytical_works = True - except Exception as e: - print(f"Analytical gradient FAILED: {e}") - return False - - if isinstance(x0, jnp.ndarray) and x0.ndim > 0: - print(f"Gradient shape: {grads.shape}") - print(f"Gradient stats: min={float(jnp.min(grads)):.4e}, max={float(jnp.max(grads)):.4e}") - print(f" mean={float(jnp.mean(grads)):.4e}, std={float(jnp.std(grads)):.4e}") - - # Check if all zeros - if jnp.allclose(grads, 0): - print("WARNING: All gradients are ZERO!") - return False - - # Numerical check for first element - x_plus = x0.at[0].set(x0[0] + eps) - x_minus = x0.at[0].set(x0[0] - eps) - num_grad = (loss_fn(x_plus) - loss_fn(x_minus)) / (2 * eps) - print(f"First element: analytical={float(grads[0]):.4e}, numerical={float(num_grad):.4e}") - else: - print(f"Analytical: {float(grads):.4e}") - x_plus = x0 + eps - x_minus = x0 - eps - num_grad = (loss_fn(x_plus) - loss_fn(x_minus)) / (2 * eps) - print(f"Numerical: {float(num_grad):.4e}") - - return True - - -def main(): - print("="*70) - print("Position Gradient Analysis V2") - print("Understanding What Is and Isn't Differentiable") - print("="*70) - - # Load data - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - n_test = 50 - de = jnp.asarray(step_data['de'][:n_test], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_test], dtype=jnp.float32) - positions_mm = jnp.asarray(step_data['position'][:n_test], dtype=jnp.float32) - positions_cm = positions_mm / 10.0 - - drift_velocity = detector_config['drift_velocity_cm_us'] - wire_spacing = float(detector_config['wire_spacings_cm'][0, 0]) - - physics_params = create_default_params() - - # ========================================================================= - # TEST 1: X position through drift time (should work) - # ========================================================================= - print("\n" + "="*70) - print("SECTION 1: X Position (Drift Direction)") - print("="*70) - print("\nX position affects drift_time = |x| / velocity") - print("Drift time affects: attenuation, diffusion sigma") - print("These are continuous functions → DIFFERENTIABLE") - - x_positions = positions_cm[:, 0] - base_drift_times = jnp.abs(x_positions) / drift_velocity - - def x_to_attenuation_loss(x_offsets): - """Loss through drift time → attenuation.""" - x_new = x_positions + x_offsets - drift_times = jnp.abs(x_new) / drift_velocity - attenuation = jnp.exp(-drift_times / 10000.0) # 10 ms lifetime - return jnp.mean(attenuation) - - test_simple_gradient("X → Drift Time → Attenuation", x_to_attenuation_loss, jnp.zeros(n_test)) - - def x_to_diffusion_loss(x_offsets): - """Loss through drift time → diffusion sigma.""" - x_new = x_positions + x_offsets - drift_times = jnp.abs(x_new) / drift_velocity - sigma_sq = 2.0 * physics_params.diffusion_trans * drift_times - return jnp.mean(sigma_sq) - - test_simple_gradient("X → Drift Time → Diffusion Sigma", x_to_diffusion_loss, jnp.zeros(n_test)) - - # ========================================================================= - # TEST 2: Z position through wire index (should NOT work directly) - # ========================================================================= - print("\n" + "="*70) - print("SECTION 2: Z Position (Wire Direction) - Discrete Index") - print("="*70) - print("\nZ position affects wire_index = floor(z / wire_spacing)") - print("floor() has zero gradient almost everywhere") - print("This is NOT differentiable through indices!") - - z_positions = positions_cm[:, 2] - wire_index_offset = 100 - - def z_to_index_loss(z_offsets): - """Loss through wire index (discrete).""" - z_new = z_positions + z_offsets - wire_indices = jnp.floor(z_new / wire_spacing + wire_index_offset).astype(jnp.int32) - # Convert back to float to compute loss - return jnp.mean(wire_indices.astype(jnp.float32)) - - test_simple_gradient("Z → Wire Index (floor) - EXPECTED TO FAIL", z_to_index_loss, jnp.zeros(n_test)) - - # ========================================================================= - # TEST 3: Z position through sub-bin offset (DIFFERENTIABLE!) - # ========================================================================= - print("\n" + "="*70) - print("SECTION 3: Z Position Through Sub-Bin Offset (Differentiable!)") - print("="*70) - print("\nThe KEY insight: wire_offset = z/spacing - floor(z/spacing)") - print("This fractional part IS differentiable!") - print("It determines the Gaussian weight at each wire.") - - def z_to_subbin_loss(z_offsets): - """Loss through sub-bin wire offset (continuous).""" - z_new = z_positions + z_offsets - # Continuous wire position - wire_pos = z_new / wire_spacing + wire_index_offset - # Discrete index - wire_idx = jnp.floor(wire_pos) - # Sub-bin offset (0 to 1) - THIS IS DIFFERENTIABLE - wire_offset = wire_pos - wire_idx - return jnp.mean(wire_offset ** 2) - - test_simple_gradient("Z → Sub-Bin Offset (continuous)", z_to_subbin_loss, jnp.zeros(n_test)) - - # ========================================================================= - # TEST 4: Z through Gaussian kernel weights (DIFFERENTIABLE!) - # ========================================================================= - print("\n" + "="*70) - print("SECTION 4: Z Position Through Gaussian Kernel Weights") - print("="*70) - print("\nWhen we compute Gaussian kernels at neighboring wires,") - print("the z position determines the distance to each wire.") - print("distance_to_wire[k] = z - (wire_idx + k) * wire_spacing") - print("This flows into: exp(-d²/2σ²) which IS differentiable!") - - def z_through_gaussian_loss(z_offsets): - """Loss through Gaussian kernel weights.""" - z_new = z_positions + z_offsets - drift_times = jnp.abs(positions_cm[:, 0]) / drift_velocity - - # Wire position (continuous) - wire_pos = z_new / wire_spacing + wire_index_offset - wire_idx = jnp.floor(wire_pos) - - # Distances to neighboring wires - wire_offsets_k = jnp.array([-1, 0, 1]) # 3 nearest wires - distances = (wire_pos[:, None] - (wire_idx[:, None] + wire_offsets_k)) * wire_spacing - - # Diffusion sigma - sigma_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-10 - sigma = jnp.sqrt(sigma_sq) - - # Gaussian weights (DIFFERENTIABLE w.r.t. z through distances!) - gauss_weights = jnp.exp(-distances**2 / (2 * sigma_sq[:, None])) - - return jnp.mean(gauss_weights) - - test_simple_gradient("Z → Gaussian Weights (distance-based)", z_through_gaussian_loss, jnp.zeros(n_test)) - - # ========================================================================= - # TEST 5: Full Simulation with Position Offsets (Small Values) - # ========================================================================= - print("\n" + "="*70) - print("SECTION 5: Full Simulation - Position Offsets (N x 3)") - print("="*70) - print("\nTesting with SMALL offsets (0.1 cm scale) to ensure overlap.") - print("Large offsets would cause non-overlapping signals → weak gradients.") - print("\nExpected: gradients for x (through drift time)") - print(" gradients for z (through Gaussian kernel weights)") - - electron_lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 - time_step_size = detector_config['time_step_size_us'] - num_wires = 200 - num_time_steps = 500 - K_wire = 3 - K_time = 5 - - def compute_wireplane(pos): - """Compute wireplane from positions (shared function).""" - x_pos = pos[:, 0] - z_pos = pos[:, 2] - - drift_times = jnp.abs(x_pos) / drift_velocity - - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - wire_pos = z_pos / wire_spacing + num_wires // 2 - center_wire = jnp.floor(wire_pos).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - wire_offset = wire_pos - center_wire.astype(jnp.float32) - time_offset = drift_times / time_step_size - center_time.astype(jnp.float32) - - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) - time_offsets_k = jnp.arange(-K_time, K_time + 1) - - wire_distances = (wire_offsets_k[None, :] - wire_offset[:, None]) * wire_spacing - time_distances = (time_offsets_k[None, :] - time_offset[:, None]) * time_step_size - - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None] + 1e-12) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None] + 1e-12) - - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - n_hits = de.shape[0] - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] - time_indices_k = center_time[:, None] + time_offsets_k[None, :] - - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_hits, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_hits, n_wire_k, n_time_k)) - - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - return wireplane - - # Compute reference wireplane at zero offset - reference_wireplane = compute_wireplane(positions_cm) - print(f"Reference wireplane: max={float(jnp.max(reference_wireplane)):.4e}") - - def full_sim_mse_loss(position_offsets): - """MSE loss comparing offset simulation to reference.""" - pos = positions_cm + position_offsets - wireplane = compute_wireplane(pos) - # MSE against reference (gradient pushes toward zero offset) - return jnp.mean((wireplane - reference_wireplane) ** 2) - - # Test with small offset to get non-zero gradient - print("\nTesting at zero offset (should have zero gradient at minimum)...") - position_offsets_zero = jnp.zeros((n_test, 3)) - loss_at_zero = full_sim_mse_loss(position_offsets_zero) - print(f"Loss at zero offset: {float(loss_at_zero):.4e}") - - # Test with small non-zero offset - print("\nTesting with small offset (0.1 cm in x and z)...") - position_offsets_small = jnp.zeros((n_test, 3)) - position_offsets_small = position_offsets_small.at[:, 0].set(0.1) # 0.1 cm x offset - position_offsets_small = position_offsets_small.at[:, 2].set(0.05) # 0.05 cm z offset - - loss_at_small = full_sim_mse_loss(position_offsets_small) - print(f"Loss at small offset: {float(loss_at_small):.4e}") - - try: - grad_fn = jax.grad(full_sim_mse_loss) - grads = grad_fn(position_offsets_small) - print(f"\nGradient shape: {grads.shape}") - - print("\nPer-Dimension Gradient Statistics:") - dim_names = ['x (drift)', 'y', 'z (wire)'] - for d in range(3): - g = grads[:, d] - print(f" {dim_names[d]:>12}: min={float(jnp.min(g)):>12.4e}, max={float(jnp.max(g)):>12.4e}") - print(f" mean={float(jnp.mean(g)):>12.4e}, std={float(jnp.std(g)):>12.4e}") - - # Numerical verification - print("\nNumerical Verification (small eps=1e-4):") - eps = 1e-4 - for d, dim_name in enumerate(dim_names): - delta = jnp.zeros((n_test, 3)) - delta = delta.at[0, d].set(eps) - num_grad = (full_sim_mse_loss(position_offsets_small + delta) - full_sim_mse_loss(position_offsets_small - delta)) / (2 * eps) - ana_grad = grads[0, d] - if abs(float(num_grad)) > 1e-10: - rel_diff = abs(float(ana_grad) - float(num_grad)) / abs(float(num_grad)) - match = "MATCH" if rel_diff < 0.5 else "DIFF" - else: - match = "~0" if abs(float(ana_grad)) < 1e-8 else "NON-ZERO" - print(f" {dim_name}: analytical={float(ana_grad):>12.4e}, numerical={float(num_grad):>12.4e} [{match}]") - - # Check gradient direction - should point back toward zero - print("\nGradient Direction Check:") - print(" (Negative gradient means 'decrease offset to reduce loss')") - for d, dim_name in enumerate(dim_names): - mean_grad = float(jnp.mean(grads[:, d])) - offset_val = float(position_offsets_small[0, d]) - if abs(mean_grad) > 1e-10: - direction = "CORRECT" if (mean_grad * offset_val > 0) else "REVERSED" - print(f" {dim_name}: mean_grad={mean_grad:>12.4e}, offset={offset_val:.3f} → {direction}") - else: - print(f" {dim_name}: mean_grad={mean_grad:>12.4e} → ZERO/WEAK") - - except Exception as e: - print(f"FAILED: {e}") - - # ========================================================================= - # SUMMARY - # ========================================================================= - print("\n" + "="*70) - print("SUMMARY: Position Gradient Differentiability") - print("="*70) - print(""" -WHAT IS DIFFERENTIABLE: ------------------------ -✓ X position (drift direction): - - Flows through drift_time = |x| / velocity - - Affects: electron attenuation, diffusion sigmas - - Gradient path: x → drift_time → exp(-t/τ), sqrt(2*D*t) → values - -✓ Z position (wire direction) via sub-bin offset: - - Flows through: wire_offset = z/spacing - floor(z/spacing) - - Affects: distance_to_wire in Gaussian kernel - - Gradient path: z → wire_offset → exp(-d²/2σ²) → kernel weight → values - -✓ Y position (if used): - - Would flow through angle calculations - - Affects: angular response kernels - -WHAT IS NOT DIFFERENTIABLE: ---------------------------- -✗ Wire INDEX: floor(z/spacing) → integer → no gradient -✗ Time INDEX: floor(t/step) → integer → no gradient -✗ Index SELECTION: wireplane[wire_idx, time_idx] → discrete choice - -KEY INSIGHT: ------------- -Positions ARE differentiable, but only through the VALUES scattered to bins, -not through WHICH bins are selected. The gradient flows through: - -1. Sub-bin offsets (continuous fractional position within bin) -2. Gaussian kernel weights (depend on distance to neighboring bins) -3. Attenuation and diffusion (depend on drift distance/time) - -For practical inverse problems (learning particle positions): -- X position: LEARNABLE (strong gradient through drift physics) -- Z position: LEARNABLE with sub-bin precision (gradient through kernel weights) -- Y position: LEARNABLE if angular effects are modeled - -The discrete binning creates a PIECEWISE smooth loss landscape: -- Within each bin: smooth gradients from sub-bin position -- At bin boundaries: discontinuity in gradient direction -""") - - return True - - -if __name__ == "__main__": - success = main() - sys.exit(0 if success else 1) diff --git a/closure/archive/gradient_test/gradient_test/test_position_proper.py b/closure/archive/gradient_test/gradient_test/test_position_proper.py deleted file mode 100644 index c83ccb4..0000000 --- a/closure/archive/gradient_test/gradient_test/test_position_proper.py +++ /dev/null @@ -1,336 +0,0 @@ -#!/usr/bin/env python3 -""" -Position Gradient Analysis with Proper Geometry - -Uses actual detector geometry from config file. -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np - -from physics_params import create_default_params -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - - -def main(): - print("="*70) - print("Position Gradient Analysis - Proper Geometry") - print("="*70) - - # Load data - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - n_test = 50 - de = jnp.asarray(step_data['de'][:n_test], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_test], dtype=jnp.float32) - positions_cm = jnp.asarray(step_data['position'][:n_test], dtype=jnp.float32) / 10.0 - - # Use actual detector parameters - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 - time_step_size = detector_config['time_step_size_us'] - num_time_steps = detector_config['num_time_steps'] - - # Wire plane parameters from config (side 0) - angles_rad = detector_config['angles_rad'][0] - wire_spacings_cm = detector_config['wire_spacings_cm'][0] - index_offsets = detector_config['index_offsets'][0] - num_wires_actual = detector_config['num_wires_actual'][0] - min_wire_indices = detector_config['min_wire_indices_abs'][0] - max_wire_indices = detector_config['max_wire_indices_abs'][0] - - physics_params = create_default_params() - - K_wire = 3 - K_time = 5 - - plane_names = ['U (+60°)', 'V (-60°)', 'Y (0°)'] - - print(f"\nDetector geometry:") - for i, name in enumerate(plane_names): - print(f" {name}: {int(num_wires_actual[i])} wires, offset={int(index_offsets[i])}, " - f"range=[{int(min_wire_indices[i])}, {int(max_wire_indices[i])}]") - - print(f"\nData positions (cm):") - print(f" X: [{float(positions_cm[:,0].min()):.2f}, {float(positions_cm[:,0].max()):.2f}]") - print(f" Y: [{float(positions_cm[:,1].min()):.2f}, {float(positions_cm[:,1].max()):.2f}]") - print(f" Z: [{float(positions_cm[:,2].min()):.2f}, {float(positions_cm[:,2].max()):.2f}]") - - # Verify wire positions - y = positions_cm[:, 1] - z = positions_cm[:, 2] - print(f"\nWire positions in each plane:") - for i, name in enumerate(plane_names): - angle = float(angles_rad[i]) - spacing = float(wire_spacings_cm[i]) - offset = float(index_offsets[i]) - num_wires = int(num_wires_actual[i]) - - cos_a = np.cos(angle) - sin_a = np.sin(angle) - wire_coord = y * sin_a + z * cos_a - wire_pos = wire_coord / spacing + offset - - in_range = float(wire_pos.min()) >= 0 and float(wire_pos.max()) < num_wires - print(f" {name}: wire_pos=[{float(wire_pos.min()):.1f}, {float(wire_pos.max()):.1f}], " - f"valid=[0, {num_wires-1}], OK={in_range}") - - def compute_wireplane_for_plane(positions_cm, plane_idx): - """Compute wireplane for a single plane using proper geometry.""" - angle = angles_rad[plane_idx] - wire_spacing = float(wire_spacings_cm[plane_idx]) - wire_offset = float(index_offsets[plane_idx]) - num_wires = int(num_wires_actual[plane_idx]) - - x_pos = positions_cm[:, 0] - y_pos = positions_cm[:, 1] - z_pos = positions_cm[:, 2] - - drift_times = jnp.abs(x_pos) / drift_velocity - - # Wire coordinate: r = y*sin(angle) + z*cos(angle) - cos_angle = jnp.cos(angle) - sin_angle = jnp.sin(angle) - wire_coord = y_pos * sin_angle + z_pos * cos_angle - - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - # Wire position with proper offset from geometry - wire_pos = wire_coord / wire_spacing + wire_offset - center_wire = jnp.floor(wire_pos).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - wire_subbin = wire_pos - center_wire.astype(jnp.float32) - time_subbin = drift_times / time_step_size - center_time.astype(jnp.float32) - - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) - time_offsets_k = jnp.arange(-K_time, K_time + 1) - - wire_distances = (wire_offsets_k[None, :] - wire_subbin[:, None]) * wire_spacing - time_distances = (time_offsets_k[None, :] - time_subbin[:, None]) * time_step_size - - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None] + 1e-12) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None] + 1e-12) - - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] - time_indices_k = center_time[:, None] + time_offsets_k[None, :] - - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_test, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_test, n_wire_k, n_time_k)) - - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - return wireplane - - def compute_centroid(wireplane): - """Compute signal-weighted centroid.""" - num_w, num_t = wireplane.shape - wire_coords = jnp.arange(num_w) - time_coords = jnp.arange(num_t) - wire_grid, time_grid = jnp.meshgrid(wire_coords, time_coords, indexing='ij') - - weights = jnp.abs(wireplane) + 1e-12 - total_weight = jnp.sum(weights) - - centroid_wire = jnp.sum(wire_grid * weights) / total_weight - centroid_time = jnp.sum(time_grid * weights) / total_weight - - return centroid_wire, centroid_time - - # Compute reference - print("\n" + "="*70) - print("Computing reference wireplanes and centroids...") - print("="*70) - - ref_wireplanes = [] - ref_centroids = [] - for i in range(3): - wp = compute_wireplane_for_plane(positions_cm, i) - cw, ct = compute_centroid(wp) - ref_wireplanes.append(wp) - ref_centroids.append((cw, ct)) - print(f" {plane_names[i]}: centroid=({float(cw):.1f}, {float(ct):.1f}), max_signal={float(jnp.max(wp)):.2e}") - - # Create loss functions - def mse_loss_all_planes(position_offsets): - """MSE loss summed over all planes.""" - pos = positions_cm + position_offsets - total_loss = 0.0 - for i in range(3): - wp = compute_wireplane_for_plane(pos, i) - total_loss += jnp.mean((wp - ref_wireplanes[i]) ** 2) - return total_loss / 3.0 - - def centroid_loss_all_planes(position_offsets): - """Centroid distance loss summed over all planes.""" - pos = positions_cm + position_offsets - total_loss = 0.0 - for i in range(3): - wp = compute_wireplane_for_plane(pos, i) - cw, ct = compute_centroid(wp) - ref_cw, ref_ct = ref_centroids[i] - total_loss += (cw - ref_cw)**2 + (ct - ref_ct)**2 - return total_loss / 3.0 - - # Test gradients - print("\n" + "="*70) - print("Gradient Test with Small Offset (0.05 cm each direction)") - print("="*70) - - offset = jnp.zeros((n_test, 3)) - offset = offset.at[:, 0].set(0.05) # Small x shift - offset = offset.at[:, 1].set(0.05) # Small y shift - offset = offset.at[:, 2].set(0.05) # Small z shift - - # MSE Loss - print("\n--- MSE Loss ---") - loss_zero = float(mse_loss_all_planes(jnp.zeros((n_test, 3)))) - loss_offset = float(mse_loss_all_planes(offset)) - print(f"Loss at zero: {loss_zero:.4e}") - print(f"Loss at offset: {loss_offset:.4e}") - - grad_fn = jax.grad(mse_loss_all_planes) - grads = grad_fn(offset) - - print(f"\nAnalytical gradients (mean over segments):") - for d, name in enumerate(['x', 'y', 'z']): - mean_g = float(jnp.mean(grads[:, d])) - print(f" ∂L/∂{name} = {mean_g:>12.4e}") - - print(f"\nNumerical verification (segment 0):") - eps = 1e-4 - for d, name in enumerate(['x', 'y', 'z']): - delta = jnp.zeros((n_test, 3)) - delta = delta.at[0, d].set(eps) - num_grad = (mse_loss_all_planes(offset + delta) - mse_loss_all_planes(offset - delta)) / (2 * eps) - ana_grad = float(grads[0, d]) - - if abs(float(num_grad)) > 1e-12: - rel_diff = abs(ana_grad - float(num_grad)) / abs(float(num_grad)) - status = "MATCH" if rel_diff < 0.5 else "DIFF" - elif abs(ana_grad) < 1e-10: - status = "BOTH~0" - else: - status = "ANA≠0" - - print(f" ∂L/∂{name}: ana={ana_grad:>12.4e}, num={float(num_grad):>12.4e} [{status}]") - - # Centroid Loss - print("\n--- Centroid Loss ---") - loss_zero_c = float(centroid_loss_all_planes(jnp.zeros((n_test, 3)))) - loss_offset_c = float(centroid_loss_all_planes(offset)) - print(f"Loss at zero: {loss_zero_c:.4e}") - print(f"Loss at offset: {loss_offset_c:.4e}") - - grad_fn_c = jax.grad(centroid_loss_all_planes) - grads_c = grad_fn_c(offset) - - print(f"\nAnalytical gradients (mean over segments):") - for d, name in enumerate(['x', 'y', 'z']): - mean_g = float(jnp.mean(grads_c[:, d])) - print(f" ∂L/∂{name} = {mean_g:>12.4e}") - - print(f"\nNumerical verification (segment 0):") - for d, name in enumerate(['x', 'y', 'z']): - delta = jnp.zeros((n_test, 3)) - delta = delta.at[0, d].set(eps) - num_grad = (centroid_loss_all_planes(offset + delta) - centroid_loss_all_planes(offset - delta)) / (2 * eps) - ana_grad = float(grads_c[0, d]) - - if abs(float(num_grad)) > 1e-12: - rel_diff = abs(ana_grad - float(num_grad)) / abs(float(num_grad)) - status = "MATCH" if rel_diff < 0.5 else "DIFF" - elif abs(ana_grad) < 1e-10: - status = "BOTH~0" - else: - status = "ANA≠0" - - print(f" ∂L/∂{name}: ana={ana_grad:>12.4e}, num={float(num_grad):>12.4e} [{status}]") - - # Per-plane gradient breakdown - print("\n" + "="*70) - print("Per-Plane Gradient Breakdown") - print("="*70) - - for plane_idx in range(3): - def single_plane_mse(position_offsets): - pos = positions_cm + position_offsets - wp = compute_wireplane_for_plane(pos, plane_idx) - return jnp.mean((wp - ref_wireplanes[plane_idx]) ** 2) - - grad_fn_p = jax.grad(single_plane_mse) - grads_p = grad_fn_p(offset) - - angle = float(angles_rad[plane_idx]) - sin_a, cos_a = np.sin(angle), np.cos(angle) - - print(f"\n{plane_names[plane_idx]} (sin={sin_a:.3f}, cos={cos_a:.3f}):") - print(f" ∂L/∂x = {float(jnp.mean(grads_p[:,0])):>12.4e}") - print(f" ∂L/∂y = {float(jnp.mean(grads_p[:,1])):>12.4e}") - print(f" ∂L/∂z = {float(jnp.mean(grads_p[:,2])):>12.4e}") - - # Check gradient ratio matches angle - mean_y = float(jnp.mean(grads_p[:,1])) - mean_z = float(jnp.mean(grads_p[:,2])) - if abs(sin_a) > 0.01 and abs(cos_a) > 0.01 and abs(mean_z) > 1e-10: - ratio = (mean_y / sin_a) / (mean_z / cos_a) - print(f" (∂L/∂y/sin) / (∂L/∂z/cos) = {ratio:.4f} (should be ~1.0)") - - print("\n" + "="*70) - print("SUMMARY") - print("="*70) - print(""" -With proper geometry from config: -- All wire positions are within valid detector bounds -- Each plane uses its correct angle, spacing, and offset - -Expected gradient behavior: -- X: Affects drift time → attenuation, diffusion (all planes) -- Y: Affects wire coord via y*sin(angle) (U and V planes, NOT Y plane) -- Z: Affects wire coord via z*cos(angle) (all planes) - -For Y-gradient: -- U plane (+60°): sin(60°) = 0.866 → strong Y contribution -- V plane (-60°): sin(-60°) = -0.866 → strong Y contribution (opposite sign) -- Y plane (0°): sin(0°) = 0 → NO Y contribution - -When U and V planes are properly in range, Y-gradients should be non-zero! -""") - - return True - - -if __name__ == "__main__": - main() diff --git a/closure/archive/gradient_test/gradient_test/test_segments_and_de.py b/closure/archive/gradient_test/gradient_test/test_segments_and_de.py deleted file mode 100644 index 619ce48..0000000 --- a/closure/archive/gradient_test/gradient_test/test_segments_and_de.py +++ /dev/null @@ -1,268 +0,0 @@ -#!/usr/bin/env python3 -""" -Test per-segment gradients with many segments and learnable dE. -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import jax -import jax.numpy as jnp -import numpy as np - -from physics_params import create_default_params -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - - -def main(): - print("="*60) - print("Per-Segment Gradients: Positions + dE") - print("="*60) - - # Load data - config_path = "../config/cubic_wireplane_config.yaml" - data_path = "../mpvmpr_20.h5" - - detector_config = generate_detector(config_path) - step_data = load_particle_step_data(data_path, 0) - - n_segments = 500 # Many segments with overlap - de_true = jnp.asarray(step_data['de'][:n_segments], dtype=jnp.float32) - dx = jnp.asarray(step_data['dx'][:n_segments], dtype=jnp.float32) - positions_cm = jnp.asarray(step_data['position'][:n_segments], dtype=jnp.float32) / 10.0 - - print(f"\nSegments: {n_segments}") - print(f"Position range (cm):") - print(f" X: [{float(positions_cm[:,0].min()):.2f}, {float(positions_cm[:,0].max()):.2f}]") - print(f" Y: [{float(positions_cm[:,1].min()):.2f}, {float(positions_cm[:,1].max()):.2f}]") - print(f" Z: [{float(positions_cm[:,2].min()):.2f}, {float(positions_cm[:,2].max()):.2f}]") - print(f"dE range: [{float(de_true.min()):.4f}, {float(de_true.max()):.4f}]") - - # Detector params - drift_velocity = detector_config['drift_velocity_cm_us'] - electron_lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 - time_step_size = detector_config['time_step_size_us'] - num_time_steps = detector_config['num_time_steps'] - - angles_rad = detector_config['angles_rad'][0] - wire_spacings_cm = detector_config['wire_spacings_cm'][0] - index_offsets = detector_config['index_offsets'][0] - num_wires_actual = detector_config['num_wires_actual'][0] - - physics_params = create_default_params() - K_wire = 3 - K_time = 5 - - # Verify charges are non-zero - charges = calculate_box_model_charge_with_physics_params(de_true, dx, physics_params) - print(f"\nCharges range: [{float(charges.min()):.2e}, {float(charges.max()):.2e}]") - print(f"Charges sum: {float(charges.sum()):.2e}") - - def compute_wireplane(positions, de_vals, plane_idx): - """Compute wireplane for one plane.""" - n_seg = positions.shape[0] - - angle = angles_rad[plane_idx] - wire_spacing = float(wire_spacings_cm[plane_idx]) - wire_offset = float(index_offsets[plane_idx]) - num_wires = int(num_wires_actual[plane_idx]) - - x_pos = positions[:, 0] - y_pos = positions[:, 1] - z_pos = positions[:, 2] - - drift_times = jnp.abs(x_pos) / drift_velocity - wire_coord = y_pos * jnp.sin(angle) + z_pos * jnp.cos(angle) - - # Use proper recombination function - charges = calculate_box_model_charge_with_physics_params(de_vals, dx, physics_params) - attenuation = jnp.exp(-drift_times / electron_lifetime_us) - attenuated_charges = charges * attenuation - - sigma_wire_sq = 2.0 * physics_params.diffusion_trans * drift_times + 1e-12 - sigma_time_sq = 2.0 * (physics_params.diffusion_long / (drift_velocity ** 2)) * drift_times + 1e-12 - sigma_wire = jnp.sqrt(sigma_wire_sq) - sigma_time = jnp.sqrt(sigma_time_sq) - - wire_pos = wire_coord / wire_spacing + wire_offset - center_wire = jnp.floor(wire_pos).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - wire_subbin = wire_pos - center_wire.astype(jnp.float32) - time_subbin = drift_times / time_step_size - center_time.astype(jnp.float32) - - wire_offsets_k = jnp.arange(-K_wire, K_wire + 1) - time_offsets_k = jnp.arange(-K_time, K_time + 1) - - wire_distances = (wire_offsets_k[None, :] - wire_subbin[:, None]) * wire_spacing - time_distances = (time_offsets_k[None, :] - time_subbin[:, None]) * time_step_size - - wire_gauss = jnp.exp(-wire_distances**2 / (2 * sigma_wire_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_wire[:, None] + 1e-12) - time_gauss = jnp.exp(-time_distances**2 / (2 * sigma_time_sq[:, None])) / (jnp.sqrt(2 * jnp.pi) * sigma_time[:, None] + 1e-12) - - kernel_2d = wire_gauss[:, :, None] * time_gauss[:, None, :] - weighted_kernel = kernel_2d * attenuated_charges[:, None, None] - - n_wire_k = 2 * K_wire + 1 - n_time_k = 2 * K_time + 1 - - wire_indices_k = center_wire[:, None] + wire_offsets_k[None, :] - time_indices_k = center_time[:, None] + time_offsets_k[None, :] - - wire_indices_k = jnp.clip(wire_indices_k, 0, num_wires - 1) - time_indices_k = jnp.clip(time_indices_k, 0, num_time_steps - 1) - - wire_idx_3d = jnp.broadcast_to(wire_indices_k[:, :, None], (n_seg, n_wire_k, n_time_k)) - time_idx_3d = jnp.broadcast_to(time_indices_k[:, None, :], (n_seg, n_wire_k, n_time_k)) - - wire_flat = wire_idx_3d.reshape(-1) - time_flat = time_idx_3d.reshape(-1) - values_flat = weighted_kernel.reshape(-1) - - wireplane = jnp.zeros((num_wires, num_time_steps)) - wireplane = wireplane.at[wire_flat, time_flat].add(values_flat) - - return wireplane - - # Compute reference wireplanes with true values - ref_wireplanes = [compute_wireplane(positions_cm, de_true, i) for i in range(3)] - - print(f"\nReference wireplane max signals:") - for i, wp in enumerate(ref_wireplanes): - print(f" Plane {i}: max={float(jnp.max(wp)):.2e}, sum={float(jnp.sum(wp)):.2e}") - - # ========================================================================= - # Test 1: Position gradients - # ========================================================================= - print("\n" + "="*60) - print("TEST 1: Position Gradients (500 segments)") - print("="*60) - - def pos_loss(pos_offsets): - pos = positions_cm + pos_offsets - total = 0.0 - for i in range(3): - wp = compute_wireplane(pos, de_true, i) - total += jnp.mean((wp - ref_wireplanes[i]) ** 2) - return total / 3.0 - - # Check loss values first - zero_offset = jnp.zeros((n_segments, 3)) - small_offset = jnp.ones((n_segments, 3)) * 0.05 - - loss_at_zero = float(pos_loss(zero_offset)) - loss_at_offset = float(pos_loss(small_offset)) - - print(f"\nLoss at zero offset: {loss_at_zero:.4e}") - print(f"Loss at 0.05 offset: {loss_at_offset:.4e}") - - grad_pos_fn = jax.grad(pos_loss) - grads_pos = grad_pos_fn(small_offset) - - print(f"\nGradient shape: {grads_pos.shape}") - print(f"\nGradient statistics:") - for d, dim in enumerate(['x', 'y', 'z']): - g = grads_pos[:, d] - print(f" ∂L/∂{dim}: mean={float(jnp.mean(g)):.4e}, std={float(jnp.std(g)):.4e}") - - # Check a few segments numerically - print("\nNumerical check (segments 0, 250, 499):") - eps = 1e-4 - for seg_idx in [0, 250, 499]: - print(f"\n Segment {seg_idx}:") - for d, dim in enumerate(['x', 'y', 'z']): - delta = jnp.zeros((n_segments, 3)) - delta = delta.at[seg_idx, d].set(eps) - loss_plus = float(pos_loss(small_offset + delta)) - loss_minus = float(pos_loss(small_offset - delta)) - num_grad = (loss_plus - loss_minus) / (2 * eps) - ana_grad = float(grads_pos[seg_idx, d]) - - if abs(num_grad) > 1e-12: - rel_err = abs(ana_grad - num_grad) / abs(num_grad) - status = "MATCH" if rel_err < 0.3 else "DIFF" - else: - status = "BOTH~0" if abs(ana_grad) < 1e-10 else "CHECK" - - print(f" ∂L/∂{dim}: ana={ana_grad:.4e}, num={num_grad:.4e} [{status}]") - - nonzero_pos = jnp.sum(jnp.abs(grads_pos) > 1e-12) - print(f"\nNon-zero gradients: {int(nonzero_pos)} / {n_segments * 3} ({100*int(nonzero_pos)/(n_segments*3):.1f}%)") - - # ========================================================================= - # Test 2: dE gradients - # ========================================================================= - print("\n" + "="*60) - print("TEST 2: dE Gradients (500 segments)") - print("="*60) - - def de_loss(de_scale): - """Scale dE by per-segment factors.""" - de_scaled = de_true * de_scale - total = 0.0 - for i in range(3): - wp = compute_wireplane(positions_cm, de_scaled, i) - total += jnp.mean((wp - ref_wireplanes[i]) ** 2) - return total / 3.0 - - # Check loss values - ones_scale = jnp.ones(n_segments) - perturbed_scale = jnp.ones(n_segments) * 1.1 - - loss_at_ones = float(de_loss(ones_scale)) - loss_at_perturbed = float(de_loss(perturbed_scale)) - - print(f"\nLoss at scale=1.0: {loss_at_ones:.4e}") - print(f"Loss at scale=1.1: {loss_at_perturbed:.4e}") - - grad_de_fn = jax.grad(de_loss) - grads_de = grad_de_fn(perturbed_scale) - - print(f"\nGradient shape: {grads_de.shape}") - print(f"\nGradient statistics:") - print(f" ∂L/∂(dE_scale): mean={float(jnp.mean(grads_de)):.4e}, std={float(jnp.std(grads_de)):.4e}") - - # Numerical check - print("\nNumerical check (segments 0, 250, 499):") - for seg_idx in [0, 250, 499]: - delta = jnp.zeros(n_segments) - delta = delta.at[seg_idx].set(eps) - loss_plus = float(de_loss(perturbed_scale + delta)) - loss_minus = float(de_loss(perturbed_scale - delta)) - num_grad = (loss_plus - loss_minus) / (2 * eps) - ana_grad = float(grads_de[seg_idx]) - - if abs(num_grad) > 1e-12: - rel_err = abs(ana_grad - num_grad) / abs(num_grad) - status = "MATCH" if rel_err < 0.3 else "DIFF" - else: - status = "BOTH~0" if abs(ana_grad) < 1e-10 else "CHECK" - print(f" Segment {seg_idx}: ana={ana_grad:.4e}, num={num_grad:.4e} [{status}]") - - nonzero_de = jnp.sum(jnp.abs(grads_de) > 1e-12) - print(f"\nNon-zero gradients: {int(nonzero_de)} / {n_segments} ({100*int(nonzero_de)/n_segments:.1f}%)") - - # ========================================================================= - # Summary - # ========================================================================= - print("\n" + "="*60) - print("SUMMARY") - print("="*60) - print(f"Tested {n_segments} overlapping segments.") - print(f"Position gradients shape: ({n_segments}, 3)") - print(f"dE gradients shape: ({n_segments},)") - - pos_ok = int(nonzero_pos) == n_segments * 3 - de_ok = int(nonzero_de) == n_segments - - print(f"\nPosition gradients: {'PASS' if pos_ok else 'PARTIAL'} ({100*int(nonzero_pos)/(n_segments*3):.1f}% non-zero)") - print(f"dE gradients: {'PASS' if de_ok else 'PARTIAL'} ({100*int(nonzero_de)/n_segments:.1f}% non-zero)") - - return True - - -if __name__ == "__main__": - main() diff --git a/closure/archive/gradient_test/gradient_test/test_simple.py b/closure/archive/gradient_test/gradient_test/test_simple.py deleted file mode 100644 index 81b51a7..0000000 --- a/closure/archive/gradient_test/gradient_test/test_simple.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python3 -"""Test 1 segment with MSE vs centroid loss, starting 5cm away.""" - -import sys, os -sys.path.insert(0, '.') - -import jax -import jax.numpy as jnp -import numpy as np -import optax - -from physics_params import create_default_params -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import calculate_box_model_charge_with_physics_params - -detector_config = generate_detector('../config/cubic_wireplane_config.yaml') -step_data = load_particle_step_data('../mpvmpr_20.h5', 0) - -drift_velocity = detector_config['drift_velocity_cm_us'] -electron_lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 -time_step_size = detector_config['time_step_size_us'] -num_time_steps = detector_config['num_time_steps'] -angles_rad = detector_config['angles_rad'][0] -wire_spacings_cm = detector_config['wire_spacings_cm'][0] -index_offsets = detector_config['index_offsets'][0] -num_wires_actual = detector_config['num_wires_actual'][0] -physics_params = create_default_params() -K_wire, K_time = 3, 5 - -n_seg = 1 -de = jnp.asarray(step_data['de'][:n_seg], dtype=jnp.float32) -dx = jnp.asarray(step_data['dx'][:n_seg], dtype=jnp.float32) -true_pos = jnp.asarray(step_data['position'][:n_seg], dtype=jnp.float32) / 10.0 - -print(f"True position: {true_pos[0]}") - -def compute_wireplane(positions, plane_idx): - angle = angles_rad[plane_idx] - wire_spacing = float(wire_spacings_cm[plane_idx]) - wire_offset = float(index_offsets[plane_idx]) - num_wires = int(num_wires_actual[plane_idx]) - - drift_times = jnp.abs(positions[:, 0]) / drift_velocity - wire_coord = positions[:, 1] * jnp.sin(angle) + positions[:, 2] * jnp.cos(angle) - - charges = calculate_box_model_charge_with_physics_params(de, dx, physics_params) - attenuated_charges = charges * jnp.exp(-drift_times / electron_lifetime_us) - - sigma_wire = jnp.sqrt(2.0 * physics_params.diffusion_trans * drift_times + 1e-12) - sigma_time = jnp.sqrt(2.0 * (physics_params.diffusion_long / drift_velocity**2) * drift_times + 1e-12) - - wire_pos = wire_coord / wire_spacing + wire_offset - center_wire = jnp.floor(wire_pos).astype(jnp.int32) - center_time = jnp.floor(drift_times / time_step_size).astype(jnp.int32) - - wire_subbin = wire_pos - center_wire.astype(jnp.float32) - time_subbin = drift_times / time_step_size - center_time.astype(jnp.float32) - - wire_k = jnp.arange(-K_wire, K_wire + 1) - time_k = jnp.arange(-K_time, K_time + 1) - - wire_dist = (wire_k[None, :] - wire_subbin[:, None]) * wire_spacing - time_dist = (time_k[None, :] - time_subbin[:, None]) * time_step_size - - wire_gauss = jnp.exp(-wire_dist**2 / (2 * sigma_wire[:, None]**2 + 1e-12)) - time_gauss = jnp.exp(-time_dist**2 / (2 * sigma_time[:, None]**2 + 1e-12)) - - kernel = wire_gauss[:, :, None] * time_gauss[:, None, :] * attenuated_charges[:, None, None] - - n_w, n_t = 2*K_wire+1, 2*K_time+1 - w_idx = jnp.clip(center_wire[:, None] + wire_k, 0, num_wires-1) - t_idx = jnp.clip(center_time[:, None] + time_k, 0, num_time_steps-1) - - w_3d = jnp.broadcast_to(w_idx[:, :, None], (n_seg, n_w, n_t)) - t_3d = jnp.broadcast_to(t_idx[:, None, :], (n_seg, n_w, n_t)) - - wp = jnp.zeros((num_wires, num_time_steps)) - wp = wp.at[w_3d.reshape(-1), t_3d.reshape(-1)].add(kernel.reshape(-1)) - return wp - -def centroid(wp): - w_idx = jnp.arange(wp.shape[0]) - t_idx = jnp.arange(wp.shape[1]) - total = jnp.sum(wp) + 1e-12 - w_cent = jnp.sum(wp * w_idx[:, None]) / total - t_cent = jnp.sum(wp * t_idx[None, :]) / total - return w_cent, t_cent - -target_wps = [compute_wireplane(true_pos, i) for i in range(3)] -target_cents = [centroid(wp) for wp in target_wps] - -def mse_loss(pos): - return sum(jnp.mean((compute_wireplane(pos, i) - target_wps[i])**2) for i in range(3)) / 3.0 - -def centroid_loss(pos): - loss = 0.0 - for i in range(3): - wp = compute_wireplane(pos, i) - w_c, t_c = centroid(wp) - loss += (w_c - target_cents[i][0])**2 + (t_c - target_cents[i][1])**2 - return loss / 3.0 - -# Start 5cm away -np.random.seed(42) -init_offset = jnp.array(np.random.randn(n_seg, 3) * 5.0, dtype=jnp.float32) -init_err = float(jnp.mean(jnp.abs(init_offset))) - -print(f"\n1 segment, starting {init_err:.2f} cm away") -print("="*50) - -for loss_name, loss_fn in [('MSE', mse_loss), ('Centroid', centroid_loss)]: - positions = true_pos + init_offset - optimizer = optax.adam(0.01) - opt_state = optimizer.init(positions) - - print(f"\n{loss_name} Loss:") - for i in range(500): - loss, grads = jax.value_and_grad(loss_fn)(positions) - updates, opt_state = optimizer.update(grads, opt_state) - positions = optax.apply_updates(positions, updates) - - if i % 100 == 0: - err = float(jnp.mean(jnp.abs(positions - true_pos))) - print(f" iter {i:3d}: loss={float(loss):.4e}, err={err:.3f} cm") - - final_err = float(jnp.mean(jnp.abs(positions - true_pos))) - print(f" Final: {init_err:.3f} -> {final_err:.3f} cm") diff --git a/closure/archive/gradient_test/gradient_test/tools/__init__.py b/closure/archive/gradient_test/gradient_test/tools/__init__.py deleted file mode 100644 index dfe1913..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/__init__.py +++ /dev/null @@ -1,64 +0,0 @@ -""" -JAXTPC Refactored Tools Package - -This package contains the refactored simulation tools for LArTPC detector simulation. -See REFACTORING_PLAN.md for details on the changes from the original tools package. - -Main entry points: -- DetectorSimulator: Main simulation class -- run_simulation: Convenience function for single-event processing - -Configuration classes: -- DepositData: Input data container -- DriftParams: Drift physics parameters -- TimeParams: Time discretization parameters -- PlaneGeometry: Wire plane geometry -- DiffusionParams: Diffusion parameters -- TrackHitsConfig: Track labeling configuration -""" - -from tools.config import ( - DepositData, - DriftParams, - TimeParams, - PlaneGeometry, - DiffusionParams, - TrackHitsConfig, - create_diffusion_params, - create_drift_params, - create_time_params, - create_plane_geometry, - create_track_hits_config, -) - -from tools.simulation import ( - DetectorSimulator, - run_simulation, -) - -from tools.wires import ( - sparse_buckets_to_dense, - accumulate_response_signals_sparse_bucketed, -) - -__all__ = [ - # Config classes - 'DepositData', - 'DriftParams', - 'TimeParams', - 'PlaneGeometry', - 'DiffusionParams', - 'TrackHitsConfig', - # Factory functions - 'create_diffusion_params', - 'create_drift_params', - 'create_time_params', - 'create_plane_geometry', - 'create_track_hits_config', - # Main simulation - 'DetectorSimulator', - 'run_simulation', - # Sparse utilities - 'sparse_buckets_to_dense', - 'accumulate_response_signals_sparse_bucketed', -] diff --git a/closure/archive/gradient_test/gradient_test/tools/config.py b/closure/archive/gradient_test/gradient_test/tools/config.py deleted file mode 100644 index 6565315..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/config.py +++ /dev/null @@ -1,217 +0,0 @@ -""" -Configuration classes for JAXTPC detector simulation. - -This module defines all NamedTuple parameter bundles used throughout -the simulation code for clean parameter passing and type hints. -""" - -from typing import NamedTuple -import numpy as np -import jax.numpy as jnp - - -class DepositData(NamedTuple): - """Padded input data from particle simulation steps.""" - positions_mm: jnp.ndarray # (N_pad, 3) - hit positions - charges: jnp.ndarray # (N_pad,) - recombined charge - valid_mask: jnp.ndarray # (N_pad,) - True for real hits - theta: jnp.ndarray # (N_pad,) - polar angle of step direction - phi: jnp.ndarray # (N_pad,) - azimuthal angle of step direction - track_ids: jnp.ndarray # (N_pad,) - particle track ID - - -class DriftParams(NamedTuple): - """Drift physics parameters (detector-wide constants).""" - detector_half_width_cm: float # Maximum drift distance - velocity_cm_us: float # Drift velocity - lifetime_us: float # Electron lifetime (in μs) - diffusion_long_cm2_us: float # Longitudinal diffusion coefficient - diffusion_trans_cm2_us: float # Transverse diffusion coefficient - - -class TimeParams(NamedTuple): - """Time axis discretization.""" - num_steps: int # Number of time bins - step_size_us: float # Duration per bin (μs) - - -class PlaneGeometry(NamedTuple): - """Geometry for one wire plane.""" - angle_rad: float # Wire angle in YZ plane - wire_spacing_cm: float # Wire pitch - distance_from_anode_cm: float # Plane position relative to anode - index_offset: int # Offset for absolute wire indexing - min_wire_idx: int # Minimum absolute wire index - max_wire_idx: int # Maximum absolute wire index - num_wires: int # Total wire count - plane_type: str # 'U', 'V', or 'Y' - - -class DiffusionParams(NamedTuple): - """Diffusion parameters for signal generation.""" - # Source values (from physics) - max_sigma_trans_unitless: float # Max transverse σ (wire spacing units) - max_sigma_long_unitless: float # Max longitudinal σ (time bin units) - - # Derived grid sizes (computed from sigmas) - K_wire: int # Half-width in wire direction - K_time: int # Half-width in time direction - - # Kernel interpolation - num_s: int # Number of diffusion levels for kernel - - -class TrackHitsConfig(NamedTuple): - """Configuration for track hit labeling.""" - threshold: float # Minimum charge to keep - max_tracks: int # Max tracks for array pre-allocation - max_keys: int # Max unique (track, wire, time) combinations - - -def create_diffusion_params( - max_sigma_trans_unitless: float, - max_sigma_long_unitless: float, - num_s: int = 16, - n_sigma: float = 3.0 -) -> DiffusionParams: - """ - Create DiffusionParams with K values computed from sigmas. - - Parameters - ---------- - max_sigma_trans_unitless : float - Maximum transverse diffusion sigma in unitless grid coordinates (wires). - max_sigma_long_unitless : float - Maximum longitudinal diffusion sigma in unitless grid coordinates (time bins). - num_s : int, optional - Number of diffusion levels for kernel interpolation, by default 16. - n_sigma : float, optional - Number of sigma to cover (determines K values), by default 3.0. - - Returns - ------- - DiffusionParams - Configured diffusion parameters with derived K values. - """ - K_wire = max(1, int(np.ceil(n_sigma * max_sigma_trans_unitless))) - K_time = max(1, int(np.ceil(n_sigma * max_sigma_long_unitless))) - - return DiffusionParams( - max_sigma_trans_unitless=max_sigma_trans_unitless, - max_sigma_long_unitless=max_sigma_long_unitless, - K_wire=K_wire, - K_time=K_time, - num_s=num_s, - ) - - -def create_drift_params(detector_config: dict) -> DriftParams: - """ - Create DriftParams from detector configuration dictionary. - - Parameters - ---------- - detector_config : dict - Detector configuration from generate_detector(). - - Returns - ------- - DriftParams - Configured drift parameters. - """ - # Convert electron lifetime from ms to μs - lifetime_us = detector_config['electron_lifetime_ms'] * 1000.0 - - return DriftParams( - detector_half_width_cm=detector_config['detector_half_width_x'], - velocity_cm_us=detector_config['drift_velocity_cm_us'], - lifetime_us=lifetime_us, - diffusion_long_cm2_us=detector_config['longitudinal_diffusion_cm2_us'], - diffusion_trans_cm2_us=detector_config['transverse_diffusion_cm2_us'], - ) - - -def create_time_params(detector_config: dict) -> TimeParams: - """ - Create TimeParams from detector configuration dictionary. - - Parameters - ---------- - detector_config : dict - Detector configuration from generate_detector(). - - Returns - ------- - TimeParams - Configured time parameters. - """ - return TimeParams( - num_steps=detector_config['num_time_steps'], - step_size_us=detector_config['time_step_size_us'], - ) - - -def create_plane_geometry( - detector_config: dict, - side_idx: int, - plane_idx: int, - plane_type: str -) -> PlaneGeometry: - """ - Create PlaneGeometry for a specific wire plane. - - Parameters - ---------- - detector_config : dict - Detector configuration from generate_detector(). - side_idx : int - Side index (0 or 1). - plane_idx : int - Plane index (0, 1, or 2). - plane_type : str - Plane type ('U', 'V', or 'Y'). - - Returns - ------- - PlaneGeometry - Configured plane geometry. - """ - return PlaneGeometry( - angle_rad=float(detector_config['angles_rad'][side_idx, plane_idx]), - wire_spacing_cm=float(detector_config['wire_spacings_cm'][side_idx, plane_idx]), - distance_from_anode_cm=float(detector_config['all_plane_distances_cm'][side_idx, plane_idx]), - index_offset=int(detector_config['index_offsets'][side_idx, plane_idx]), - min_wire_idx=int(detector_config['min_wire_indices_abs'][side_idx, plane_idx]), - max_wire_idx=int(detector_config['max_wire_indices_abs'][side_idx, plane_idx]), - num_wires=int(detector_config['num_wires_actual'][side_idx, plane_idx]), - plane_type=plane_type, - ) - - -def create_track_hits_config( - threshold: float = 1.0, - max_tracks: int = 10000, - max_keys: int = 1000000 -) -> TrackHitsConfig: - """ - Create TrackHitsConfig with specified parameters. - - Parameters - ---------- - threshold : float, optional - Minimum charge threshold for keeping hits, by default 1.0. - max_tracks : int, optional - Maximum number of tracks for array pre-allocation, by default 10000. - max_keys : int, optional - Maximum number of unique (track, wire, time) combinations, by default 1000000. - - Returns - ------- - TrackHitsConfig - Configured track hits parameters. - """ - return TrackHitsConfig( - threshold=threshold, - max_tracks=max_tracks, - max_keys=max_keys, - ) diff --git a/closure/archive/gradient_test/gradient_test/tools/drift.py b/closure/archive/gradient_test/gradient_test/tools/drift.py deleted file mode 100644 index 32c749b..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/drift.py +++ /dev/null @@ -1,126 +0,0 @@ -""" -Drift physics calculations for LArTPC simulation. - -This module provides JIT-compiled functions for calculating electron drift -times and distances, as well as charge attenuation due to electron lifetime. -""" - -import jax -import jax.numpy as jnp -from functools import partial - - -@partial(jax.jit, static_argnums=(1,)) -def compute_drift_to_plane(positions_cm, detector_half_width_x, drift_velocity_cm_us, plane_dist_from_anode_cm): - """ - Calculate the drift time and distance to a single plane for each position. - - Parameters - ---------- - positions_cm : jnp.ndarray - Array of shape (n_hits, 3) containing the (x, y, z) positions in cm. - detector_half_width_x : float - Half-width of the detector in the x-direction in cm. - drift_velocity_cm_us : float - Drift velocity in cm/μs. - plane_dist_from_anode_cm : float - Distance of the plane from the anode in cm. - - Returns - ------- - drift_distance_cm : jnp.ndarray - Array of shape (n_hits,) containing the drift distances in cm. - drift_time_us : jnp.ndarray - Array of shape (n_hits,) containing the drift times in μs. - positions_yz_cm : jnp.ndarray - Array of shape (n_hits, 2) containing the (y, z) positions in cm. - """ - x = positions_cm[:, 0] - positions_yz_cm = positions_cm[:, 1:3] # Shape: (n_hits, 2) - is_left_side = x < 0 - left_anode_x = -detector_half_width_x - right_anode_x = detector_half_width_x - plane_x_left = left_anode_x + plane_dist_from_anode_cm - plane_x_right = right_anode_x - plane_dist_from_anode_cm - plane_x = jnp.where(is_left_side, plane_x_left, plane_x_right) - drift_distance_cm = jnp.abs(x - plane_x) - drift_time_us = jnp.where(drift_velocity_cm_us > 1e-9, - drift_distance_cm / drift_velocity_cm_us, - jnp.inf) - return drift_distance_cm, drift_time_us, positions_yz_cm - - -@jax.jit -def correct_drift_for_plane(drift_distance_cm, drift_time_us, drift_velocity_cm_us, plane_dist_difference_cm): - """ - Correct drift time/distance for planes relative to the furthest plane. - The correction is subtracted because planes closer to the anode have less drift distance. - - Parameters - ---------- - drift_distance_cm : jnp.ndarray - Array of shape (n_hits,) containing the drift distances to the furthest plane in cm. - drift_time_us : jnp.ndarray - Array of shape (n_hits,) containing the drift times to the furthest plane in μs. - drift_velocity_cm_us : float - Drift velocity in cm/μs. - plane_dist_difference_cm : float - Distance difference between the furthest plane and this plane in cm. - Positive value means this plane is closer to the anode than the furthest plane. - - Returns - ------- - corrected_drift_distance_cm : jnp.ndarray - Array of shape (n_hits,) containing the corrected drift distances in cm. - corrected_drift_time_us : jnp.ndarray - Array of shape (n_hits,) containing the corrected drift times in μs. - """ - # A positive plane_dist_difference_cm means this plane is closer to the anode than the furthest plane - drift_distance_correction = plane_dist_difference_cm - drift_time_correction = jnp.where(drift_velocity_cm_us > 1e-9, - drift_distance_correction / drift_velocity_cm_us, - jnp.inf) - - corrected_drift_distance_cm = drift_distance_cm - drift_distance_correction - corrected_drift_time_us = drift_time_us - drift_time_correction - - # Ensure we don't get negative distances/times due to correction - corrected_drift_distance_cm = jnp.maximum(corrected_drift_distance_cm, 0.0) - corrected_drift_time_us = jnp.maximum(corrected_drift_time_us, 0.0) - - return corrected_drift_distance_cm, corrected_drift_time_us - - -@jax.jit -def compute_lifetime_attenuation(drift_distance_cm, drift_velocity_cm_us, electron_lifetime_ms): - """ - Calculate charge attenuation due to electron lifetime during drift. - Uses exponential decay model. - - Parameters - ---------- - drift_distance_cm : jnp.ndarray - Array of shape (n_hits,) containing the drift distances in cm. - drift_velocity_cm_us : float - Drift velocity in cm/μs. - electron_lifetime_ms : float - Electron lifetime in milliseconds. - - Returns - ------- - attenuation : jnp.ndarray - Array of shape (n_hits,) containing the attenuation factors. - Values are between 0 and 1, where 1 means no attenuation. - """ - # Convert electron lifetime from ms to µs for consistent units - electron_lifetime_us = electron_lifetime_ms * 1000.0 - - # Calculate drift time in µs - drift_time_us = jnp.where(drift_velocity_cm_us > 1e-9, - drift_distance_cm / drift_velocity_cm_us, - jnp.inf) - - # Calculate attenuation factor using exponential decay - attenuation = jnp.exp(-drift_time_us / electron_lifetime_us) - - return attenuation diff --git a/closure/archive/gradient_test/gradient_test/tools/geometry.py b/closure/archive/gradient_test/gradient_test/tools/geometry.py deleted file mode 100644 index 53058a9..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/geometry.py +++ /dev/null @@ -1,544 +0,0 @@ -""" -Detector geometry configuration for LArTPC simulation. - -This module handles loading and parsing detector configuration from YAML files, -and pre-calculates all geometry parameters needed for simulation including -wire positions, drift parameters, and diffusion coefficients. -""" - -import yaml -import os -import numpy as np -import jax.numpy as jnp -from typing import Dict, Tuple, Optional, Any, List, Union - - -def calculate_max_diffusion_sigmas( - detector_half_width_cm, - drift_velocity_cm_us, - transverse_diffusion_cm2_us, - longitudinal_diffusion_cm2_us, - wire_spacing_cm, - time_spacing_us -): - """ - Calculate maximum diffusion sigmas for the detector in both physical and unitless coordinates. - - Parameters - ---------- - detector_half_width_cm : float - Half-width of detector (max drift distance) in cm - drift_velocity_cm_us : float - Drift velocity in cm/μs - transverse_diffusion_cm2_us : float - Transverse diffusion coefficient in cm²/μs - longitudinal_diffusion_cm2_us : float - Longitudinal diffusion coefficient in cm²/μs - wire_spacing_cm : float - Wire spacing in cm (for converting to unitless) - time_spacing_us : float - Time bin spacing in μs (for converting to unitless) - - Returns - ------- - max_sigma_trans_cm : float - Maximum transverse sigma in cm - max_sigma_long_us : float - Maximum longitudinal sigma in μs - max_sigma_trans_unitless : float - Maximum transverse sigma in unitless grid coordinates (wires) - max_sigma_long_unitless : float - Maximum longitudinal sigma in unitless grid coordinates (time bins) - """ - # Maximum drift time - max_drift_time_us = detector_half_width_cm / drift_velocity_cm_us - - # Transverse sigma (spatial - in cm) - max_sigma_trans_cm = np.sqrt(2.0 * transverse_diffusion_cm2_us * max_drift_time_us) - - # Longitudinal sigma (temporal - in μs) - D_long_temporal = longitudinal_diffusion_cm2_us / (drift_velocity_cm_us ** 2) - max_sigma_long_us = np.sqrt(2.0 * D_long_temporal * max_drift_time_us) - - # Convert to unitless coordinates by dividing by grid spacing - max_sigma_trans_unitless = max_sigma_trans_cm / wire_spacing_cm - max_sigma_long_unitless = max_sigma_long_us / time_spacing_us - - return max_sigma_trans_cm, max_sigma_long_us, max_sigma_trans_unitless, max_sigma_long_unitless - - -def generate_detector(config_file_path: str) -> Optional[Dict[str, Any]]: - """ - Read a JAXTPC detector configuration YAML file and return a detector dictionary. - - Parameters - ---------- - config_file_path : str - Path to the YAML configuration file. - - Returns - ------- - dict or None - A dictionary containing all detector properties and derived parameters, - or None if loading fails. - """ - if not os.path.exists(config_file_path): - print(f"Error: Configuration file not found at {config_file_path}") - return None - - try: - with open(config_file_path, 'r') as file: - detector_config = yaml.safe_load(file) - - # Basic validation to ensure the config has the expected structure - required_keys = ['detector', 'wire_planes', 'readout', 'simulation', 'medium', 'electric_field'] - for key in required_keys: - if key not in detector_config: - print(f"Error: Missing required section '{key}' in configuration file") - return None - - # Pre-calculate all parameters needed for simulation - params = _precalculate_all_parameters(detector_config) - detector_config.update(params) - - return detector_config - except yaml.YAMLError as e: - print(f"Error parsing YAML: {e}") - return None - except Exception as e: - print(f"Error loading detector configuration: {e}") - import traceback - traceback.print_exc() - return None - - -def _precalculate_all_parameters(detector_config: Dict[str, Any]) -> Dict[str, Any]: - """ - Calculate all derived parameters needed for simulation from the detector config. - - Parameters - ---------- - detector_config : dict - Original detector configuration dictionary. - - Returns - ------- - dict - Dictionary of all derived parameters. - """ - params = {} - - # Get basic dimensions - dims_cm = get_detector_dimensions(detector_config) - params['dims_cm'] = dims_cm - - # Get drift parameters - detector_half_width_x, drift_velocity_cm_us = get_drift_params( - detector_config, dims_cm) - params['detector_half_width_x'] = detector_half_width_x - params['drift_velocity_cm_us'] = drift_velocity_cm_us - - # Get plane distances and furthest indices (combined function) - all_plane_distances_cm, furthest_plane_indices = get_plane_geometry(detector_config) - params['all_plane_distances_cm'] = all_plane_distances_cm - params['furthest_plane_indices'] = furthest_plane_indices - - # Calculate time parameters - num_time_steps, time_step_size_us, max_drift_time_us = calculate_time_params( - detector_config, dims_cm, drift_velocity_cm_us) - params['num_time_steps'] = num_time_steps - params['time_step_size_us'] = time_step_size_us - params['max_drift_time_us'] = max_drift_time_us - - # Calculate wire parameters for all planes - (params['angles_rad'], params['wire_spacings_cm'], params['index_offsets'], - params['num_wires_actual'], params['max_wire_indices_abs'], - params['min_wire_indices_abs']) = pre_calculate_all_wire_params( - detector_config, dims_cm) - - # Extract electron lifetime and diffusion parameters - params['electron_lifetime_ms'] = float(detector_config['simulation']['drift']['electron_lifetime']) - params['longitudinal_diffusion_cm2_s'] = float(detector_config['simulation']['drift']['longitudinal_diffusion']) - params['transverse_diffusion_cm2_s'] = float(detector_config['simulation']['drift']['transverse_diffusion']) - - # Convert diffusion from cm²/s to cm²/μs for consistent units - params['longitudinal_diffusion_cm2_us'] = params['longitudinal_diffusion_cm2_s'] / 1e6 - params['transverse_diffusion_cm2_us'] = params['transverse_diffusion_cm2_s'] / 1e6 - - # Get wire spacing from config (using first plane as reference - all planes have same spacing) - wire_spacing_cm = float(detector_config['wire_planes']['sides'][0]['planes'][0]['wire_spacing']) - - # Calculate maximum diffusion sigmas (both physical and unitless) - (max_sigma_trans_cm, max_sigma_long_us, - max_sigma_trans_unitless, max_sigma_long_unitless) = calculate_max_diffusion_sigmas( - detector_half_width_x, - drift_velocity_cm_us, - params['transverse_diffusion_cm2_us'], - params['longitudinal_diffusion_cm2_us'], - wire_spacing_cm, - time_step_size_us - ) - params['max_sigma_trans_cm'] = max_sigma_trans_cm - params['max_sigma_long_us'] = max_sigma_long_us - params['max_sigma_trans_unitless'] = max_sigma_trans_unitless - params['max_sigma_long_unitless'] = max_sigma_long_unitless - - # Note: sigma_wire_base_cm and sigma_time_base_us were removed as unused - - return params - - -def get_detector_dimensions(detector_config: Dict[str, Any]) -> Dict[str, float]: - """ - Extract detector dimensions from config and convert them to floats. - - Parameters - ---------- - detector_config : dict - Detector configuration dictionary. - - Returns - ------- - dict - Dictionary of detector dimensions in cm. - """ - dims_cm = detector_config['detector']['dimensions'] - return {k: float(v) for k, v in dims_cm.items()} - - -def get_drift_params(detector_config: Dict[str, Any], - dims_cm: Optional[Dict[str, float]] = None) -> Tuple[float, float]: - """ - Extract global drift parameters, converting velocity to cm/us. - - Parameters - ---------- - detector_config : dict - Detector configuration dictionary. - dims_cm : dict, optional - Pre-calculated dimensions to avoid redundant calculation. - If None, dimensions are calculated. - - Returns - ------- - tuple - (detector_half_width_x, drift_velocity) in cm and cm/us respectively. - """ - if dims_cm is None: - dims_cm = get_detector_dimensions(detector_config) - - detector_half_width_x = dims_cm['x'] / 2.0 - drift_velocity_mm_us = float(detector_config['simulation']['drift']['velocity']) - drift_velocity_cm_us = drift_velocity_mm_us / 10.0 # Convert mm/us to cm/us - - if drift_velocity_cm_us <= 1e-9: - raise ValueError("Drift velocity must be positive.") - - return detector_half_width_x, drift_velocity_cm_us - - -def get_plane_geometry(detector_config: Dict[str, Any]) -> Tuple[jnp.ndarray, np.ndarray]: - """ - Get distances for all planes from anode and identify furthest plane per side. - - Parameters - ---------- - detector_config : dict - Detector configuration dictionary. - - Returns - ------- - all_plane_distances_cm : jnp.ndarray - Array of shape (2, 3) with distances from anode in cm. - furthest_plane_indices : np.ndarray - Array of shape (2,) with indices of furthest planes. - """ - # Get plane distances - distances_cm = np.zeros((2, 3), dtype=float) - - for side_idx in range(2): - for plane_idx in range(3): - plane_config = detector_config['wire_planes']['sides'][side_idx]['planes'][plane_idx] - distances_cm[side_idx, plane_idx] = float(plane_config['distance_from_anode']) - - all_plane_distances_cm = jnp.array(distances_cm) - - # Get furthest plane indices - furthest_plane_indices = np.zeros(2, dtype=int) - - for side_idx in range(2): - furthest_plane_indices[side_idx] = np.argmax(all_plane_distances_cm[side_idx]) - - return all_plane_distances_cm, furthest_plane_indices - - -def get_single_plane_wire_params(detector_config: Dict[str, Any], - side_idx: int, - plane_idx: int, - dims_cm: Optional[Dict[str, float]] = None) -> Tuple[float, float, int, int, int]: - """ - Extract wire parameters for a single specified plane. - - Handles angles, spacing (cm), calculates offset and wire count/range. - - Parameters - ---------- - detector_config : dict - Detector configuration dictionary. - side_idx : int - Index of the detector side (0 or 1). - plane_idx : int - Index of the plane (0, 1, or 2). - dims_cm : dict, optional - Pre-calculated dimensions to avoid redundant calculation. - If None, dimensions are calculated. - - Returns - ------- - angle_rad : float - Wire angle in radians. - wire_spacing_cm : float - Spacing between wires in cm. - index_offset : int - Wire index offset. - num_wires : int - Number of wires in the plane. - max_wire_idx_abs : int - Maximum absolute wire index. - """ - if dims_cm is None: - dims_cm = get_detector_dimensions(detector_config) - - detector_y, detector_z = dims_cm['y'], dims_cm['z'] - # Assumes symmetrical geometry defined in the first side entry - plane_config = detector_config['wire_planes']['sides'][0]['planes'][plane_idx] - - angle_deg = float(plane_config['angle']) - angle_rad = jnp.radians(angle_deg) - wire_spacing_cm = float(plane_config['wire_spacing']) - - if wire_spacing_cm <= 1e-9: - raise ValueError("Wire spacing must be positive.") - - cos_theta = jnp.cos(angle_rad) - sin_theta = jnp.sin(angle_rad) - half_y, half_z = detector_y / 2.0, detector_z / 2.0 - - # Calculate corners of the detector in the YZ plane - corners_centered = jnp.array([ - [-half_y, -half_z], [+half_y, -half_z], [-half_y, +half_z], [+half_y, +half_z] - ], dtype=jnp.float32) - - # Project corners onto the wire direction - r_values = corners_centered[:, 0] * sin_theta + corners_centered[:, 1] * cos_theta - r_min = jnp.min(r_values) - r_max = jnp.max(r_values) - - # Calculate offset - index_offset = 0 - if r_min < -1e-9: - index_offset = int(jnp.floor(jnp.abs(r_min / wire_spacing_cm) + 1e-9)) + 1 - - # Calculate relative and absolute indices - idx_min_rel = jnp.floor(r_min / wire_spacing_cm - 1e-9).astype(jnp.int32) - idx_max_rel = jnp.ceil(r_max / wire_spacing_cm + 1e-9).astype(jnp.int32) - abs_idx_min = idx_min_rel + index_offset - abs_idx_max = idx_max_rel + index_offset - - # Calculate number of wires - num_wires = int(abs_idx_max - abs_idx_min + 1) - max_wire_idx_abs = int(abs_idx_max) - - return angle_rad, wire_spacing_cm, index_offset, num_wires, max_wire_idx_abs - - -def calculate_time_params(detector_config: Dict[str, Any], - dims_cm: Optional[Dict[str, float]] = None, - drift_velocity_cm_us: Optional[float] = None) -> Tuple[int, float, float]: - """ - Calculate time-related parameters from the detector config. - - Parameters - ---------- - detector_config : dict - Detector configuration dictionary. - dims_cm : dict, optional - Pre-calculated dimensions to avoid redundant calculation. - If None, dimensions are calculated. - drift_velocity_cm_us : float, optional - Pre-calculated drift velocity to avoid redundant calculation. - If None, velocity is calculated. - - Returns - ------- - num_time_steps : int - Number of time steps for simulation. - time_step_size_us : float - Size of time step in μs. - max_drift_time_us : float - Maximum drift time in μs. - """ - if dims_cm is None: - dims_cm = get_detector_dimensions(detector_config) - - if drift_velocity_cm_us is None: - _, drift_velocity_cm_us = get_drift_params(detector_config, dims_cm) - - max_drift_dist_cm = dims_cm['x'] / 2.0 - - if drift_velocity_cm_us <= 1e-9: - max_drift_time_us = 0.0 - else: - max_drift_time_us = max_drift_dist_cm / drift_velocity_cm_us - - sampling_rate_mhz = float(detector_config['readout']['sampling_rate']) - - if sampling_rate_mhz <= 1e-9: - raise ValueError("Sampling rate must be positive.") - - time_step_size_us = 1.0 / sampling_rate_mhz # us - num_time_steps = int(jnp.ceil(max_drift_time_us / time_step_size_us)) + 1 - num_time_steps = max(1, num_time_steps) - - return num_time_steps, time_step_size_us, max_drift_time_us - - -def pre_calculate_all_wire_params(detector_config: Dict[str, Any], - dims_cm: Optional[Dict[str, float]] = None) -> Tuple[jnp.ndarray, ...]: - """ - Pre-calculate wire parameters for all planes and sides. - - Parameters - ---------- - detector_config : dict - Detector configuration dictionary. - dims_cm : dict, optional - Pre-calculated dimensions to avoid redundant calculation. - If None, dimensions are calculated. - - Returns - ------- - angles_rad : jnp.ndarray - Wire angles in radians, shape (2, 3). - wire_spacings_cm : jnp.ndarray - Spacing between wires in cm, shape (2, 3). - index_offsets : jnp.ndarray - Wire index offsets, shape (2, 3). - num_wires_all : jnp.ndarray - Number of wires for each plane, shape (2, 3). - max_wire_indices_abs_all : jnp.ndarray - Maximum absolute wire indices, shape (2, 3). - min_wire_indices_abs_all : jnp.ndarray - Minimum absolute wire indices, shape (2, 3). - """ - if dims_cm is None: - dims_cm = get_detector_dimensions(detector_config) - - # Initialize arrays - num_wires_all = np.zeros((2, 3), dtype=int) - max_wire_indices_abs_all = np.zeros((2, 3), dtype=int) - min_wire_indices_abs_all = np.zeros((2, 3), dtype=int) - index_offsets_all = np.zeros((2, 3), dtype=int) - wire_spacings_all = np.zeros((2, 3), dtype=float) - angles_all = np.zeros((2, 3), dtype=float) - - detector_y, detector_z = dims_cm['y'], dims_cm['z'] - half_y, half_z = detector_y / 2.0, detector_z / 2.0 - corners_centered = np.array([ - [-half_y, -half_z], [+half_y, -half_z], [-half_y, +half_z], [+half_y, +half_z] - ], dtype=np.float32) - - for side_idx in range(2): - for plane_idx in range(3): - # Get wire parameters - angle, spacing, offset, n_wires, max_idx_abs = get_single_plane_wire_params( - detector_config, side_idx, plane_idx, dims_cm - ) - - # Calculate min_idx_abs - cos_theta = np.cos(angle) - sin_theta = np.sin(angle) - r_values = corners_centered[:, 0] * sin_theta + corners_centered[:, 1] * cos_theta - r_min = np.min(r_values) - idx_min_rel = np.floor(r_min / spacing - 1e-9).astype(np.int32) - min_idx_abs = idx_min_rel + offset - - # Store values - num_wires_all[side_idx, plane_idx] = n_wires - max_wire_indices_abs_all[side_idx, plane_idx] = max_idx_abs - min_wire_indices_abs_all[side_idx, plane_idx] = min_idx_abs - index_offsets_all[side_idx, plane_idx] = offset - wire_spacings_all[side_idx, plane_idx] = spacing - angles_all[side_idx, plane_idx] = angle - - # Convert all arrays to JAX arrays for compatibility with JIT - return (jnp.array(angles_all, dtype=jnp.float32), - jnp.array(wire_spacings_all, dtype=jnp.float32), - jnp.array(index_offsets_all, dtype=jnp.int32), - jnp.array(num_wires_all, dtype=jnp.int32), - jnp.array(max_wire_indices_abs_all, dtype=jnp.int32), - jnp.array(min_wire_indices_abs_all, dtype=jnp.int32)) - - -def print_detector_summary(detector_config: Dict[str, Any]) -> None: - """ - Print a summary of the detector configuration. - - Parameters - ---------- - detector_config : dict - Detector configuration dictionary with pre-calculated parameters. - """ - print("Detector Configuration Summary") - print("==============================") - - # Basic detector properties - print(f"Detector name: {detector_config['detector']['name']}") - dimensions = detector_config['dims_cm'] - print(f"Dimensions: {dimensions['x']} × {dimensions['y']} × {dimensions['z']} cm³") - - # Wire planes information - print("\nWire Plane Configuration:") - print("------------------------") - for side in detector_config['wire_planes']['sides']: - side_id = side['side_id'] - print(f"Side {side_id}: {side['description']}") - - for plane in side['planes']: - plane_id = plane['plane_id'] - plane_type = plane['type'] - print(f" Plane {plane_id} ({plane_type}):") - print(f" Angle: {plane['angle']} degrees") - print(f" Wire spacing: {plane['wire_spacing']} cm") - print(f" Bias voltage: {plane['bias_voltage']} V") - - # Medium properties - print(f"\nElectric field strength: {detector_config['electric_field']['field_strength']} V/cm") - print(f"Medium: {detector_config['medium']['type']} at {detector_config['medium']['temperature']} K") - - # Derived simulation parameters - print("\nDerived Parameters:") - print("------------------") - print(f"Number of time steps: {detector_config['num_time_steps']}") - print(f"Time step size: {detector_config['time_step_size_us']:.6f} μs") - print(f"Maximum drift time: {detector_config['max_drift_time_us']:.2f} μs") - print(f"Drift velocity: {detector_config['drift_velocity_cm_us']:.2f} cm/μs") - print(f"Electron lifetime: {detector_config['electron_lifetime_ms']:.2f} ms") - print(f"Longitudinal diffusion: {detector_config['longitudinal_diffusion_cm2_s']:.6f} cm²/s") - print(f"Transverse diffusion: {detector_config['transverse_diffusion_cm2_s']:.6f} cm²/s") - print(f"\nDiffusion Sigmas (at max drift):") - print(f" Transverse: {detector_config['max_sigma_trans_cm']:.3f} cm ({detector_config['max_sigma_trans_unitless']:.3f} unitless)") - print(f" Longitudinal: {detector_config['max_sigma_long_us']:.3f} μs ({detector_config['max_sigma_long_unitless']:.3f} unitless)") - - -if __name__ == "__main__": - # Path to your detector configuration file - config_path = "config/cubic_wireplane_config.yaml" - - # Generate the detector dictionary - detector = generate_detector(config_path) - - if detector: - print_detector_summary(detector) - else: - print("Failed to load detector configuration.") \ No newline at end of file diff --git a/closure/archive/gradient_test/gradient_test/tools/kernels.py b/closure/archive/gradient_test/gradient_test/tools/kernels.py deleted file mode 100644 index 4091819..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/kernels.py +++ /dev/null @@ -1,487 +0,0 @@ -""" -Response Kernel Module - -This module handles loading, creating, and applying wire response kernels with diffusion. -Uses pre-computed diffusion kernel arrays for efficient runtime interpolation. - -Contents: -1. Kernel Loading - Load NPZ kernel files -2. Gaussian Convolution - Create diffusion kernels at different s levels -3. Runtime Interpolation - JIT-compiled batch interpolation -4. High-Level API - load_response_kernels(), apply_diffusion_response() -""" - -import jax -import jax.numpy as jnp -from jax import jit, vmap -from functools import partial -import numpy as np - - -# ============================================================================ -# KERNEL LOADING -# ============================================================================ - -def load_kernel(filename): - """ - Load kernel from npz file (stored in actual values, not log scale). - - Parameters - ---------- - filename : str - Path to kernel npz file - - Returns - ------- - kernel : np.ndarray - Kernel array in actual current values - kernel_x_coords : np.ndarray - Wire coordinates - kernel_y_coords : np.ndarray - Time coordinates - plane : str - Plane name - dx : float - Wire spacing - dy : float - Time spacing - """ - data = np.load(filename, allow_pickle=True) - - # Kernel is now stored in actual values, not log scale - kernel = data['kernel'] - - kernel_x_coords = data['kernel_x_coords'] - kernel_y_coords = data['kernel_y_coords'] - plane = str(data['plane']) - - # Get spacing from coordinates - dx = kernel_x_coords[1] - kernel_x_coords[0] if len(kernel_x_coords) > 1 else 0.1 - dy = kernel_y_coords[1] - kernel_y_coords[0] if len(kernel_y_coords) > 1 else 0.5 - - return kernel, kernel_x_coords, kernel_y_coords, plane, dx, dy - - -def calculate_wire_count(kernel_width, wire_spacing=0.1): - """ - Calculate how many wire positions we can represent given kernel width. - - For wire_spacing = 0.1, we have 10 bins per unit wire spacing. - So if kernel_width = 127, we have (127-1)/10 = 12.6, so floor(12.6) = 12 wires total. - - Parameters - ---------- - kernel_width : int - Width of kernel in bins - wire_spacing : float - Wire spacing - - Returns - ------- - num_wires : int - Number of representable wires - """ - # Number of bins per wire unit - bins_per_wire = int(1.0 / wire_spacing) # 10 - - # Total wire range (symmetric around center) - wire_range = (kernel_width - 1) / bins_per_wire - num_wires = int(wire_range) # Use floor, not +1 - - return num_wires - - -# ============================================================================ -# GAUSSIAN CONVOLUTION (for creating diffusion levels) -# ============================================================================ - -def create_gaussian_kernel(shape, sigma_trans, sigma_long, dx, dy): - """ - Create a 2D Gaussian kernel with given sigmas and grid spacing. - - Parameters - ---------- - shape : tuple - (ny, nx) kernel shape - sigma_trans : float - Sigma in transverse direction (wire/spatial, unitless) - sigma_long : float - Sigma in longitudinal direction (time/temporal, unitless) - dx : float - Wire grid spacing - dy : float - Time grid spacing - - Returns - ------- - gaussian : np.ndarray - Normalized Gaussian kernel - """ - ny, nx = shape - - # Create coordinate grids centered at 0 - x = np.arange(nx) - nx // 2 - y = np.arange(ny) - ny // 2 - X, Y = np.meshgrid(x * dx, y * dy) - - # Handle small sigma values - eps = 1e-6 - sigma_trans = max(sigma_trans, eps) - sigma_long = max(sigma_long, eps) - - # Create Gaussian - gaussian = np.exp(-(X**2 / (2 * sigma_trans**2) + Y**2 / (2 * sigma_long**2))) - - # Normalize - gaussian = gaussian / np.sum(gaussian) - - return gaussian - - -def convolve_with_gaussian(kernel, sigma_trans, sigma_long, dx, dy): - """ - Convolve kernel with Gaussian using JAX. - - Parameters - ---------- - kernel : np.ndarray - Input kernel - sigma_trans : float - Sigma in transverse direction (wire/spatial) - sigma_long : float - Sigma in longitudinal direction (time/temporal) - dx : float - Wire grid spacing - dy : float - Time grid spacing - - Returns - ------- - convolved : np.ndarray - Convolved kernel - gaussian : np.ndarray - Gaussian kernel used - """ - # Create Gaussian kernel with same shape as input - gaussian = create_gaussian_kernel(kernel.shape, sigma_trans, sigma_long, dx, dy) - - # Convert to JAX arrays - kernel_jax = jnp.array(kernel) - gaussian_jax = jnp.array(gaussian) - - # Perform convolution with 'same' mode to maintain shape - convolved = jax.scipy.signal.convolve2d(kernel_jax, gaussian_jax, mode='same') - - return np.array(convolved), gaussian - - -def create_diffusion_kernel_array(planes=['U', 'V', 'Y'], num_s=16, kernel_dir='tools/responses', - wire_spacing=0.1, time_spacing=0.5, - max_sigma_trans_unitless=None, max_sigma_long_unitless=None): - """ - Create the diffusion kernel array DKernel for each plane. - DKernel[0] is the original kernel (s=0, no convolution) - DKernel[1:] are progressively more diffused kernels - - Parameters - ---------- - planes : list - List of planes to process - num_s : int - Number of s values (diffusion levels) - kernel_dir : str - Directory containing kernel files - wire_spacing : float - Wire spacing in cm - time_spacing : float - Time spacing in us - max_sigma_trans_unitless : float, optional - Maximum transverse diffusion sigma in unitless grid coordinates - max_sigma_long_unitless : float, optional - Maximum longitudinal diffusion sigma in unitless grid coordinates - - Returns - ------- - DKernels : dict - Dictionary mapping plane to (DKernel, linear_s, kernel_shape, x_coords, y_coords) - """ - # Create linear mapping from 0 to 1 - linear_s = jnp.linspace(0, 1, num_s) - - DKernels = {} - - for plane in planes: - try: - # Load original kernel - filename = f'{kernel_dir}/{plane}_plane_kernel.npz' - kernel, x_coords, y_coords, loaded_plane, dx, dy = load_kernel(filename) - - # Initialize DKernel array - kernel_shape = kernel.shape - DKernel = jnp.zeros((num_s, *kernel_shape)) - - # First entry is original kernel (s=0) - DKernel = DKernel.at[0].set(kernel) - - # Create progressively diffused kernels - for i in range(1, num_s): - s = linear_s[i] - - # Calculate sigmas based on physics: sigma = sigma_max * sqrt(s) - # Since sigma ~ sqrt(drift_time) and s ~ drift_time, then sigma(s) = sigma_max * sqrt(s) - # These are in UNITLESS grid coordinates (not physical units) - if max_sigma_trans_unitless is not None and max_sigma_long_unitless is not None: - sigma_trans = max_sigma_trans_unitless * np.sqrt(s) # unitless - sigma_long = max_sigma_long_unitless * np.sqrt(s) # unitless - else: - # Fallback to old hardcoded values if not provided - sigma_trans = 0.7 * s + 1e-3 - sigma_long = 1.0 * s + 1e-3 - - # Convolve with Gaussian - convolved, _ = convolve_with_gaussian(kernel, sigma_trans, sigma_long, dx, dy) - DKernel = DKernel.at[i].set(convolved) - - DKernels[plane] = (DKernel, linear_s, kernel_shape, x_coords, y_coords) - - except FileNotFoundError: - print(f"Warning: Could not find kernel file for {plane} plane") - continue - - return DKernels - - -# ============================================================================ -# RUNTIME INTERPOLATION (JIT-compiled) -# ============================================================================ - -@partial(jit, static_argnums=(4, 5, 6, 7)) # wire_stride, wire_spacing, time_spacing, num_wires are static -def interpolate_diffusion_kernel(DKernel, s_observed, w_offset, t_offset, - wire_stride, wire_spacing, time_spacing, num_wires): - """ - Interpolate the diffusion kernel at given s, w, t offsets. - - This is the core runtime function for efficient kernel interpolation. - - Parameters - ---------- - DKernel : jnp.ndarray - Array of shape (num_s, kernel_height, kernel_width) - s_observed : float - Diffusion parameter in [0, 1] - w_offset : float - Wire offset in [0, 1.0) - wire offset in units of wire_spacing - t_offset : float - Time offset in [0, 0.5) - time offset in units of time_spacing - wire_stride : int - Static wire stride (10 for 0.1 spacing to 1.0 spacing) - wire_spacing : float - Static wire spacing (0.1) - time_spacing : float - Static time spacing (0.5) - num_wires : int - Static number of wire positions expected - - Returns - ------- - interpolated_values : jnp.ndarray - Interpolated kernel values with shape (num_wires, kernel_height-1) - """ - num_s, kernel_height, kernel_width = DKernel.shape - - # 1. S interpolation - simple since we have linear points - s_continuous = s_observed * (num_s - 1) # Map to [0, num_s-1] - s_idx = jnp.floor(s_continuous).astype(int) - s_idx = jnp.clip(s_idx, 0, num_s - 2) # Ensure we don't go out of bounds - s_alpha = s_continuous - s_idx - - # 2. Wire interpolation setup - center_w = kernel_width // 2 - bins_per_wire = int(1.0 / wire_spacing) # 10 - - # Convert w_offset to bin offset - w_bin_offset = w_offset * bins_per_wire - w_base_bin = jnp.floor(w_bin_offset).astype(int) - w_alpha = w_bin_offset - w_base_bin - - # Generate wire bin indices for each output wire position - # For num_wires=12, we want: -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 (12 total) - if num_wires % 2 == 0: - # Even number of wires - half_wires = num_wires // 2 - wire_positions = jnp.arange(-half_wires, half_wires) # -6 to 5 for num_wires=12 - else: - # Odd number of wires - half_wires = num_wires // 2 - wire_positions = jnp.arange(-half_wires, half_wires + 1) # -6 to 6 for num_wires=13 - - wire_base_positions = wire_positions * bins_per_wire + center_w - - # Initialize output array - output_values = jnp.zeros((num_wires, kernel_height - 1)) - - # Process each wire position - for wire_idx in range(num_wires): - wire_bin_left = wire_base_positions[wire_idx] + w_base_bin - wire_bin_right = wire_bin_left + 1 - wire_bin_left = jnp.clip(wire_bin_left, 0, kernel_width - 1) - wire_bin_right = jnp.clip(wire_bin_right, 0, kernel_width - 1) - - values_s_n_left = DKernel[s_idx, :, wire_bin_left] - values_s_n_plus_1_left = DKernel[s_idx + 1, :, wire_bin_left] - values_s_n_right = DKernel[s_idx, :, wire_bin_right] - values_s_n_plus_1_right = DKernel[s_idx + 1, :, wire_bin_right] - - values_s_interp_left = (1 - s_alpha) * values_s_n_left + s_alpha * values_s_n_plus_1_left - values_s_interp_right = (1 - s_alpha) * values_s_n_right + s_alpha * values_s_n_plus_1_right - values_w_interp = (1 - w_alpha) * values_s_interp_left + w_alpha * values_s_interp_right - - t_alpha = t_offset / time_spacing - interpolated_values = (1 - t_alpha) * values_w_interp[:-1] + t_alpha * values_w_interp[1:] - output_values = output_values.at[wire_idx, :].set(interpolated_values) - - return output_values - - -@partial(jit, static_argnums=(4, 5, 6, 7)) # wire_stride, wire_spacing, time_spacing, num_wires are static -def interpolate_diffusion_kernel_batch(DKernel, s_observed_batch, w_offset_batch, t_offset_batch, - wire_stride, wire_spacing, time_spacing, num_wires): - """ - Batch interpolation using vmap for multiple sets of parameters. - - This is the key function for efficient runtime processing of many segments. - - Parameters - ---------- - DKernel : jnp.ndarray - Array of shape (num_s, kernel_height, kernel_width) - s_observed_batch : jnp.ndarray - Array of shape (N,) with s values - w_offset_batch : jnp.ndarray - Array of shape (N,) with w_offset values - t_offset_batch : jnp.ndarray - Array of shape (N,) with t_offset values - wire_stride : int - Static wire stride - wire_spacing : float - Static wire spacing - time_spacing : float - Static time spacing - num_wires : int - Static number of wires - - Returns - ------- - batch_results : jnp.ndarray - Batch results with shape (N, num_wires, kernel_height-1) - """ - # Vmap over the batch dimension (first axis) - vmapped_interpolate = vmap( - lambda s, w, t: interpolate_diffusion_kernel( - DKernel, s, w, t, wire_stride, wire_spacing, time_spacing, num_wires - ), - in_axes=(0, 0, 0), # Vmap over first axis of s, w, t - out_axes=0 # Output has batch dimension first - ) - - return vmapped_interpolate(s_observed_batch, w_offset_batch, t_offset_batch) - - -# ============================================================================ -# HIGH-LEVEL API -# ============================================================================ - -def load_response_kernels(response_path="tools/responses/", num_s=16, - wire_spacing=0.1, time_spacing=0.5, - max_sigma_trans_unitless=None, max_sigma_long_unitless=None): - """ - Load response kernels and create diffusion kernel arrays. - - Parameters - ---------- - response_path : str - Path to directory containing kernel NPZ files. - num_s : int - Number of diffusion levels to create. - wire_spacing : float - Wire spacing in cm. - time_spacing : float - Time spacing in microseconds. - max_sigma_trans_unitless : float, optional - Maximum transverse diffusion sigma in unitless grid coordinates. - max_sigma_long_unitless : float, optional - Maximum longitudinal diffusion sigma in unitless grid coordinates. - - Returns - ------- - dict - Dictionary mapping plane names to kernel data. - """ - planes = ['U', 'V', 'Y'] - - # Create diffusion kernel arrays - DKernels = create_diffusion_kernel_array( - planes=planes, - num_s=num_s, - kernel_dir=response_path, - wire_spacing=wire_spacing, - time_spacing=time_spacing, - max_sigma_trans_unitless=max_sigma_trans_unitless, - max_sigma_long_unitless=max_sigma_long_unitless - ) - - # Extract kernel info for each plane - response_kernels = {} - for plane in DKernels: - DKernel, linear_s, kernel_shape, x_coords, y_coords = DKernels[plane] - num_wires = calculate_wire_count(kernel_shape[1], wire_spacing) - kernel_height = kernel_shape[0] - 1 # Output height after interpolation - - response_kernels[plane] = { - 'DKernel': DKernel, - 'num_wires': num_wires, - 'kernel_height': kernel_height, - 'wire_spacing': wire_spacing, - 'time_spacing': time_spacing, - 'wire_stride': int(1.0 / wire_spacing) # 10 for 0.1 spacing - } - - return response_kernels - - -def apply_diffusion_response(DKernel, s_values, wire_offsets, time_offsets, - wire_stride, wire_spacing, time_spacing, num_wires): - """ - Apply diffusion response using pre-computed kernels. - - Parameters - ---------- - DKernel : jnp.ndarray - Diffusion kernel array for the plane. - s_values : jnp.ndarray - Array of s values (diffusion parameters) for each segment. - wire_offsets : jnp.ndarray - Array of wire offsets in [0, 1) for each segment. - time_offsets : jnp.ndarray - Array of time offsets in [0, 0.5) for each segment. - wire_stride : int - Wire stride (static parameter). - wire_spacing : float - Wire spacing (static parameter). - time_spacing : float - Time spacing (static parameter). - num_wires : int - Number of wires in kernel (static parameter). - - Returns - ------- - jnp.ndarray - Response contributions with shape (N, num_wires, kernel_height). - """ - # Apply batch interpolation - contributions = interpolate_diffusion_kernel_batch( - DKernel, s_values, wire_offsets, time_offsets, - wire_stride, wire_spacing, time_spacing, num_wires - ) - - return contributions diff --git a/closure/archive/gradient_test/gradient_test/tools/loader.py b/closure/archive/gradient_test/gradient_test/tools/loader.py deleted file mode 100644 index 471a1a0..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/loader.py +++ /dev/null @@ -1,381 +0,0 @@ -import h5py -import jax.numpy as jnp -import numpy as np -from typing import Dict, List, Tuple, Any, Optional -import json - - -class ParticleStepExtractor: - """ - Simplified extractor for particle steps from HDF5 files. - - This class extracts particle step data from an HDF5 file and converts it to JAX arrays. - It handles the standard structure of particle physics HDF5 files with steps, particles, - and associations between them. - - Attributes - ---------- - file_path : str - Path to the HDF5 file. - file : h5py.File or None - The opened HDF5 file or None if not opened. - verbose : bool - Whether to print verbose information. - pstep_path : str or None - The actual path to the particle step dataset. - particle_path : str or None - The actual path to the particle dataset. - association_path : str or None - The actual path to the association dataset. - """ - - def __init__(self, file_path: str, verbose: bool = False): - """ - Initialize the extractor with the path to an HDF5 file. - - Parameters - ---------- - file_path : str - Path to the HDF5 file. - verbose : bool, optional - Whether to print verbose information, by default False. - """ - self.file_path = file_path - self.file = None - self.verbose = verbose - - # Common paths in particle physics HDF5 files - self.pstep_paths = ['pstep/lar_vol'] - self.particle_paths = ['particle/geant4'] - self.association_paths = [ - 'ass/particle_pstep_lar_vol' - ] - - # The actual paths found in this file - self.pstep_path = None - self.particle_path = None - self.association_path = None - - # Open the file and find paths - self.open_file() - self._find_dataset_paths() - - if verbose: - print(f"Loaded file: {file_path}") - print(f"Step path: {self.pstep_path}") - print(f"Particle path: {self.particle_path}") - print(f"Association path: {self.association_path}") - - def _find_dataset_paths(self): - """ - Find the actual dataset paths in the file. - - Checks for the existence of common paths and sets the actual paths - found in the file. - """ - # Find step path - for path in self.pstep_paths: - if path in self.file: - self.pstep_path = path - break - - # Find particle path - for path in self.particle_paths: - if path in self.file: - self.particle_path = path - break - - # Find association path - for path in self.association_paths: - if path in self.file: - self.association_path = path - break - - def open_file(self): - """ - Open the HDF5 file. - - Opens the file in read mode and stores the file object. - """ - self.file = h5py.File(self.file_path, 'r') - - def close(self): - """ - Close the HDF5 file. - - Closes the file if it is open and sets the file object to None. - """ - if self.file is not None: - self.file.close() - self.file = None - - def __enter__(self): - """ - Context manager entry method. - - Returns - ------- - ParticleStepExtractor - The extractor object. - """ - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - """ - Context manager exit method. - - Closes the file when exiting the context. - - Parameters - ---------- - exc_type : type - Exception type if an exception was raised. - exc_val : Exception - Exception value if an exception was raised. - exc_tb : traceback - Exception traceback if an exception was raised. - """ - self.close() - - def _get_numeric_fields(self, dataset, event_idx=0): - """ - Extract numeric fields from a dataset for a specific event. - Skips string fields that JAX doesn't support. - - Parameters - ---------- - dataset : str - Path to the dataset in the HDF5 file. - event_idx : int, optional - Index of the event to extract, by default 0. - - Returns - ------- - dict - Dictionary mapping field names to JAX arrays. - """ - if dataset not in self.file: - if self.verbose: - print(f"Dataset {dataset} not found") - return {} - - try: - data = self.file[dataset][event_idx] - except Exception as e: - if self.verbose: - print(f"Error accessing {dataset}[{event_idx}]: {e}") - return {} - - result = {} - - # Check if data has fields (structured array) - if hasattr(data, 'dtype') and data.dtype.names: - for field in data.dtype.names: - try: - field_data = data[field] - - # Skip string fields - JAX doesn't support these - if isinstance(field_data, (bytes, np.bytes_)) or ( - isinstance(field_data, np.ndarray) and field_data.dtype.kind in ('S', 'U', 'O')): - if self.verbose: - print(f"Skipping string field: {field}") - continue - - # Convert to JAX array for numeric data - result[field] = jnp.array(field_data) - except Exception as e: - if self.verbose: - print(f"Error extracting field {field}: {e}") - - return result - - def get_step_to_particle_mapping(self, event_idx=0): - """ - Create a mapping from each step to its parent particle. - - Parameters - ---------- - event_idx : int, optional - Index of the event to extract, by default 0. - - Returns - ------- - jnp.ndarray or None - JAX array where index[i] gives the particle index for step i, - or None if the mapping could not be created. - """ - if not self.association_path or self.association_path not in self.file: - if self.verbose: - print(f"Association dataset {self.association_path} not found") - return None - - try: - mapping_data = self.file[self.association_path][event_idx] - - # Check how the mapping is stored - if hasattr(mapping_data, 'dtype') and mapping_data.dtype.names and 'start' in mapping_data.dtype.names: - # Format with start/end indices - starts = mapping_data['start'] - ends = mapping_data['end'] - - # Create a mapping from step index to particle index - num_steps = np.max(ends) if len(ends) > 0 else 0 - step_to_particle = np.zeros(num_steps, dtype=np.int32) - - for i in range(len(starts)): - start_idx = starts[i] - end_idx = ends[i] - step_to_particle[start_idx:end_idx] = i - - return jnp.array(step_to_particle) - else: - # Other format - this would need to be adapted based on the specific file structure - if self.verbose: - print("Unsupported association format") - return None - - except Exception as e: - if self.verbose: - print(f"Error getting step-to-particle mapping: {e}") - return None - - def extract_step_arrays(self, event_idx=0): - """ - Extract step data as JAX arrays. - For each property, returns an array of shape (N, ...) where N is the number of steps. - - Parameters - ---------- - event_idx : int, optional - Index of the event to extract, by default 0. - - Returns - ------- - dict - Dictionary mapping property names to JAX arrays. - """ - # Get step data - step_data = self._get_numeric_fields(self.pstep_path, event_idx) - if not step_data: - if self.verbose: - print("No step data found") - return {} - - # Get particle data - particle_data = self._get_numeric_fields(self.particle_path, event_idx) - if not particle_data: - if self.verbose: - print("No particle data found") - return step_data # Return just step data if no particle data - - # Get mapping from steps to particles - step_to_particle = self.get_step_to_particle_mapping(event_idx) - if step_to_particle is None: - if self.verbose: - print("No step-to-particle mapping found") - return step_data # Return just step data if no mapping - - # Initialize result with step properties - result = dict(step_data) - - # For each particle property, add it to each step - for key, value in particle_data.items(): - # Skip if already exists in step data - if key in result: - continue - - try: - # Get the property for each step's particle - result[f"particle_{key}"] = value[step_to_particle] - except Exception as e: - if self.verbose: - print(f"Error mapping particle property {key} to steps: {e}") - - # Add some convenience properties - if 'x' in result and 'y' in result and 'z' in result: - result['position'] = jnp.stack([result['x'], result['y'], result['z']], axis=1) - - return result - - -def load_particle_step_data(file_path, event_idx=0, verbose=False): - """ - Convenience function to extract particle step data from an HDF5 file. - - This function creates a ParticleStepExtractor, extracts the data, - and closes the file, all in one call. - - Parameters - ---------- - file_path : str - Path to the HDF5 file. - event_idx : int, optional - Index of the event to extract, by default 0. - verbose : bool, optional - Whether to print verbose information, by default False. - - Returns - ------- - dict - Dictionary mapping property names to JAX arrays. - """ - with ParticleStepExtractor(file_path, verbose=verbose) as extractor: - return extractor.extract_step_arrays(event_idx) - - -def main(): - """ - Example usage of the particle step extractor. - - This function demonstrates how to use the particle step extractor - from the command line with various options. - """ - import argparse - import sys - - parser = argparse.ArgumentParser(description='Extract particle step data from HDF5 files') - parser.add_argument('file_path', help='Path to the HDF5 file') - parser.add_argument('--event', '-e', type=int, default=0, help='Event index (default: 0)') - parser.add_argument('--verbose', '-v', action='store_true', help='Print verbose information') - parser.add_argument('--output', '-o', help='Save data to JSON file (will convert JAX arrays to lists)') - - args = parser.parse_args() - - # Extract step data - step_data = load_particle_step_data(args.file_path, args.event, args.verbose) - - # Print summary of the extracted data - print("\nExtracted step arrays:") - for key, value in step_data.items(): - if hasattr(value, 'shape'): - print(f" {key}: shape={value.shape}, dtype={value.dtype}") - else: - print(f" {key}: {type(value)}") - - for pdg in particle_types: - # Get steps for this particle type - mask = step_data['particle_pdg'] == pdg - energy = jnp.sum(step_data['de'][mask]) - print(f" PDG code {pdg}: total energy = {energy}") - - # Save to file if requested - if args.output: - try: - # Convert JAX arrays to lists for JSON serialization - json_data = {} - for key, value in step_data.items(): - if hasattr(value, 'shape'): - json_data[key] = value.tolist() - else: - json_data[key] = value - - with open(args.output, 'w') as f: - json.dump(json_data, f) - - print(f"\nData saved to {args.output}") - except Exception as e: - print(f"Error saving data: {e}", file=sys.stderr) - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/closure/archive/gradient_test/gradient_test/tools/recombination.py b/closure/archive/gradient_test/gradient_test/tools/recombination.py deleted file mode 100644 index a3149b2..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/recombination.py +++ /dev/null @@ -1,218 +0,0 @@ -""" -Charge recombination calculations for LArTPC simulation. - -This module implements the Box model for calculating charge recombination -in liquid argon. The recombination factor determines how much of the -ionization charge is collected versus recombined with ions. - -Modified for gradient testing - accepts PhysicsParams for differentiation. -""" - -import jax -import jax.numpy as jnp -from jax import jit -from typing import Dict, Any, Optional, Union - -# Import PhysicsParams from gradient_test package -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -from physics_params import PhysicsParams - - -def calculate_box_model_charge(de, dx, params): - """ - Calculate deposited charge using the standard Box model. - - This function is NOT jit-compiled to allow gradient computation - through the physics parameters. - - Parameters - ---------- - de : jnp.ndarray - Array of energy depositions in MeV. - dx : jnp.ndarray - Array of step lengths in cm. - params : tuple or PhysicsParams - Either a tuple of (field_strength, density, w_value, A, B) or - a PhysicsParams object. - - Returns - ------- - jnp.ndarray - Array of deposited charge (electrons) for each step. - """ - # Handle both tuple and PhysicsParams inputs - if isinstance(params, PhysicsParams): - field_strength = params.field_strength - density = params.density - w_value = params.w_value - A = params.recomb_A - B = params.recomb_B - else: - field_strength, density, w_value, A, B = params - - # Convert w_value from eV to MeV - w_value_mev = w_value * 1e-6 - - # Calculate dE/dx (MeV/cm) - de_dx = de / jnp.maximum(dx, 1e-10) - - # Calculate recombination factor using Box model - denominator = 1.0 + (B * field_strength) / (density * jnp.maximum(de_dx, 1e-10)) - recombination_factor = A / denominator - recombination_factor = jnp.clip(recombination_factor, 0.0, 1.0) - - # Calculate initial charge and apply recombination - initial_charge = de / w_value_mev - collected_charge = initial_charge * (1.0 - recombination_factor) - - return collected_charge - - -def calculate_box_model_charge_with_physics_params( - de: jnp.ndarray, - dx: jnp.ndarray, - physics_params: PhysicsParams -) -> jnp.ndarray: - """ - Calculate deposited charge using PhysicsParams. - - This is the gradient-friendly version that takes PhysicsParams directly. - - Parameters - ---------- - de : jnp.ndarray - Array of energy depositions in MeV. - dx : jnp.ndarray - Array of step lengths in cm. - physics_params : PhysicsParams - Physics parameters for recombination. - - Returns - ------- - jnp.ndarray - Array of deposited charge (electrons) for each step. - """ - # Extract parameters - field_strength = physics_params.field_strength - density = physics_params.density - w_value = physics_params.w_value - A = physics_params.recomb_A - B = physics_params.recomb_B - - # Convert w_value from eV to MeV - w_value_mev = w_value * 1e-6 - - # Calculate dE/dx (MeV/cm) - de_dx = de / jnp.maximum(dx, 1e-10) - - # Calculate recombination factor using Box model - denominator = 1.0 + (B * field_strength) / (density * jnp.maximum(de_dx, 1e-10)) - recombination_factor = A / denominator - recombination_factor = jnp.clip(recombination_factor, 0.0, 1.0) - - # Calculate initial charge and apply recombination - initial_charge = de / w_value_mev - collected_charge = initial_charge * (1.0 - recombination_factor) - - return collected_charge - - -def extract_params_for_box_model(detector_config): - """ - Extract recombination parameters from the detector configuration. - - Parameters - ---------- - detector_config : dict - Dictionary with detector configuration parameters. - - Returns - ------- - tuple - Tuple of parameters (field_strength, density, w_value, A, B). - """ - field_strength = detector_config['electric_field']['field_strength'] - density = detector_config['medium']['properties']['density'] - w_value = detector_config['medium']['properties']['ionization_energy'] - recomb_params = detector_config['simulation']['charge_recombination']['recomb_parameters'] - A = recomb_params['A'] - B = recomb_params['B'] - - return field_strength, density, w_value, A, B - - -def recombine_steps( - step_data: Dict, - detector_config: Dict, - physics_params: Optional[PhysicsParams] = None -) -> jnp.ndarray: - """ - Process particle steps to calculate deposited charge. - - Parameters - ---------- - step_data : dict - Dictionary containing arrays from the particle step data. - detector_config : dict - Dictionary with detector configuration parameters. - physics_params : PhysicsParams, optional - If provided, use these parameters instead of detector_config. - This allows gradient computation through the parameters. - - Returns - ------- - jnp.ndarray - Array of deposited charge for each step. - """ - # Extract de and dx arrays from step_data - de = step_data['de'] - dx = step_data['dx'] - - if physics_params is not None: - # Use PhysicsParams for gradient-friendly computation - return calculate_box_model_charge_with_physics_params(de, dx, physics_params) - else: - # Use detector_config (original behavior) - params = extract_params_for_box_model(detector_config) - return calculate_box_model_charge(de, dx, params) - - -def recombine_steps_with_physics_params( - step_data: Dict, - physics_params: PhysicsParams -) -> jnp.ndarray: - """ - Convenience function for gradient testing. - - Parameters - ---------- - step_data : dict - Dictionary containing 'de' and 'dx' arrays. - physics_params : PhysicsParams - Physics parameters. - - Returns - ------- - jnp.ndarray - Array of deposited charge for each step. - """ - de = step_data['de'] - dx = step_data['dx'] - return calculate_box_model_charge_with_physics_params(de, dx, physics_params) - - -if __name__ == "__main__": - from geometry import generate_detector - from loader import load_particle_step_data - - config_path = "config/cubic_wireplane_config.yaml" - detector = generate_detector(config_path) - - data_path = "mpvmpr.h5" - event_idx = 0 - - step_data = load_particle_step_data(data_path, event_idx) - - processed_charge = recombine_steps(step_data, detector) diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/U_plane_kernel.npz b/closure/archive/gradient_test/gradient_test/tools/responses/U_plane_kernel.npz deleted file mode 100644 index d5ce7c1..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/U_plane_kernel.npz and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/V_plane_kernel.npz b/closure/archive/gradient_test/gradient_test/tools/responses/V_plane_kernel.npz deleted file mode 100644 index 2953fca..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/V_plane_kernel.npz and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/Y_plane_kernel.npz b/closure/archive/gradient_test/gradient_test/tools/responses/Y_plane_kernel.npz deleted file mode 100644 index 82ea704..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/Y_plane_kernel.npz and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/__init__.py b/closure/archive/gradient_test/gradient_test/tools/responses/__init__.py deleted file mode 100644 index 55eefc5..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/responses/__init__.py +++ /dev/null @@ -1,47 +0,0 @@ -""" -Wire Response Processing Module - -This module provides tools for extracting wire responses from images, -creating diffusion kernels, and performing efficient runtime interpolation. -""" - -# Core runtime functions - what most users need -# These are now in the main kernels module -from tools.kernels import ( - create_diffusion_kernel_array, - interpolate_diffusion_kernel_batch, - calculate_wire_count -) - -# Extraction function - only needed for initial setup -from .response_extraction import process_single_plane - -# Visualization functions -from .response_visualization_utils import ( - visualize_kernel, - visualize_interpolation_steps, - create_parameter_sweep_gif -) - -# Version -__version__ = '1.0.0' - -# Note: The extract_and_create_kernels function has been removed. -# Use extract_responses_from_images.py for one-time extraction, -# then use create_diffusion_kernel_array to load and process. - - -__all__ = [ - # Core runtime functions - 'create_diffusion_kernel_array', - 'interpolate_diffusion_kernel_batch', - 'calculate_wire_count', - - # Extraction (one-time use) - 'process_single_plane', - - # Visualization - 'visualize_kernel', - 'visualize_interpolation_steps', - 'create_parameter_sweep_gif' -] \ No newline at end of file diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/example_response_usage.py b/closure/archive/gradient_test/gradient_test/tools/responses/example_response_usage.py deleted file mode 100644 index aaac8e6..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/responses/example_response_usage.py +++ /dev/null @@ -1,125 +0,0 @@ -""" -Example usage of the diffusion kernel system. - -This demonstrates how to: -1. Load pre-extracted kernel NPZ files -2. Create diffusion kernel arrays -3. Perform runtime interpolation - -NOTE: This assumes you have already run extract_responses_from_images.py -to create the kernel NPZ files from the response images. -""" - -import os -import numpy as np -import matplotlib.pyplot as plt -# Handle both module and script execution -if __name__ == "__main__": - import sys - sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - from tools_old.responses import ( - create_diffusion_kernel_array, - interpolate_diffusion_kernel_batch, - visualize_kernel, - calculate_wire_count - ) -else: - from . import ( - create_diffusion_kernel_array, - interpolate_diffusion_kernel_batch, - visualize_kernel, - calculate_wire_count - ) -import jax -import jax.numpy as jnp - - -def main(): - # Parameters - planes = ['U', 'V', 'Y'] - time_bin_size = 0.5 - wire_spacing = 0.1 - wire_stride = 10 - num_s = 16 - - # Step 1: Check that kernel files exist - print("="*60) - print("STEP 1: Checking for kernel NPZ files") - print("="*60) - - kernel_files_exist = True - for plane in planes: - kernel_file = f'{plane}_plane_kernel.npz' - if os.path.exists(kernel_file): - print(f" ✓ Found {kernel_file}") - else: - print(f" ✗ Missing {kernel_file}") - kernel_files_exist = False - - if not kernel_files_exist: - print("\nERROR: Kernel files not found!") - print("Please run 'python extract_responses_from_images.py' first to create them.") - return - - # Step 2: Create diffusion kernel arrays from loaded kernels - print("\n" + "="*60) - print("STEP 2: Creating diffusion kernel arrays from NPZ files") - print("="*60) - - DKernels = create_diffusion_kernel_array( - planes=planes, - num_s=num_s, - kernel_dir='.', # Current directory since we're in tools/responses - wire_spacing=wire_spacing, - time_spacing=time_bin_size - ) - - # Step 4: Demonstrate runtime interpolation - print("\n" + "="*60) - print("STEP 4: Runtime interpolation example") - print("="*60) - - # Use first available plane - plane = list(DKernels.keys())[0] - DKernel, linear_s, kernel_shape, x_coords, y_coords = DKernels[plane] - num_wires = calculate_wire_count(kernel_shape[1], wire_spacing) - - print(f"\nUsing {plane} plane for interpolation example") - print(f"Number of wires: {num_wires}") - print(f"Output shape per segment: ({num_wires}, {kernel_shape[0]-1})") - - # Example: Interpolate for a batch of segments - batch_size = 10000 - - # Generate random parameters for demonstration - key = jax.random.PRNGKey(42) - key, subkey1 = jax.random.split(key) - s_batch = jax.random.uniform(subkey1, (batch_size,), minval=0.0, maxval=1.0) - - key, subkey2 = jax.random.split(key) - w_batch = jax.random.uniform(subkey2, (batch_size,), minval=0.0, maxval=0.99) - - key, subkey3 = jax.random.split(key) - t_batch = jax.random.uniform(subkey3, (batch_size,), minval=0.0, maxval=0.49) - - # Perform batch interpolation - print(f"\nInterpolating {batch_size:,} segments...") - start_time = time.time() - - results = interpolate_diffusion_kernel_batch( - DKernel, s_batch, w_batch, t_batch, - wire_stride, wire_spacing, time_bin_size, num_wires - ) - results.block_until_ready() - - end_time = time.time() - - print(f"Interpolation complete!") - print(f" Time: {(end_time - start_time)*1000:.1f} ms") - print(f" Output shape: {results.shape}") - print(f" Throughput: {batch_size/(end_time - start_time):.0f} segments/second") - - -if __name__ == "__main__": - import time - main() \ No newline at end of file diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/diffusion_sweep_Y.gif b/closure/archive/gradient_test/gradient_test/tools/responses/gifs/diffusion_sweep_Y.gif deleted file mode 100644 index 2a07e2e..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/diffusion_sweep_Y.gif and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/diffusion_sweep_detailed_Y.gif b/closure/archive/gradient_test/gradient_test/tools/responses/gifs/diffusion_sweep_detailed_Y.gif deleted file mode 100644 index 4dbf611..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/diffusion_sweep_detailed_Y.gif and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/time_offset_sweep_Y.gif b/closure/archive/gradient_test/gradient_test/tools/responses/gifs/time_offset_sweep_Y.gif deleted file mode 100644 index ade66fe..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/time_offset_sweep_Y.gif and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/time_offset_sweep_detailed_Y.gif b/closure/archive/gradient_test/gradient_test/tools/responses/gifs/time_offset_sweep_detailed_Y.gif deleted file mode 100644 index 2b6b191..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/time_offset_sweep_detailed_Y.gif and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/wire_offset_sweep_Y.gif b/closure/archive/gradient_test/gradient_test/tools/responses/gifs/wire_offset_sweep_Y.gif deleted file mode 100644 index 09a4d30..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/wire_offset_sweep_Y.gif and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/wire_offset_sweep_detailed_Y.gif b/closure/archive/gradient_test/gradient_test/tools/responses/gifs/wire_offset_sweep_detailed_Y.gif deleted file mode 100644 index 0c5aaf0..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/gifs/wire_offset_sweep_detailed_Y.gif and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/images/U_response_colorbar.png b/closure/archive/gradient_test/gradient_test/tools/responses/images/U_response_colorbar.png deleted file mode 100644 index 43f0084..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/images/U_response_colorbar.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/images/U_response_image.png b/closure/archive/gradient_test/gradient_test/tools/responses/images/U_response_image.png deleted file mode 100644 index df56bca..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/images/U_response_image.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/images/V_response_colorbar.png b/closure/archive/gradient_test/gradient_test/tools/responses/images/V_response_colorbar.png deleted file mode 100644 index fa61530..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/images/V_response_colorbar.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/images/V_response_image.png b/closure/archive/gradient_test/gradient_test/tools/responses/images/V_response_image.png deleted file mode 100644 index 181f24f..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/images/V_response_image.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/images/Y_response_colorbar.png b/closure/archive/gradient_test/gradient_test/tools/responses/images/Y_response_colorbar.png deleted file mode 100644 index 8c3e7f4..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/images/Y_response_colorbar.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/images/Y_response_image.png b/closure/archive/gradient_test/gradient_test/tools/responses/images/Y_response_image.png deleted file mode 100644 index 6bf72aa..0000000 Binary files a/closure/archive/gradient_test/gradient_test/tools/responses/images/Y_response_image.png and /dev/null differ diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/response_extraction.py b/closure/archive/gradient_test/gradient_test/tools/responses/response_extraction.py deleted file mode 100644 index a333965..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/responses/response_extraction.py +++ /dev/null @@ -1,547 +0,0 @@ -""" -Response Extraction from Images - -This module handles extraction of wire response data from colorbar and plot images, -including conversion between the paper's "Log 10" scale and actual current values. -""" - -import numpy as np -from scipy.spatial import KDTree -from scipy.interpolate import RegularGridInterpolator -from scipy.ndimage import gaussian_filter1d -from PIL import Image - - -# Define color scale ranges for each plane -PLANE_CONFIGS = { - 'U': { - 'value_range': (-3.16, 3.16), - 'tick_values': [3, 2, 1, 0, -1, -2, -3], - 'title': 'U Plane' - }, - 'V': { - 'value_range': (-3.16, 3.16), - 'tick_values': [3, 2, 1, 0, -1, -2, -3], - 'title': 'V Plane' - }, - 'Y': { - 'value_range': (-3.16, 4.16), - 'tick_values': [4, 3, 2, 1, 0, -1, -2, -3], - 'title': 'Y Plane' - } -} - - -def analyze_colorbar_for_plane(colorbar_path, plane='U', n_colors=20): - """ - Analyze colorbar and extract colors with exact tick positions for specific plane. - - Parameters - ---------- - colorbar_path : str - Path to colorbar image file - plane : str - Which plane ('U', 'V', or 'Y') - n_colors : int - Number of color levels to extract - - Returns - ------- - extracted_colors : np.ndarray - RGB colors, shape (n_colors, 3) - extracted_values : np.ndarray - Corresponding "Log 10" values, shape (n_colors,) - """ - # Load colorbar - colorbar_img = np.array(Image.open(colorbar_path).convert('RGB')) - height, width = colorbar_img.shape[:2] - - # Get value range for this plane - value_range = PLANE_CONFIGS[plane]['value_range'] - - # Extract colors evenly spaced along the colorbar - positions = np.linspace(0, height-1, n_colors) - center_x = width // 2 - - extracted_colors = [] - for pos in positions: - y_idx = int(pos) - region = colorbar_img[ - max(0, y_idx-1):min(height, y_idx+2), - max(0, center_x-2):min(width, center_x+3) - ] - mean_color = np.mean(region.reshape(-1, 3), axis=0) - extracted_colors.append(mean_color) - - extracted_colors = np.array(extracted_colors) - # Values go from top to bottom in "Log 10" scale - extracted_values = np.linspace(value_range[1], value_range[0], n_colors) - - return extracted_colors, extracted_values - - -def paper_log10_to_actual(log10_values): - """ - Convert from the paper's "Log 10" scale back to actual current values. - - The paper shows a symmetric log scale where: - - For "Log 10" > 0: i = 10^(value) / 10^5 - - For "Log 10" = 0: i = 0 - - For "Log 10" < 0: i = -10^(abs(value)) / 10^5 - - Parameters - ---------- - log10_values : np.ndarray - Values in paper's "Log 10" scale - - Returns - ------- - actual_values : np.ndarray - Actual current values (electrons per time bin) - """ - actual_values = np.zeros_like(log10_values) - - # Positive Log10 values - mask_pos = log10_values > 0 - actual_values[mask_pos] = 10**(log10_values[mask_pos]) / 10**5 - - # Zero - mask_zero = log10_values == 0 - actual_values[mask_zero] = 0 - - # Negative Log10 values - mask_neg = log10_values < 0 - actual_values[mask_neg] = -10**(-log10_values[mask_neg]) / 10**5 - - return actual_values - - -def extract_with_confidence_fixed_bins(plot_path, colorbar_colors, colorbar_values, - x_range=(-10.5, 10.5), y_range=(-60, 40), - time_bin_size=0.5, wire_spacing=0.1): - """ - Extract data from plot with confidence estimation and fixed bin sizes. - - Parameters - ---------- - plot_path : str - Path to plot image file - colorbar_colors : np.ndarray - RGB colors from colorbar, shape (n_colors, 3) - colorbar_values : np.ndarray - Corresponding values, shape (n_colors,) - x_range : tuple - (x_min, x_max) wire number range - y_range : tuple - (y_min, y_max) time range in microseconds - time_bin_size : float - Time bin size in microseconds - wire_spacing : float - Wire number spacing - - Returns - ------- - data_values : np.ndarray - Extracted values on fixed grid - confidence_map : np.ndarray - Confidence values on fixed grid - x_coords : np.ndarray - Wire coordinates - y_coords : np.ndarray - Time coordinates - """ - # Load plot image - plot_img = np.array(Image.open(plot_path).convert('RGB')) - plot_height, plot_width = plot_img.shape[:2] - - # Create coordinate grids at image resolution - x_coords_img = np.linspace(x_range[0], x_range[1], plot_width) - y_coords_img = np.linspace(y_range[1], y_range[0], plot_height) - - # Build color mapping - color_tree = KDTree(colorbar_colors) - - # Extract values at image resolution - data_values_img = np.zeros((plot_height, plot_width)) - confidence_map_img = np.zeros((plot_height, plot_width)) - - for i in range(plot_height): - for j in range(plot_width): - pixel = plot_img[i, j] - dist, idx = color_tree.query(pixel, k=1) - data_values_img[i, j] = colorbar_values[idx] - confidence_map_img[i, j] = np.exp(-dist / 50) - - # Create fixed coordinate grids - n_time_bins = int((y_range[1] - y_range[0]) / time_bin_size) + 1 - y_coords_fixed = np.linspace(y_range[0], y_range[1], n_time_bins) - - n_wire_bins = int((x_range[1] - x_range[0]) / wire_spacing) + 1 - x_coords_fixed = np.linspace(x_range[0], x_range[1], n_wire_bins) - - # Interpolate to fixed grid - interp_data = RegularGridInterpolator( - (y_coords_img[::-1], x_coords_img), # Flip y for ascending order - data_values_img[::-1, :], # Flip data accordingly - method='linear', - bounds_error=False, - fill_value=0 - ) - - interp_conf = RegularGridInterpolator( - (y_coords_img[::-1], x_coords_img), - confidence_map_img[::-1, :], - method='linear', - bounds_error=False, - fill_value=0 - ) - - # Create mesh grid for interpolation - Y_fixed, X_fixed = np.meshgrid(y_coords_fixed, x_coords_fixed, indexing='ij') - points = np.column_stack((Y_fixed.ravel(), X_fixed.ravel())) - - # Interpolate - data_values_fixed = interp_data(points).reshape(Y_fixed.shape) - confidence_map_fixed = interp_conf(points).reshape(Y_fixed.shape) - - print(f"Fixed grid resolution: {len(y_coords_fixed)} x {len(x_coords_fixed)}") - print(f"Time range: {y_coords_fixed[0]:.1f} to {y_coords_fixed[-1]:.1f} μs") - print(f"Wire range: {x_coords_fixed[0]:.1f} to {x_coords_fixed[-1]:.1f}") - - return data_values_fixed, confidence_map_fixed, x_coords_fixed, y_coords_fixed - - -def apply_smoothing(data_values, time_smoothing_width=1.0, time_bin_size=0.5): - """ - Apply Gaussian smoothing in time domain. - - Parameters - ---------- - data_values : np.ndarray - 2D array of values (time, wire) - time_smoothing_width : float - Width of Gaussian smoothing in microseconds - time_bin_size : float - Time bin size in microseconds - - Returns - ------- - smoothed_data : np.ndarray - Smoothed data array - """ - # Convert time width to number of bins - sigma_bins = time_smoothing_width / time_bin_size - smoothed_data = np.zeros_like(data_values) - - # Smooth each column (wire) independently - for i in range(data_values.shape[1]): - smoothed_data[:, i] = gaussian_filter1d(data_values[:, i], sigma=sigma_bins) - - return smoothed_data - - -def extract_kernel(smoothed_data, x_coords, y_coords, kernel_size=(127, 201)): - """ - Extract a kernel centered at (0,0) from the smoothed data. - If kernel size is even, zero out one row/column to ensure (0,0) is at center. - - Parameters - ---------- - smoothed_data : np.ndarray - 2D array of smoothed values - x_coords : np.ndarray - Wire coordinates - y_coords : np.ndarray - Time coordinates - kernel_size : tuple - (height, width) of kernel to extract - - Returns - ------- - kernel : np.ndarray - Extracted kernel - kernel_x_coords : np.ndarray - Wire coordinates for kernel - kernel_y_coords : np.ndarray - Time coordinates for kernel - """ - # Find indices closest to (0,0) - x_idx_zero = np.argmin(np.abs(x_coords - 0)) - y_idx_zero = np.argmin(np.abs(y_coords - 0)) - - kernel_height, kernel_width = kernel_size - - # Calculate extraction bounds - # For even kernel size, we need to handle centering - if kernel_height % 2 == 0: - # Even height - need to zero out one row - half_h = kernel_height // 2 - y_start = y_idx_zero - half_h + 1 - y_end = y_idx_zero + half_h + 1 - else: - # Odd height - normal centering - half_h = kernel_height // 2 - y_start = y_idx_zero - half_h - y_end = y_idx_zero + half_h + 1 - - if kernel_width % 2 == 0: - # Even width - need to zero out one column - half_w = kernel_width // 2 - x_start = x_idx_zero - half_w + 1 - x_end = x_idx_zero + half_w + 1 - else: - # Odd width - normal centering - half_w = kernel_width // 2 - x_start = x_idx_zero - half_w - x_end = x_idx_zero + half_w + 1 - - # Handle boundaries - y_start = max(0, y_start) - y_end = min(smoothed_data.shape[0], y_end) - x_start = max(0, x_start) - x_end = min(smoothed_data.shape[1], x_end) - - # Extract kernel - kernel = np.zeros(kernel_size) - extracted = smoothed_data[y_start:y_end, x_start:x_end] - - # Calculate where to place the extracted data in the kernel - kernel_y_start = max(0, -y_start + y_idx_zero - kernel_height//2 + (1 if kernel_height % 2 == 0 else 0)) - kernel_x_start = max(0, -x_start + x_idx_zero - kernel_width//2 + (1 if kernel_width % 2 == 0 else 0)) - - kernel_y_end = kernel_y_start + extracted.shape[0] - kernel_x_end = kernel_x_start + extracted.shape[1] - - kernel[kernel_y_start:kernel_y_end, kernel_x_start:kernel_x_end] = extracted - - # If even size, zero out the first row/column to ensure (0,0) is at center - if kernel_height % 2 == 0: - kernel[0, :] = 0 - if kernel_width % 2 == 0: - kernel[:, 0] = 0 - - # Extract corresponding coordinates - kernel_x_coords = x_coords[x_start:x_end] - kernel_y_coords = y_coords[y_start:y_end] - - # Pad coordinate arrays if needed - if len(kernel_x_coords) < kernel_width: - # Pad with appropriate values - dx = x_coords[1] - x_coords[0] if len(x_coords) > 1 else 0.1 - if x_start == 0: - # Pad on the left - n_pad = kernel_width - len(kernel_x_coords) - pad_values = kernel_x_coords[0] - dx * np.arange(n_pad, 0, -1) - kernel_x_coords = np.concatenate([pad_values, kernel_x_coords]) - else: - # Pad on the right - n_pad = kernel_width - len(kernel_x_coords) - pad_values = kernel_x_coords[-1] + dx * np.arange(1, n_pad + 1) - kernel_x_coords = np.concatenate([kernel_x_coords, pad_values]) - - if len(kernel_y_coords) < kernel_height: - # Pad with appropriate values - dy = y_coords[1] - y_coords[0] if len(y_coords) > 1 else 0.5 - if y_start == 0: - # Pad on the bottom - n_pad = kernel_height - len(kernel_y_coords) - pad_values = kernel_y_coords[0] - dy * np.arange(n_pad, 0, -1) - kernel_y_coords = np.concatenate([pad_values, kernel_y_coords]) - else: - # Pad on the top - n_pad = kernel_height - len(kernel_y_coords) - pad_values = kernel_y_coords[-1] + dy * np.arange(1, n_pad + 1) - kernel_y_coords = np.concatenate([kernel_y_coords, pad_values]) - - return kernel, kernel_x_coords, kernel_y_coords - - -def save_kernel(kernel, kernel_x_coords, kernel_y_coords, plane, - time_bin_size, wire_spacing, time_smoothing_width, output_path): - """ - Save kernel data to npz file in actual current values (not log scale). - - Parameters - ---------- - kernel : np.ndarray - Kernel array in paper's "Log 10" scale - kernel_x_coords : np.ndarray - Wire coordinates - kernel_y_coords : np.ndarray - Time coordinates - plane : str - Plane name ('U', 'V', or 'Y') - time_bin_size : float - Time bin size used - wire_spacing : float - Wire spacing used - time_smoothing_width : float - Smoothing width used - output_path : str - Output file path - """ - # Convert from log10 scale to actual current values before saving - kernel_actual = paper_log10_to_actual(kernel) - - # Clamp very small values to exactly zero to avoid numerical noise - # This prevents the off-white background issue when converting back to log - threshold = 1e-5 - kernel_actual = np.where(np.abs(kernel_actual) < threshold, 0.0, kernel_actual) - - np.savez(output_path, - kernel=kernel_actual, # Save in actual values, not log scale - kernel_x_coords=kernel_x_coords, - kernel_y_coords=kernel_y_coords, - plane=plane, - time_bin_size=time_bin_size, - wire_spacing=wire_spacing, - time_smoothing_width=time_smoothing_width) - - print(f"Saved kernel to {output_path} (in actual values, not log scale)") - - -def process_single_plane(colorbar_path, plot_path, plane='U', - time_bin_size=0.5, wire_spacing=0.1, - time_smoothing_width=1.0, kernel_size=(127, 201), - output_kernel_path=None): - """ - Process a single plane: extract, smooth, and extract kernel. - - Parameters - ---------- - colorbar_path : str - Path to colorbar image - plot_path : str - Path to plot image - plane : str - Which plane ('U', 'V', or 'Y') - time_bin_size : float - Time bin size in microseconds - wire_spacing : float - Wire spacing - time_smoothing_width : float - Gaussian smoothing width in microseconds - kernel_size : tuple - (height, width) of kernel to extract - output_kernel_path : str, optional - Path to save kernel, defaults to 'kernel_{plane}_kernel.npz' - - Returns - ------- - dict - Dictionary containing all results - """ - print(f"\nProcessing {plane} plane...") - - # Extract colors from colorbar - extracted_colors, extracted_values = analyze_colorbar_for_plane(colorbar_path, plane=plane) - - # Extract data with fixed bins - data_values_log10, confidence_map, x_coords, y_coords = extract_with_confidence_fixed_bins( - plot_path, extracted_colors, extracted_values, - time_bin_size=time_bin_size, - wire_spacing=wire_spacing - ) - - # Apply smoothing - smoothed_data = apply_smoothing(data_values_log10, time_smoothing_width, time_bin_size) - - # Extract kernel - kernel, kernel_x_coords, kernel_y_coords = extract_kernel(smoothed_data, x_coords, y_coords, kernel_size) - - print(f"Extracted kernel shape: {kernel.shape}") - print(f"Kernel center value at (0,0): {kernel[kernel.shape[0]//2, kernel.shape[1]//2]:.3f}") - - # Save kernel if path provided - if output_kernel_path is None: - output_kernel_path = f'{plane}_plane_kernel.npz' - - save_kernel(kernel, kernel_x_coords, kernel_y_coords, plane, - time_bin_size, wire_spacing, time_smoothing_width, output_kernel_path) - - return { - 'kernel': kernel, - 'kernel_x_coords': kernel_x_coords, - 'kernel_y_coords': kernel_y_coords, - 'smoothed_data': smoothed_data, - 'data_values': data_values_log10, - 'confidence_map': confidence_map, - 'x_coords': x_coords, - 'y_coords': y_coords, - 'plane': plane, - 'time_bin_size': time_bin_size, - 'wire_spacing': wire_spacing, - 'time_smoothing_width': time_smoothing_width - } - - -def main(): - """Extract kernels for all wire planes when run as a script.""" - import os - - # Configuration - planes = ['U', 'V', 'Y'] - script_dir = os.path.dirname(os.path.abspath(__file__)) - image_dir = os.path.join(script_dir, 'images') - output_dir = script_dir # Save in tools/responses/ - - # Extraction parameters - kernel_size = (127, 201) - time_bin_size = 0.5 - wire_spacing = 0.1 - time_smoothing_width = 1.0 - - print("="*60) - print("Wire Response Kernel Extraction") - print("="*60) - print(f"Image directory: {image_dir}") - print(f"Output directory: {output_dir}") - print(f"Kernel size: {kernel_size}") - print(f"Time bin size: {time_bin_size} μs") - print(f"Wire spacing: {wire_spacing}") - print(f"Time smoothing: {time_smoothing_width} μs") - - # Process each plane - for plane in planes: - colorbar_path = os.path.join(image_dir, f'{plane}_response_colorbar.png') - plot_path = os.path.join(image_dir, f'{plane}_response_image.png') - output_path = os.path.join(output_dir, f'{plane}_plane_kernel.npz') - - # Check if input files exist - if not os.path.exists(colorbar_path): - print(f"\nERROR: Missing colorbar image: {colorbar_path}") - continue - if not os.path.exists(plot_path): - print(f"\nERROR: Missing plot image: {plot_path}") - continue - - try: - # Process the plane - result = process_single_plane( - colorbar_path=colorbar_path, - plot_path=plot_path, - plane=plane, - time_bin_size=time_bin_size, - wire_spacing=wire_spacing, - time_smoothing_width=time_smoothing_width, - kernel_size=kernel_size, - output_kernel_path=output_path - ) - - print(f"✓ Created {output_path}") - - except Exception as e: - print(f"\n✗ ERROR processing {plane} plane: {e}") - import traceback - traceback.print_exc() - - print("\n" + "="*60) - print("Extraction complete!") - print("="*60) - print("\nNext steps:") - print("1. Run example scripts: python3 example_response_usage.py") - print("2. Run timing benchmark: python3 timing/benchmark_response_interpolation.py") - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/response_extraction_rbf.py b/closure/archive/gradient_test/gradient_test/tools/responses/response_extraction_rbf.py deleted file mode 100644 index 2274fc7..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/responses/response_extraction_rbf.py +++ /dev/null @@ -1,531 +0,0 @@ -""" -Response Extraction from Images - -This module handles extraction of wire response data from colorbar and plot images, -including conversion between the paper's "Log 10" scale and actual current values. -""" - -import numpy as np -from scipy.spatial import KDTree -from scipy.interpolate import RegularGridInterpolator -from skimage.restoration import denoise_bilateral -from PIL import Image - - -# Define color scale ranges for each plane -PLANE_CONFIGS = { - 'U': { - 'value_range': (-3.16, 3.16), - 'tick_values': [3, 2, 1, 0, -1, -2, -3], - 'title': 'U Plane' - }, - 'V': { - 'value_range': (-3.16, 3.16), - 'tick_values': [3, 2, 1, 0, -1, -2, -3], - 'title': 'V Plane' - }, - 'Y': { - 'value_range': (-3.16, 4.16), - 'tick_values': [4, 3, 2, 1, 0, -1, -2, -3], - 'title': 'Y Plane' - } -} - - -def analyze_colorbar_for_plane(colorbar_path, plane='U', n_colors=20): - """ - Analyze colorbar and extract colors with exact tick positions for specific plane. - - Parameters - ---------- - colorbar_path : str - Path to colorbar image file - plane : str - Which plane ('U', 'V', or 'Y') - n_colors : int - Number of color levels to extract - - Returns - ------- - extracted_colors : np.ndarray - RGB colors, shape (n_colors, 3) - extracted_values : np.ndarray - Corresponding "Log 10" values, shape (n_colors,) - """ - # Load colorbar - colorbar_img = np.array(Image.open(colorbar_path).convert('RGB')) - height, width = colorbar_img.shape[:2] - - # Get value range for this plane - value_range = PLANE_CONFIGS[plane]['value_range'] - - # Extract colors evenly spaced along the colorbar - positions = np.linspace(0, height-1, n_colors) - center_x = width // 2 - - extracted_colors = [] - for pos in positions: - y_idx = int(pos) - region = colorbar_img[ - max(0, y_idx-1):min(height, y_idx+2), - max(0, center_x-2):min(width, center_x+3) - ] - mean_color = np.mean(region.reshape(-1, 3), axis=0) - extracted_colors.append(mean_color) - - extracted_colors = np.array(extracted_colors) - # Values go from top to bottom in "Log 10" scale - extracted_values = np.linspace(value_range[1], value_range[0], n_colors) - - return extracted_colors, extracted_values - - -def paper_log10_to_actual(log10_values): - """ - Convert from the paper's "Log 10" scale back to actual current values. - - The paper shows a symmetric log scale where: - - For "Log 10" > 0: i = 10^(value) / 10^5 - - For "Log 10" = 0: i = 0 - - For "Log 10" < 0: i = -10^(abs(value)) / 10^5 - - Parameters - ---------- - log10_values : np.ndarray - Values in paper's "Log 10" scale - - Returns - ------- - actual_values : np.ndarray - Actual current values (electrons per time bin) - """ - actual_values = np.zeros_like(log10_values) - - # Positive Log10 values - mask_pos = log10_values > 0 - actual_values[mask_pos] = 10**(log10_values[mask_pos]) / 10**5 - - # Zero - mask_zero = log10_values == 0 - actual_values[mask_zero] = 0 - - # Negative Log10 values - mask_neg = log10_values < 0 - actual_values[mask_neg] = -10**(-log10_values[mask_neg]) / 10**5 - - return actual_values - - -def extract_with_bilateral_filter(plot_path, colorbar_colors, colorbar_values, - x_range=(-10.5, 10.5), y_range=(-60, 40), - time_bin_size=0.5, wire_spacing=0.1): - """ - Extract data using bilateral filtering to smooth within contours while preserving edges. - - Parameters - ---------- - plot_path : str - Path to plot image file - colorbar_colors : np.ndarray - RGB colors from colorbar, shape (n_colors, 3) - colorbar_values : np.ndarray - Corresponding values, shape (n_colors,) - x_range : tuple - (x_min, x_max) wire number range - y_range : tuple - (y_min, y_max) time range in microseconds - time_bin_size : float - Time bin size in microseconds - wire_spacing : float - Wire number spacing - - Returns - ------- - data_values : np.ndarray - Extracted values on fixed grid - confidence_map : np.ndarray - Confidence values on fixed grid - x_coords : np.ndarray - Wire coordinates - y_coords : np.ndarray - Time coordinates - """ - # Load plot image - plot_img = np.array(Image.open(plot_path).convert('RGB')) - plot_height, plot_width = plot_img.shape[:2] - - print(f"Image size: {plot_height} x {plot_width}") - - # Build color mapping - color_tree = KDTree(colorbar_colors) - - # Map colors to values - discrete mapping, no interpolation - print("Mapping colors to discrete values...") - plot_img_flat = plot_img.reshape(-1, 3) - distances, indices = color_tree.query(plot_img_flat) - pixel_values = colorbar_values[indices].reshape(plot_height, plot_width) - - # Get unique contour levels and spacing - unique_levels = np.unique(pixel_values) - contour_spacing = np.median(np.diff(unique_levels)) - - print(f"Found {len(unique_levels)} unique contour levels") - print(f"Contour spacing: {contour_spacing:.3f}") - print(f"Value range: {unique_levels.min():.2f} to {unique_levels.max():.2f}") - - # Apply bilateral filtering to smooth within contours while preserving edges - print("Applying bilateral filter...") - - # Normalize values for bilateral filter (works better with values in [0,1] range) - value_min, value_max = pixel_values.min(), pixel_values.max() - pixel_values_normalized = (pixel_values - value_min) / (value_max - value_min) - - # Apply bilateral filter - # sigma_color controls how much values can differ while still being smoothed together - # Set it to about half the contour spacing (in normalized units) - sigma_color = 0.01 - sigma_spatial = 5.0 # Spatial extent of smoothing - - filtered_normalized = denoise_bilateral( - pixel_values_normalized, - sigma_color=sigma_color, - sigma_spatial=sigma_spatial, - channel_axis=None # Single channel data - ) - - # Convert back to original value range - filtered_values = filtered_normalized * (value_max - value_min) + value_min - - print(f"Filtered value range: {filtered_values.min():.2f} to {filtered_values.max():.2f}") - - # Create coordinate arrays for the image - x_coords_img = np.linspace(x_range[0], x_range[1], plot_width) - y_coords_img = np.linspace(y_range[1], y_range[0], plot_height) # Note: y flipped - - # Create output coordinate grids at target resolution - n_time_bins = int((y_range[1] - y_range[0]) / time_bin_size) + 1 - y_coords_fixed = np.linspace(y_range[0], y_range[1], n_time_bins) - - n_wire_bins = int((x_range[1] - x_range[0]) / wire_spacing) + 1 - x_coords_fixed = np.linspace(x_range[0], x_range[1], n_wire_bins) - - # Interpolate filtered values to fixed grid - print("Interpolating to target grid...") - interp_func = RegularGridInterpolator( - (y_coords_img[::-1], x_coords_img), # Flip y for ascending order - filtered_values[::-1, :], # Flip data accordingly - method='linear', - bounds_error=False, - fill_value=0 - ) - - # Create mesh grid for evaluation - Y_fixed, X_fixed = np.meshgrid(y_coords_fixed, x_coords_fixed, indexing='ij') - eval_points = np.column_stack((Y_fixed.ravel(), X_fixed.ravel())) - - # Evaluate at fixed grid points - data_values_fixed = interp_func(eval_points).reshape(Y_fixed.shape) - - # Simple confidence map (uniform high confidence) - confidence_map_fixed = np.ones_like(data_values_fixed) * 0.9 - - print(f"Fixed grid resolution: {len(y_coords_fixed)} x {len(x_coords_fixed)}") - print(f"Output value range: {data_values_fixed.min():.2f} to {data_values_fixed.max():.2f}") - - return data_values_fixed, confidence_map_fixed, x_coords_fixed, y_coords_fixed - - -def extract_kernel(data_values, x_coords, y_coords, kernel_size=(127, 201)): - """ - Extract a kernel centered at (0,0) from the data. - If kernel size is even, zero out one row/column to ensure (0,0) is at center. - - Parameters - ---------- - data_values : np.ndarray - 2D array of values - x_coords : np.ndarray - Wire coordinates - y_coords : np.ndarray - Time coordinates - kernel_size : tuple - (height, width) of kernel to extract - - Returns - ------- - kernel : np.ndarray - Extracted kernel - kernel_x_coords : np.ndarray - Wire coordinates for kernel - kernel_y_coords : np.ndarray - Time coordinates for kernel - """ - # Find indices closest to (0,0) - x_idx_zero = np.argmin(np.abs(x_coords - 0)) - y_idx_zero = np.argmin(np.abs(y_coords - 0)) - - kernel_height, kernel_width = kernel_size - - # Calculate extraction bounds - # For even kernel size, we need to handle centering - if kernel_height % 2 == 0: - # Even height - need to zero out one row - half_h = kernel_height // 2 - y_start = y_idx_zero - half_h + 1 - y_end = y_idx_zero + half_h + 1 - else: - # Odd height - normal centering - half_h = kernel_height // 2 - y_start = y_idx_zero - half_h - y_end = y_idx_zero + half_h + 1 - - if kernel_width % 2 == 0: - # Even width - need to zero out one column - half_w = kernel_width // 2 - x_start = x_idx_zero - half_w + 1 - x_end = x_idx_zero + half_w + 1 - else: - # Odd width - normal centering - half_w = kernel_width // 2 - x_start = x_idx_zero - half_w - x_end = x_idx_zero + half_w + 1 - - # Handle boundaries - y_start = max(0, y_start) - y_end = min(data_values.shape[0], y_end) - x_start = max(0, x_start) - x_end = min(data_values.shape[1], x_end) - - # Extract kernel - kernel = np.zeros(kernel_size) - extracted = data_values[y_start:y_end, x_start:x_end] - - # Calculate where to place the extracted data in the kernel - kernel_y_start = max(0, -y_start + y_idx_zero - kernel_height//2 + (1 if kernel_height % 2 == 0 else 0)) - kernel_x_start = max(0, -x_start + x_idx_zero - kernel_width//2 + (1 if kernel_width % 2 == 0 else 0)) - - kernel_y_end = kernel_y_start + extracted.shape[0] - kernel_x_end = kernel_x_start + extracted.shape[1] - - kernel[kernel_y_start:kernel_y_end, kernel_x_start:kernel_x_end] = extracted - - # If even size, zero out the first row/column to ensure (0,0) is at center - if kernel_height % 2 == 0: - kernel[0, :] = 0 - if kernel_width % 2 == 0: - kernel[:, 0] = 0 - - # Extract corresponding coordinates - kernel_x_coords = x_coords[x_start:x_end] - kernel_y_coords = y_coords[y_start:y_end] - - # Pad coordinate arrays if needed - if len(kernel_x_coords) < kernel_width: - # Pad with appropriate values - dx = x_coords[1] - x_coords[0] if len(x_coords) > 1 else 0.1 - if x_start == 0: - # Pad on the left - n_pad = kernel_width - len(kernel_x_coords) - pad_values = kernel_x_coords[0] - dx * np.arange(n_pad, 0, -1) - kernel_x_coords = np.concatenate([pad_values, kernel_x_coords]) - else: - # Pad on the right - n_pad = kernel_width - len(kernel_x_coords) - pad_values = kernel_x_coords[-1] + dx * np.arange(1, n_pad + 1) - kernel_x_coords = np.concatenate([kernel_x_coords, pad_values]) - - if len(kernel_y_coords) < kernel_height: - # Pad with appropriate values - dy = y_coords[1] - y_coords[0] if len(y_coords) > 1 else 0.5 - if y_start == 0: - # Pad on the bottom - n_pad = kernel_height - len(kernel_y_coords) - pad_values = kernel_y_coords[0] - dy * np.arange(n_pad, 0, -1) - kernel_y_coords = np.concatenate([pad_values, kernel_y_coords]) - else: - # Pad on the top - n_pad = kernel_height - len(kernel_y_coords) - pad_values = kernel_y_coords[-1] + dy * np.arange(1, n_pad + 1) - kernel_y_coords = np.concatenate([kernel_y_coords, pad_values]) - - return kernel, kernel_x_coords, kernel_y_coords - - -def save_kernel(kernel, kernel_x_coords, kernel_y_coords, plane, - time_bin_size, wire_spacing, output_path): - """ - Save kernel data to npz file in actual current values (not log scale). - - Parameters - ---------- - kernel : np.ndarray - Kernel array in paper's "Log 10" scale - kernel_x_coords : np.ndarray - Wire coordinates - kernel_y_coords : np.ndarray - Time coordinates - plane : str - Plane name ('U', 'V', or 'Y') - time_bin_size : float - Time bin size used - wire_spacing : float - Wire spacing used - output_path : str - Output file path - """ - # Convert from log10 scale to actual current values before saving - kernel_actual = paper_log10_to_actual(kernel) - - # Clamp very small values to exactly zero to avoid numerical noise - threshold = 1e-5 - kernel_actual = np.where(np.abs(kernel_actual) < threshold, 0.0, kernel_actual) - - np.savez(output_path, - kernel=kernel_actual, # Save in actual values, not log scale - kernel_x_coords=kernel_x_coords, - kernel_y_coords=kernel_y_coords, - plane=plane, - time_bin_size=time_bin_size, - wire_spacing=wire_spacing) - - print(f"Saved kernel to {output_path} (in actual values, not log scale)") - - -def process_single_plane(colorbar_path, plot_path, plane='U', - time_bin_size=0.5, wire_spacing=0.1, - kernel_size=(127, 201), - output_kernel_path=None): - """ - Process a single plane using bilateral filtering approach. - - Parameters - ---------- - colorbar_path : str - Path to colorbar image - plot_path : str - Path to plot image - plane : str - Which plane ('U', 'V', or 'Y') - time_bin_size : float - Time bin size in microseconds - wire_spacing : float - Wire spacing - kernel_size : tuple - (height, width) of kernel to extract - output_kernel_path : str, optional - Path to save kernel, defaults to 'kernel_{plane}_kernel.npz' - - Returns - ------- - dict - Dictionary containing all results - """ - print(f"\nProcessing {plane} plane with bilateral filtering...") - - # Extract colors from colorbar - extracted_colors, extracted_values = analyze_colorbar_for_plane(colorbar_path, plane=plane) - - # Extract data using bilateral filtering - data_values_log10, confidence_map, x_coords, y_coords = extract_with_bilateral_filter( - plot_path, extracted_colors, extracted_values, - time_bin_size=time_bin_size, - wire_spacing=wire_spacing - ) - - # Extract kernel - kernel, kernel_x_coords, kernel_y_coords = extract_kernel( - data_values_log10, x_coords, y_coords, kernel_size - ) - - print(f"Extracted kernel shape: {kernel.shape}") - print(f"Kernel center value at (0,0): {kernel[kernel.shape[0]//2, kernel.shape[1]//2]:.3f}") - - # Save kernel if path provided - if output_kernel_path is None: - output_kernel_path = f'{plane}_plane_kernel.npz' - - save_kernel(kernel, kernel_x_coords, kernel_y_coords, plane, - time_bin_size, wire_spacing, output_kernel_path) - - return { - 'kernel': kernel, - 'kernel_x_coords': kernel_x_coords, - 'kernel_y_coords': kernel_y_coords, - 'data_values': data_values_log10, - 'confidence_map': confidence_map, - 'x_coords': x_coords, - 'y_coords': y_coords, - 'plane': plane, - 'time_bin_size': time_bin_size, - 'wire_spacing': wire_spacing - } - - -def main(): - """Extract kernels for all wire planes when run as a script.""" - import os - - # Configuration - planes = ['U', 'V', 'Y'] - script_dir = os.path.dirname(os.path.abspath(__file__)) - image_dir = os.path.join(script_dir, 'images') - output_dir = script_dir # Save in tools/responses/ - - # Extraction parameters - kernel_size = (127, 201) - time_bin_size = 0.5 - wire_spacing = 0.1 - - print("="*60) - print("Wire Response Kernel Extraction") - print("(Bilateral Filtering Approach)") - print("="*60) - print(f"Image directory: {image_dir}") - print(f"Output directory: {output_dir}") - print(f"Kernel size: {kernel_size}") - print(f"Time bin size: {time_bin_size} μs") - print(f"Wire spacing: {wire_spacing}") - - # Process each plane - for plane in planes: - colorbar_path = os.path.join(image_dir, f'{plane}_response_colorbar.png') - plot_path = os.path.join(image_dir, f'{plane}_response_image.png') - output_path = os.path.join(output_dir, f'{plane}_plane_kernel.npz') - - # Check if input files exist - if not os.path.exists(colorbar_path): - print(f"\nERROR: Missing colorbar image: {colorbar_path}") - continue - if not os.path.exists(plot_path): - print(f"\nERROR: Missing plot image: {plot_path}") - continue - - try: - # Process the plane - result = process_single_plane( - colorbar_path=colorbar_path, - plot_path=plot_path, - plane=plane, - time_bin_size=time_bin_size, - wire_spacing=wire_spacing, - kernel_size=kernel_size, - output_kernel_path=output_path - ) - - print(f"✓ Created {output_path}") - - except Exception as e: - print(f"\n✗ ERROR processing {plane} plane: {e}") - import traceback - traceback.print_exc() - - print("\n" + "="*60) - print("Extraction complete!") - print("="*60) - print("\nNext steps:") - print("1. Run example scripts: python3 example_response_usage.py") - print("2. Run timing benchmark: python3 timing/benchmark_response_interpolation.py") - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/response_visualization_utils.py b/closure/archive/gradient_test/gradient_test/tools/responses/response_visualization_utils.py deleted file mode 100644 index 7d0e695..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/responses/response_visualization_utils.py +++ /dev/null @@ -1,451 +0,0 @@ -""" -Visualization utilities for wire response data. - -This module provides plotting functions for visualizing kernels, -smoothed data, and creating animations. -""" - -import os -import shutil -import numpy as np -import matplotlib.pyplot as plt -from PIL import Image -from .response_extraction import PLANE_CONFIGS -from tools.kernels import calculate_wire_count - - -def visualize_kernel(kernel, kernel_x_coords, kernel_y_coords, plane='U', figsize=(8, 8)): - """ - Visualize the extracted kernel. - - Parameters - ---------- - kernel : np.ndarray - Kernel array - kernel_x_coords : np.ndarray - Wire coordinates for kernel - kernel_y_coords : np.ndarray - Time coordinates for kernel - plane : str - Plane name - figsize : tuple - Figure size - - Returns - ------- - fig : matplotlib.figure.Figure - Figure object - ax : matplotlib.axes.Axes - Axes object - """ - config = PLANE_CONFIGS[plane] - - fig, ax = plt.subplots(figsize=figsize) - - # Create continuous colormap - cmap = plt.cm.RdBu_r - - # Plot kernel - im = ax.imshow(kernel, aspect='auto', - extent=[kernel_x_coords[0], kernel_x_coords[-1], - kernel_y_coords[0], kernel_y_coords[-1]], - cmap=cmap, origin='lower') - - # Set axis properties - ax.set_xlabel('Wire Number', fontsize=12) - ax.set_ylabel('Time [μs]', fontsize=12) - ax.set_title(f'{config["title"]} - Extracted Kernel ({kernel.shape[0]}x{kernel.shape[1]})', - fontsize=14, pad=15) - - # Add grid - ax.grid(True, alpha=0.3, color='gray', linestyle='-', linewidth=0.5) - ax.set_axisbelow(True) - - # Add crosshairs at (0,0) - ax.axvline(x=0, color='black', linestyle='--', alpha=0.5, linewidth=1) - ax.axhline(y=0, color='black', linestyle='--', alpha=0.5, linewidth=1) - - # Create colorbar - cbar = plt.colorbar(im, ax=ax, pad=0.02, orientation='vertical') - cbar.set_label('Log 10″', rotation=270, labelpad=15, fontsize=12) - cbar.ax.tick_params(labelsize=10) - - # Set colorbar limits based on plane - im.set_clim(config['value_range']) - - plt.tight_layout() - return fig, ax - - -def visualize_diffusion_progression(DKernel, linear_s, x_coords, y_coords, plane='U', - figsize=(15, 3)): - """ - Visualize how kernels change with diffusion parameter s. - - Parameters - ---------- - DKernel : np.ndarray - Array of diffused kernels, shape (num_s, height, width) - linear_s : np.ndarray - Array of s values - x_coords : np.ndarray - Wire coordinates - y_coords : np.ndarray - Time coordinates - plane : str - Plane name - figsize : tuple - Figure size - - Returns - ------- - fig : matplotlib.figure.Figure - Figure object - """ - num_s = len(linear_s) - - # Show a few representative kernels - indices_to_show = [0, num_s//4, num_s//2, 3*num_s//4, num_s-1] - - fig, axes = plt.subplots(1, len(indices_to_show), figsize=figsize) - - config = PLANE_CONFIGS[plane] - cmap = plt.cm.RdBu_r - vmin, vmax = config['value_range'] - - for i, idx in enumerate(indices_to_show): - kernel = DKernel[idx] - s_val = linear_s[idx] - - im = axes[i].imshow(kernel, aspect='auto', - extent=[x_coords[0], x_coords[-1], y_coords[0], y_coords[-1]], - cmap=cmap, origin='lower', vmin=vmin, vmax=vmax) - - axes[i].set_title(f's = {s_val:.2f}') - axes[i].set_xlabel('Wire Number') - if i == 0: - axes[i].set_ylabel('Time [μs]') - - axes[i].axvline(x=0, color='black', linestyle='--', alpha=0.5) - axes[i].axhline(y=0, color='black', linestyle='--', alpha=0.5) - axes[i].grid(True, alpha=0.3) - - plt.tight_layout() - plt.suptitle(f'{plane} Plane Diffusion Progression', y=1.02) - return fig - - -def create_parameter_sweep_gif(visualization_func, DKernels, plane='Y', - parameter='w_offset', param_range=(0, 1), - fixed_params=None, output_filename='parameter_sweep.gif', - n_frames=30, fps=10): - """ - Create a GIF animation sweeping through any parameter. - - Parameters - ---------- - visualization_func : callable - Function to create visualization (e.g., visualize_interpolation_steps) - DKernels : dict - Dictionary of diffusion kernels - plane : str - Which plane to visualize - parameter : str - Which parameter to sweep ('w_offset', 's_observed', or 't_offset') - param_range : tuple - (min, max) values for the parameter - fixed_params : dict, optional - Dict of fixed parameters (defaults: s_observed=0.3, w_offset=0.25, t_offset=0.15) - output_filename : str - Name of output GIF file - n_frames : int - Number of frames for the animation - fps : int - Frames per second for the GIF - - Returns - ------- - None - Saves GIF to output_filename - """ - # Set default fixed parameters - if fixed_params is None: - fixed_params = { - 's_observed': 0.3, - 'w_offset': 0.25, - 't_offset': 0.15 - } - - # Create temporary folder for frames - temp_folder = 'temp_param_sweep_frames' - if os.path.exists(temp_folder): - shutil.rmtree(temp_folder) - os.makedirs(temp_folder) - - print(f"Creating parameter sweep GIF for {parameter}...") - print(f" Range: {param_range[0]:.3f} to {param_range[1]:.3f}") - - try: - # Create parameter values that go from min to max and back to min - half_frames = n_frames // 2 - param_values_forward = np.linspace(param_range[0], param_range[1], half_frames, endpoint=False) - param_values_backward = np.linspace(param_range[1], param_range[0], n_frames - half_frames, endpoint=True) - param_values = np.concatenate([param_values_forward, param_values_backward]) - - # Generate frames - frame_files = [] - for i, param_val in enumerate(param_values): - print(f" Generating frame {i+1}/{n_frames} ({parameter}={param_val:.3f})") - - # Set up parameters for this frame - params = fixed_params.copy() - params[parameter] = param_val - - # Create the visualization - fig = visualization_func( - DKernels, - plane=plane, - **params - ) - - if fig: - # Save frame - frame_filename = os.path.join(temp_folder, f'frame_{i:04d}.png') - plt.figure(fig.number) - plt.savefig(frame_filename, dpi=100, bbox_inches='tight') - plt.close(fig) - frame_files.append(frame_filename) - - # Create GIF from frames - print("\nCreating GIF...") - images = [] - for filename in frame_files: - images.append(Image.open(filename)) - - if images: - # Save GIF - duration = 1000 // fps - images[0].save( - output_filename, - save_all=True, - append_images=images[1:], - duration=duration, - loop=0 - ) - print(f"GIF saved as: {output_filename}") - - finally: - # Clean up temporary folder - print("\nCleaning up temporary files...") - if os.path.exists(temp_folder): - shutil.rmtree(temp_folder) - print("Done!") - - -def visualize_interpolation_steps(DKernels, plane='Y', s_observed=0.3, w_offset=0.25, t_offset=0.15, - wire_spacing=0.1, time_spacing=0.5, verbose=False): - """ - Visualize the interpolation process step by step in a 2x2 layout. - - Parameters - ---------- - DKernels : dict - Dictionary of diffusion kernels - plane : str - Which plane to visualize - s_observed : float - Diffusion parameter in [0, 1] - w_offset : float - Wire offset in [0, 1) - t_offset : float - Time offset in [0, 0.5) - wire_spacing : float - Wire spacing - time_spacing : float - Time spacing - verbose : bool - Print debug information - - Returns - ------- - fig : matplotlib.figure.Figure - Figure object - """ - if plane not in DKernels: - print(f"Plane {plane} not available") - return None - - DKernel, linear_s, kernel_shape, x_coords, y_coords = DKernels[plane] - kernel_height, kernel_width = kernel_shape - num_s = len(linear_s) - - # Calculate interpolation parameters - s_continuous = s_observed * (num_s - 1) - s_idx = int(np.floor(s_continuous)) - s_idx = min(s_idx, num_s - 2) - s_alpha = s_continuous - s_idx - - center_w = kernel_width // 2 - bins_per_wire = int(1.0 / wire_spacing) - w_bin_offset = w_offset * bins_per_wire - w_base_bin = int(np.floor(w_bin_offset)) - w_alpha = w_bin_offset - w_base_bin - - # Calculate wire parameters - num_wires = calculate_wire_count(kernel_width, wire_spacing) - - if num_wires % 2 == 0: - half_wires = num_wires // 2 - wire_positions = np.arange(-half_wires, half_wires) - else: - half_wires = num_wires // 2 - wire_positions = np.arange(-half_wires, half_wires + 1) - - wire_base_positions = wire_positions * bins_per_wire + center_w - actual_wire_positions = wire_base_positions + w_base_bin - - if verbose: - print(f"\nInterpolation parameters:") - print(f" s_observed={s_observed:.3f} -> s_idx={s_idx}, s_alpha={s_alpha:.3f}") - print(f" w_offset={w_offset:.3f} -> w_base_bin={w_base_bin}, w_alpha={w_alpha:.3f}") - print(f" t_offset={t_offset:.3f}") - print(f" num_wires={num_wires}, Expected output shape: ({num_wires}, {kernel_height-1})") - - # Define specific wires and colors - target_wires = [-1, 0, 1, 3, 5] - wire_colors = ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6'] # Red, Blue, Green, Orange, Purple - - # Find indices for target wires - wire_indices_to_show = [] - for target in target_wires: - idx = np.where(wire_positions == target)[0] - if len(idx) > 0: - wire_indices_to_show.append(idx[0]) - - # Extract interpolation data for selected wires - all_wire_results = [] - all_wire_steps = [] - - for wire_idx in wire_indices_to_show: - # Get the two adjacent wire bin indices for interpolation - wire_bin_left = wire_base_positions[wire_idx] + w_base_bin - wire_bin_right = wire_bin_left + 1 - - # Clamp to valid range - wire_bin_left = np.clip(wire_bin_left, 0, kernel_width - 1) - wire_bin_right = np.clip(wire_bin_right, 0, kernel_width - 1) - - # Step 1: Extract values for s interpolation - values_s_n_left = np.array(DKernel[s_idx, :, int(wire_bin_left)]) - values_s_n_plus_1_left = np.array(DKernel[s_idx + 1, :, int(wire_bin_left)]) - values_s_n_right = np.array(DKernel[s_idx, :, int(wire_bin_right)]) - values_s_n_plus_1_right = np.array(DKernel[s_idx + 1, :, int(wire_bin_right)]) - - # Step 2: S interpolation for both left and right wire positions - values_s_interp_left = (1 - s_alpha) * values_s_n_left + s_alpha * values_s_n_plus_1_left - values_s_interp_right = (1 - s_alpha) * values_s_n_right + s_alpha * values_s_n_plus_1_right - - # Step 3: Wire interpolation - values_w_interp = (1 - w_alpha) * values_s_interp_left + w_alpha * values_s_interp_right - - # Step 4: Time interpolation - t_alpha = t_offset / time_spacing - interpolated_values = (1 - t_alpha) * values_w_interp[:-1] + t_alpha * values_w_interp[1:] - - # Store results - all_wire_results.append(interpolated_values) - all_wire_steps.append({ - 'left_s_n': values_s_n_left, - 'left_s_n_plus_1': values_s_n_plus_1_left, - 'right_s_n': values_s_n_right, - 'right_s_n_plus_1': values_s_n_plus_1_right, - 'left_s_interp': values_s_interp_left, - 'right_s_interp': values_s_interp_right, - 'w_interp': values_w_interp, - 'final': interpolated_values - }) - - # Create 2x2 visualization - fig, axes = plt.subplots(2, 2, figsize=(12, 10)) - - # Create time coordinates - time_full = np.linspace(y_coords[0], y_coords[-1], kernel_height) - time_reduced = np.linspace(y_coords[0], y_coords[-1], kernel_height - 1) - - # Get wire labels for the selected wires - wire_labels = [wire_positions[i] for i in wire_indices_to_show] - - # Top left: s_n (dashed) and s_n+1 (solid) for left positions - for i, (wire_idx, wire_label) in enumerate(zip(wire_indices_to_show, wire_labels)): - step = all_wire_steps[i] - color = wire_colors[i] - - axes[0, 0].plot(time_full, step['left_s_n'], color=color, alpha=0.7, - linestyle='--') - axes[0, 0].plot(time_full, step['left_s_n_plus_1'], color=color, alpha=0.7, - linestyle='-') - - axes[0, 0].set_title(f'Left positions: s[{s_idx}] (dashed) & s[{s_idx+1}] (solid)') - axes[0, 0].set_xlabel('Time [μs]') - axes[0, 0].set_ylabel('Value') - axes[0, 0].grid(True, alpha=0.3) - - # Top right: After S interpolation (solid=left, dashed=right) - for i, (wire_idx, wire_label) in enumerate(zip(wire_indices_to_show, wire_labels)): - step = all_wire_steps[i] - color = wire_colors[i] - - axes[0, 1].plot(time_full, step['left_s_interp'], color=color, alpha=0.7, - linestyle='-') - axes[0, 1].plot(time_full, step['right_s_interp'], color=color, alpha=0.7, - linestyle='--') - - axes[0, 1].set_title(f'After S interpolation\n(solid=left, dashed=right)') - axes[0, 1].set_xlabel('Time [μs]') - axes[0, 1].set_ylabel('Value') - axes[0, 1].grid(True, alpha=0.3) - - # Bottom left: Final results - for i, (wire_idx, wire_label) in enumerate(zip(wire_indices_to_show, wire_labels)): - step = all_wire_steps[i] - color = wire_colors[i] - - axes[1, 0].plot(time_reduced, step['final'], color=color, alpha=0.8, - linewidth=2, label=f'Wire {wire_label}') - - axes[1, 0].set_title('Final Results (after all interpolations)') - axes[1, 0].set_xlabel('Time [μs]') - axes[1, 0].set_ylabel('Interpolated Value') - axes[1, 0].legend() - axes[1, 0].grid(True, alpha=0.3) - - # Bottom right: Full S-interpolated plane with colored lines - config = PLANE_CONFIGS[plane] - cmap = plt.cm.RdBu_r - vmin, vmax = config['value_range'] - - # Perform S interpolation on the full planes - full_s_interp = (1 - s_alpha) * DKernel[s_idx] + s_alpha * DKernel[s_idx + 1] - - # Plot the interpolated plane - im = axes[1, 1].imshow(full_s_interp.T, aspect='auto', - extent=[y_coords[0], y_coords[-1], x_coords[0], x_coords[-1]], - cmap=cmap, origin='lower', vmin=vmin, vmax=vmax) - - # Add colored lines at the actual wire positions - for i, (wire_idx, wire_label) in enumerate(zip(wire_indices_to_show, wire_labels)): - wire_pos = actual_wire_positions[wire_idx] - if 0 <= wire_pos < kernel_width: - wire_coord = x_coords[int(wire_pos)] if int(wire_pos) < len(x_coords) else x_coords[-1] - axes[1, 1].axhline(y=wire_coord, color=wire_colors[i], alpha=0.8, - linewidth=2, label=f'Wire {wire_label}') - - axes[1, 1].set_title(f'S-interpolated plane (s={s_observed:.2f})\nwith wire positions (w_offset={w_offset:.2f})') - axes[1, 1].set_xlabel('Time [μs]') - axes[1, 1].set_ylabel('Wire Number') - axes[1, 1].legend(loc='upper right', fontsize=8) - axes[1, 1].grid(True, alpha=0.3) - - plt.tight_layout() - - return fig \ No newline at end of file diff --git a/closure/archive/gradient_test/gradient_test/tools/responses/visualization.py b/closure/archive/gradient_test/gradient_test/tools/responses/visualization.py deleted file mode 100644 index 212837a..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/responses/visualization.py +++ /dev/null @@ -1,506 +0,0 @@ -""" -Visualization utilities for wire response data with proper log10 handling. - -This module provides plotting functions for visualizing kernels, -smoothed data, and creating animations. Kernels are stored in actual values -but displayed in log10 scale for consistency with paper figures. -""" - -import os -import shutil -import numpy as np -import matplotlib.pyplot as plt -from PIL import Image -from .response_extraction import PLANE_CONFIGS -from tools.kernels import calculate_wire_count - - -def actual_to_paper_log10(actual_values): - """ - Convert from actual current values to paper's "Log 10" scale for visualization. - - This is the inverse of paper_log10_to_actual: - - For i > 10^-5: "Log 10" = log10(i * 10^5) = log10(i) + 5 - - For -10^-5 ≤ i ≤ 10^-5: "Log 10" = 0 - - For i < -10^-5: "Log 10" = -log10(abs(i) * 10^5) = -log10(abs(i)) - 5 - - Parameters - ---------- - actual_values : np.ndarray - Actual current values (electrons per time bin) - - Returns - ------- - log10_values : np.ndarray - Values in paper's "Log 10" scale - """ - log10_values = np.zeros_like(actual_values) - - # Small threshold (10^-5 in actual units corresponds to 1 in the paper scale) - threshold = 1e-5 - - # Positive values - mask_pos = actual_values > threshold - log10_values[mask_pos] = np.log10(actual_values[mask_pos] * 10**5) - - # Near-zero values - mask_zero = np.abs(actual_values) <= threshold - log10_values[mask_zero] = 0 - - # Negative values - mask_neg = actual_values < -threshold - log10_values[mask_neg] = -np.log10(-actual_values[mask_neg] * 10**5) - - return log10_values - - -def visualize_kernel(kernel, kernel_x_coords, kernel_y_coords, plane='U', figsize=(8, 8)): - """ - Visualize the extracted kernel with proper log10 conversion. - - Parameters - ---------- - kernel : np.ndarray - Kernel array in actual values - kernel_x_coords : np.ndarray - Wire coordinates for kernel - kernel_y_coords : np.ndarray - Time coordinates for kernel - plane : str - Plane name - figsize : tuple - Figure size - - Returns - ------- - fig : matplotlib.figure.Figure - Figure object - ax : matplotlib.axes.Axes - Axes object - """ - config = PLANE_CONFIGS[plane] - - fig, ax = plt.subplots(figsize=figsize) - - # Create continuous colormap - cmap = plt.cm.RdBu_r - - # Convert kernel to log10 scale for display - kernel_log10 = actual_to_paper_log10(kernel) - - # Plot kernel - im = ax.imshow(kernel_log10, aspect='auto', - extent=[kernel_x_coords[0], kernel_x_coords[-1], - kernel_y_coords[0], kernel_y_coords[-1]], - cmap=cmap, origin='lower') - - # Set axis properties - ax.set_xlabel('Wire Number', fontsize=12) - ax.set_ylabel('Time [μs]', fontsize=12) - ax.set_title(f'{config["title"]} - Extracted Kernel ({kernel.shape[0]}x{kernel.shape[1]})', - fontsize=14, pad=15) - - # Add grid - ax.grid(True, alpha=0.3, color='gray', linestyle='-', linewidth=0.5) - ax.set_axisbelow(True) - - # Add crosshairs at (0,0) - ax.axvline(x=0, color='black', linestyle='--', alpha=0.5, linewidth=1) - ax.axhline(y=0, color='black', linestyle='--', alpha=0.5, linewidth=1) - - # Create colorbar - cbar = plt.colorbar(im, ax=ax, pad=0.02, orientation='vertical') - cbar.set_label('Log 10″', rotation=270, labelpad=15, fontsize=12) - cbar.ax.tick_params(labelsize=10) - - # Set symmetric colorbar limits centered at 0 - vmax = np.max(np.abs(kernel_log10)) - im.set_clim(-vmax, vmax) - - plt.tight_layout() - return fig, ax - - -def visualize_diffusion_progression(DKernel, linear_s, x_coords, y_coords, plane='U', - figsize=(15, 3)): - """ - Visualize how kernels change with diffusion parameter s. - - Parameters - ---------- - DKernel : np.ndarray - Array of diffused kernels in actual values, shape (num_s, height, width) - linear_s : np.ndarray - Array of s values - x_coords : np.ndarray - Wire coordinates - y_coords : np.ndarray - Time coordinates - plane : str - Plane name - figsize : tuple - Figure size - - Returns - ------- - fig : matplotlib.figure.Figure - Figure object - """ - num_s = len(linear_s) - - # Show a few representative kernels - indices_to_show = [0, num_s//4, num_s//2, 3*num_s//4, num_s-1] - - fig, axes = plt.subplots(1, len(indices_to_show), figsize=figsize) - - cmap = plt.cm.RdBu_r - - # Convert all kernels to log10 and find global symmetric limits - all_kernels_log10 = [] - for idx in indices_to_show: - kernel_log10 = actual_to_paper_log10(DKernel[idx]) - all_kernels_log10.append(kernel_log10) - - # Find maximum absolute value across all kernels for symmetric colorbar - vmax = max(np.max(np.abs(k)) for k in all_kernels_log10) - vmin = -vmax - - for i, (idx, kernel_log10) in enumerate(zip(indices_to_show, all_kernels_log10)): - s_val = linear_s[idx] - - im = axes[i].imshow(kernel_log10, aspect='auto', - extent=[x_coords[0], x_coords[-1], y_coords[0], y_coords[-1]], - cmap=cmap, origin='lower', vmin=vmin, vmax=vmax) - - axes[i].set_title(f's = {s_val:.2f}') - axes[i].set_xlabel('Wire Number') - if i == 0: - axes[i].set_ylabel('Time [μs]') - - axes[i].axvline(x=0, color='black', linestyle='--', alpha=0.5) - axes[i].axhline(y=0, color='black', linestyle='--', alpha=0.5) - axes[i].grid(True, alpha=0.3) - - # No colorbar needed - the color scale is obvious from context - plt.tight_layout() - plt.suptitle(f'{plane} Plane Diffusion Progression', y=1.02) - return fig - - -def create_parameter_sweep_gif(visualization_func, DKernels, plane='Y', - parameter='w_offset', param_range=(0, 1), - fixed_params=None, output_filename='parameter_sweep.gif', - n_frames=30, fps=10): - """ - Create a GIF animation sweeping through any parameter. - - Parameters - ---------- - visualization_func : callable - Function to create visualization (e.g., visualize_interpolation_steps) - DKernels : dict - Dictionary of diffusion kernels - plane : str - Which plane to visualize - parameter : str - Which parameter to sweep ('w_offset', 's_observed', or 't_offset') - param_range : tuple - (min, max) values for the parameter - fixed_params : dict, optional - Dict of fixed parameters (defaults: s_observed=0.3, w_offset=0.25, t_offset=0.15) - output_filename : str - Name of output GIF file - n_frames : int - Number of frames for the animation - fps : int - Frames per second for the GIF - - Returns - ------- - None - Saves GIF to output_filename - """ - # Set default fixed parameters - if fixed_params is None: - fixed_params = { - 's_observed': 0.3, - 'w_offset': 0.25, - 't_offset': 0.15 - } - - # Create temporary folder for frames - temp_folder = 'temp_param_sweep_frames' - if os.path.exists(temp_folder): - shutil.rmtree(temp_folder) - os.makedirs(temp_folder) - - print(f"Creating parameter sweep GIF for {parameter}...") - print(f" Range: {param_range[0]:.3f} to {param_range[1]:.3f}") - - try: - # Create parameter values that go from min to max and back to min - half_frames = n_frames // 2 - param_values_forward = np.linspace(param_range[0], param_range[1], half_frames, endpoint=False) - param_values_backward = np.linspace(param_range[1], param_range[0], n_frames - half_frames, endpoint=True) - param_values = np.concatenate([param_values_forward, param_values_backward]) - - # Generate frames - frame_files = [] - for i, param_val in enumerate(param_values): - print(f" Generating frame {i+1}/{n_frames} ({parameter}={param_val:.3f})") - - # Set up parameters for this frame - params = fixed_params.copy() - params[parameter] = param_val - - # Create the visualization - fig = visualization_func( - DKernels, - plane=plane, - **params - ) - - if fig: - # Save frame - frame_filename = os.path.join(temp_folder, f'frame_{i:04d}.png') - plt.figure(fig.number) - plt.savefig(frame_filename, dpi=100, bbox_inches='tight') - plt.close(fig) - frame_files.append(frame_filename) - - # Create GIF from frames - print("\nCreating GIF...") - images = [] - for filename in frame_files: - images.append(Image.open(filename)) - - if images: - # Save GIF - duration = 1000 // fps - images[0].save( - output_filename, - save_all=True, - append_images=images[1:], - duration=duration, - loop=0 - ) - print(f"GIF saved as: {output_filename}") - - finally: - # Clean up temporary folder - print("\nCleaning up temporary files...") - if os.path.exists(temp_folder): - shutil.rmtree(temp_folder) - print("Done!") - - -def visualize_interpolation_steps(DKernels, plane='Y', s_observed=0.3, w_offset=0.25, t_offset=0.15, - wire_spacing=0.1, time_spacing=0.5, verbose=False): - """ - Visualize the interpolation process step by step in a 2x2 layout. - - Parameters - ---------- - DKernels : dict - Dictionary of diffusion kernels (in actual values) - plane : str - Which plane to visualize - s_observed : float - Diffusion parameter in [0, 1] - w_offset : float - Wire offset in [0, 1) - t_offset : float - Time offset in [0, 0.5) - wire_spacing : float - Wire spacing - time_spacing : float - Time spacing - verbose : bool - Print debug information - - Returns - ------- - fig : matplotlib.figure.Figure - Figure object - """ - if plane not in DKernels: - print(f"Plane {plane} not available") - return None - - DKernel, linear_s, kernel_shape, x_coords, y_coords = DKernels[plane] - kernel_height, kernel_width = kernel_shape - num_s = len(linear_s) - - # Calculate interpolation parameters - s_continuous = s_observed * (num_s - 1) - s_idx = int(np.floor(s_continuous)) - s_idx = min(s_idx, num_s - 2) - s_alpha = s_continuous - s_idx - - center_w = kernel_width // 2 - bins_per_wire = int(1.0 / wire_spacing) - w_bin_offset = w_offset * bins_per_wire - w_base_bin = int(np.floor(w_bin_offset)) - w_alpha = w_bin_offset - w_base_bin - - # Calculate wire parameters - num_wires = calculate_wire_count(kernel_width, wire_spacing) - - if num_wires % 2 == 0: - half_wires = num_wires // 2 - wire_positions = np.arange(-half_wires, half_wires) - else: - half_wires = num_wires // 2 - wire_positions = np.arange(-half_wires, half_wires + 1) - - wire_base_positions = wire_positions * bins_per_wire + center_w - actual_wire_positions = wire_base_positions + w_base_bin - - if verbose: - print(f"\nInterpolation parameters:") - print(f" s_observed={s_observed:.3f} -> s_idx={s_idx}, s_alpha={s_alpha:.3f}") - print(f" w_offset={w_offset:.3f} -> w_base_bin={w_base_bin}, w_alpha={w_alpha:.3f}") - print(f" t_offset={t_offset:.3f}") - print(f" num_wires={num_wires}, Expected output shape: ({num_wires}, {kernel_height-1})") - - # Define specific wires and colors - target_wires = [-1, 0, 1, 3, 5] - wire_colors = ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6'] # Red, Blue, Green, Orange, Purple - - # Find indices for target wires - wire_indices_to_show = [] - for target in target_wires: - idx = np.where(wire_positions == target)[0] - if len(idx) > 0: - wire_indices_to_show.append(idx[0]) - - # Extract interpolation data for selected wires - all_wire_results = [] - all_wire_steps = [] - - for wire_idx in wire_indices_to_show: - # Get the two adjacent wire bin indices for interpolation - wire_bin_left = wire_base_positions[wire_idx] + w_base_bin - wire_bin_right = wire_bin_left + 1 - - # Clamp to valid range - wire_bin_left = np.clip(wire_bin_left, 0, kernel_width - 1) - wire_bin_right = np.clip(wire_bin_right, 0, kernel_width - 1) - - # Step 1: Extract values for s interpolation - values_s_n_left = np.array(DKernel[s_idx, :, int(wire_bin_left)]) - values_s_n_plus_1_left = np.array(DKernel[s_idx + 1, :, int(wire_bin_left)]) - values_s_n_right = np.array(DKernel[s_idx, :, int(wire_bin_right)]) - values_s_n_plus_1_right = np.array(DKernel[s_idx + 1, :, int(wire_bin_right)]) - - # Step 2: S interpolation for both left and right wire positions - values_s_interp_left = (1 - s_alpha) * values_s_n_left + s_alpha * values_s_n_plus_1_left - values_s_interp_right = (1 - s_alpha) * values_s_n_right + s_alpha * values_s_n_plus_1_right - - # Step 3: Wire interpolation - values_w_interp = (1 - w_alpha) * values_s_interp_left + w_alpha * values_s_interp_right - - # Step 4: Time interpolation - t_alpha = t_offset / time_spacing - interpolated_values = (1 - t_alpha) * values_w_interp[:-1] + t_alpha * values_w_interp[1:] - - # Store results - all_wire_results.append(interpolated_values) - all_wire_steps.append({ - 'left_s_n': values_s_n_left, - 'left_s_n_plus_1': values_s_n_plus_1_left, - 'right_s_n': values_s_n_right, - 'right_s_n_plus_1': values_s_n_plus_1_right, - 'left_s_interp': values_s_interp_left, - 'right_s_interp': values_s_interp_right, - 'w_interp': values_w_interp, - 'final': interpolated_values - }) - - # Create 2x2 visualization - fig, axes = plt.subplots(2, 2, figsize=(12, 10)) - - # Create time coordinates - time_full = np.linspace(y_coords[0], y_coords[-1], kernel_height) - time_reduced = np.linspace(y_coords[0], y_coords[-1], kernel_height - 1) - - # Get wire labels for the selected wires - wire_labels = [wire_positions[i] for i in wire_indices_to_show] - - # Top left: s_n (dashed) and s_n+1 (solid) for left positions - convert to log10 for display - for i, (wire_idx, wire_label) in enumerate(zip(wire_indices_to_show, wire_labels)): - step = all_wire_steps[i] - color = wire_colors[i] - - axes[0, 0].plot(time_full, actual_to_paper_log10(step['left_s_n']), color=color, alpha=0.7, - linestyle='--') - axes[0, 0].plot(time_full, actual_to_paper_log10(step['left_s_n_plus_1']), color=color, alpha=0.7, - linestyle='-') - - axes[0, 0].set_title(f'Left positions: s[{s_idx}] (dashed) & s[{s_idx+1}] (solid)') - axes[0, 0].set_xlabel('Time [μs]') - axes[0, 0].set_ylabel('Log 10″') - axes[0, 0].grid(True, alpha=0.3) - - # Top right: After S interpolation (solid=left, dashed=right) - convert to log10 for display - for i, (wire_idx, wire_label) in enumerate(zip(wire_indices_to_show, wire_labels)): - step = all_wire_steps[i] - color = wire_colors[i] - - axes[0, 1].plot(time_full, actual_to_paper_log10(step['left_s_interp']), color=color, alpha=0.7, - linestyle='-') - axes[0, 1].plot(time_full, actual_to_paper_log10(step['right_s_interp']), color=color, alpha=0.7, - linestyle='--') - - axes[0, 1].set_title(f'After S interpolation\n(solid=left, dashed=right)') - axes[0, 1].set_xlabel('Time [μs]') - axes[0, 1].set_ylabel('Log 10″') - axes[0, 1].grid(True, alpha=0.3) - - # Bottom left: Final results - convert to log10 for display - for i, (wire_idx, wire_label) in enumerate(zip(wire_indices_to_show, wire_labels)): - step = all_wire_steps[i] - color = wire_colors[i] - - axes[1, 0].plot(time_reduced, actual_to_paper_log10(step['final']), color=color, alpha=0.8, - linewidth=2, label=f'Wire {wire_label}') - - axes[1, 0].set_title('Final Results (after all interpolations)') - axes[1, 0].set_xlabel('Time [μs]') - axes[1, 0].set_ylabel('Log 10″') - axes[1, 0].legend() - axes[1, 0].grid(True, alpha=0.3) - - # Bottom right: Full S-interpolated plane with colored lines - config = PLANE_CONFIGS[plane] - cmap = plt.cm.RdBu_r - vmin, vmax = config['value_range'] - - # Perform S interpolation on the full planes - full_s_interp = (1 - s_alpha) * DKernel[s_idx] + s_alpha * DKernel[s_idx + 1] - - # Convert to log10 for display - full_s_interp_log10 = actual_to_paper_log10(full_s_interp) - - # Plot the interpolated plane - im = axes[1, 1].imshow(full_s_interp_log10.T, aspect='auto', - extent=[y_coords[0], y_coords[-1], x_coords[0], x_coords[-1]], - cmap=cmap, origin='lower', vmin=vmin, vmax=vmax) - - # Add colored lines at the actual wire positions - for i, (wire_idx, wire_label) in enumerate(zip(wire_indices_to_show, wire_labels)): - wire_pos = actual_wire_positions[wire_idx] - if 0 <= wire_pos < kernel_width: - wire_coord = x_coords[int(wire_pos)] if int(wire_pos) < len(x_coords) else x_coords[-1] - axes[1, 1].axhline(y=wire_coord, color=wire_colors[i], alpha=0.8, - linewidth=2, label=f'Wire {wire_label}') - - axes[1, 1].set_title(f'S-interpolated plane (s={s_observed:.2f})\nwith wire positions (w_offset={w_offset:.2f})') - axes[1, 1].set_xlabel('Time [μs]') - axes[1, 1].set_ylabel('Wire Number') - axes[1, 1].legend(loc='upper right', fontsize=8) - axes[1, 1].grid(True, alpha=0.3) - - plt.tight_layout() - - return fig \ No newline at end of file diff --git a/closure/archive/gradient_test/gradient_test/tools/simulation.py b/closure/archive/gradient_test/gradient_test/tools/simulation.py deleted file mode 100644 index f0444f0..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/simulation.py +++ /dev/null @@ -1,938 +0,0 @@ -""" -Detector simulation module with dual output paths and per-side padding. - -This module provides the DetectorSimulator class that runs TWO parallel physics -simulation paths simultaneously: - -Response Path: - Generates detector response signals using pre-computed kernels - convolved with diffusion. Output: response_signals - -Hit Path: - Calculates diffused charge without response convolution. - Tracks which particle contributed to each location. - Output: track_hits - -V2 Changes: - - Per-side padding with tier system (east/west split before JIT) - - Automatic data splitting and padding inside process_event - - Pre-simulation and post-simulation validation - - No more manual padding in notebooks -""" - -import jax -import jax.numpy as jnp -import numpy as np -import time -import traceback -import os -from functools import partial - -# Config classes -from tools.config import ( - DepositData, DriftParams, TimeParams, PlaneGeometry, - DiffusionParams, TrackHitsConfig, - create_diffusion_params, create_drift_params, create_time_params, - create_plane_geometry, create_track_hits_config -) - -# Core physics modules -from tools.drift import ( - compute_drift_to_plane, - correct_drift_for_plane, - compute_lifetime_attenuation -) - -# Wire calculation functions -from tools.wires import ( - # Shared wire calculations - compute_wire_distances, - compute_angular_scaling, compute_angular_scaling_vmap, - compute_deposit_wire_angles, compute_deposit_wire_angles_vmap, - - # Response path functions - prepare_deposit_for_response, - accumulate_response_signals, - - # Bucketed accumulation (sparse) - accumulate_response_signals_sparse_bucketed, - sparse_buckets_to_dense, - - # Hit path functions (with K_wire x K_time diffusion) - compute_gaussian_diffusion, - prepare_deposit_with_diffusion, - accumulate_signals -) - -# Response kernel system (for response path) -from tools.kernels import load_response_kernels, apply_diffusion_response - -# Track labeling system (for hit path) -from tools.track_hits import group_hits_by_track, label_hits - -# Core modules -from tools.geometry import generate_detector -from tools.loader import load_particle_step_data -from tools.recombination import recombine_steps - - -# ============================================================================= -# PADDING TIER SYSTEM -# ============================================================================= - -# Default padding tiers - array sizes that trigger JIT recompilation -# Using fixed tiers limits the number of JIT versions cached -PADDING_TIERS = (50_000, 200_000) - - -def pick_padding_tier(n_hits, tiers=PADDING_TIERS): - """ - Pick the smallest tier that fits the data. - - Parameters - ---------- - n_hits : int - Actual number of hits to fit. - tiers : tuple of int - Available tier sizes. - - Returns - ------- - int - Selected tier size. - """ - for tier in tiers: - if n_hits <= tier: - return tier - print(f"ERROR: n_hits ({n_hits:,}) exceeds largest tier ({tiers[-1]:,}). Data will be truncated!") - return tiers[-1] - - -# ============================================================================= -# DETECTOR SIMULATOR CLASS -# ============================================================================= - -class DetectorSimulator: - """ - LArTPC detector simulation with dual output paths and per-side padding. - - Produces: - - response_signals: Full detector simulation with response kernels - - track_hits: Track labeling information for analysis - - V2 Features: - - Automatic splitting of data by detector side (east x<0, west x>=0) - - Per-side padding using tier system to minimize JIT recompilations - - Built-in pre/post simulation validation - - No manual padding required from notebooks - - Parameters - ---------- - detector_config : dict - Detector configuration from generate_detector(). - response_path : str - Path to response kernel files. - track_config : TrackHitsConfig, optional - Configuration for track labeling. If None, uses defaults. - diffusion_params : DiffusionParams, optional - Diffusion parameters. If None, computed from config. - padding_tiers : tuple of int, optional - Available padding tier sizes. Default: (50_000, 150_000, 350_000, 750_000) - use_bucketed : bool - If True, use sparse bucketed accumulation for very large detectors. - max_active_buckets : int - Max active buckets for sparse mode. Default 1000. - """ - - def __init__( - self, - detector_config, - response_path="tools/responses/", - track_config=None, - diffusion_params=None, - padding_tiers=PADDING_TIERS, - use_bucketed=False, - max_active_buckets=1000 - ): - print("--- Creating DetectorSimulator (V2 - Per-Side Padding) ---") - - # Store config - self.detector_config = detector_config - self.padding_tiers = padding_tiers - self.use_bucketed = use_bucketed - self.sparse_output = use_bucketed # sparse_output is True when use_bucketed is True - self.max_active_buckets = max_active_buckets - - # Extract parameter bundles - print(" Extracting parameters...") - self.drift_params = create_drift_params(detector_config) - self.time_params = create_time_params(detector_config) - - # Create plane geometry for all planes - self.plane_names = [ - ['U', 'V', 'Y'], # Side 0 (East, x < 0) - ['U', 'V', 'Y'] # Side 1 (West, x >= 0) - ] - self.plane_geometry = {} - for side_idx in range(2): - for plane_idx in range(3): - plane_type = self.plane_names[side_idx][plane_idx] - self.plane_geometry[(side_idx, plane_idx)] = create_plane_geometry( - detector_config, side_idx, plane_idx, plane_type - ) - - # Create or use provided diffusion params - if diffusion_params is None: - self.diffusion_params = create_diffusion_params( - max_sigma_trans_unitless=detector_config['max_sigma_trans_unitless'], - max_sigma_long_unitless=detector_config['max_sigma_long_unitless'], - num_s=16, - n_sigma=3.0 - ) - else: - self.diffusion_params = diffusion_params - - # Create or use provided track config - if track_config is None: - max_wires = max( - np.max(detector_config['max_wire_indices_abs']) - - np.min(detector_config['min_wire_indices_abs']) + 1, - 2000 - ) - self.track_config = create_track_hits_config( - threshold=1.0, - max_tracks=10000, - max_keys=500000 - ) - self._max_wires = int(max_wires) - self._max_time = self.time_params.num_steps - else: - self.track_config = track_config - self._max_wires = 2000 # Default - self._max_time = self.time_params.num_steps - - # Load response kernels - print(" Loading response kernels...") - self.response_kernels = load_response_kernels( - response_path=response_path, - num_s=self.diffusion_params.num_s, - wire_spacing=0.1, # Fixed kernel bin spacing - time_spacing=float(self.time_params.step_size_us), - max_sigma_trans_unitless=self.diffusion_params.max_sigma_trans_unitless, - max_sigma_long_unitless=self.diffusion_params.max_sigma_long_unitless - ) - - # Extract static arrays for JIT - self._prepare_static_args() - - # Build the JIT-compiled calculator - self._build_calculator() - - print(f" Config: tiers={padding_tiers}, num_s={self.diffusion_params.num_s}, " - f"K_wire={self.diffusion_params.K_wire}, K_time={self.diffusion_params.K_time}") - if use_bucketed: - print(f" Using BUCKETED accumulation (B=2*kernel, max_buckets={max_active_buckets})") - print("--- DetectorSimulator Ready ---") - - def _prepare_static_args(self): - """Prepare static arguments for JIT compilation.""" - # Convert arrays to hashable tuples for static args - index_offsets = np.array(self.detector_config['index_offsets']) - max_indices = np.array(self.detector_config['max_wire_indices_abs']) - min_indices = np.array(self.detector_config['min_wire_indices_abs']) - num_wires = np.array(self.detector_config['num_wires_actual']) - - self._index_offsets_tuple = tuple(tuple(int(x) for x in row) for row in index_offsets) - self._max_indices_tuple = tuple(tuple(int(x) for x in row) for row in max_indices) - self._min_indices_tuple = tuple(tuple(int(x) for x in row) for row in min_indices) - self._num_wires_tuple = tuple(tuple(int(x) for x in row) for row in num_wires) - - def _split_and_pad_data(self, deposit_data: DepositData): - """ - Split deposit data by side and pad to appropriate tiers. - - Parameters - ---------- - deposit_data : DepositData - Input data (can be any size, will be split and padded). - - Returns - ------- - east_data : DepositData - Padded data for east side (x < 0). - west_data : DepositData - Padded data for west side (x >= 0). - counts : dict - Actual counts: n_east, n_west, n_tracks. - """ - positions_mm = deposit_data.positions_mm - charges = deposit_data.charges - valid_mask = deposit_data.valid_mask - theta = deposit_data.theta - phi = deposit_data.phi - track_ids = deposit_data.track_ids - - # Only consider valid entries - x_mm = positions_mm[:, 0] - east_mask = valid_mask & (x_mm < 0) - west_mask = valid_mask & (x_mm >= 0) - - n_east = int(jnp.sum(east_mask)) - n_west = int(jnp.sum(west_mask)) - n_tracks = int(len(jnp.unique(track_ids[valid_mask]))) - - # Pick tiers - east_tier = pick_padding_tier(n_east, self.padding_tiers) - west_tier = pick_padding_tier(n_west, self.padding_tiers) - - print(f" East side: {n_east:,} hits -> tier {east_tier:,}") - print(f" West side: {n_west:,} hits -> tier {west_tier:,}") - - # Extract and pad each side - east_data = self._extract_and_pad( - positions_mm, charges, theta, phi, track_ids, - east_mask, n_east, east_tier - ) - west_data = self._extract_and_pad( - positions_mm, charges, theta, phi, track_ids, - west_mask, n_west, west_tier - ) - - counts = {'n_east': n_east, 'n_west': n_west, 'n_tracks': n_tracks} - return east_data, west_data, counts - - def _extract_and_pad(self, positions_mm, charges, theta, phi, track_ids, - mask, n_valid, pad_size): - """Extract masked data and pad to target size.""" - # Extract valid entries - pos = positions_mm[mask] - chg = charges[mask] - th = theta[mask] - ph = phi[mask] - tid = track_ids[mask] - - # Pad to tier size - pad_width = pad_size - n_valid - - if pad_width > 0: - valid_out = jnp.arange(pad_size) < n_valid - pos = jnp.pad(pos, ((0, pad_width), (0, 0)), constant_values=0.0) - chg = jnp.pad(chg, (0, pad_width), constant_values=0.0) - th = jnp.pad(th, (0, pad_width), constant_values=0.0) - ph = jnp.pad(ph, (0, pad_width), constant_values=0.0) - tid = jnp.pad(tid, (0, pad_width), constant_values=0) - else: - # Truncate if needed (shouldn't happen if tier picked correctly) - valid_out = jnp.ones(pad_size, dtype=bool) - pos = pos[:pad_size] - chg = chg[:pad_size] - th = th[:pad_size] - ph = ph[:pad_size] - tid = tid[:pad_size] - - return DepositData( - positions_mm=pos, - charges=chg, - valid_mask=valid_out, - theta=th, - phi=ph, - track_ids=tid - ) - - def _validate_pre_simulation(self, counts): - """Check inputs before running simulation.""" - if self.track_config.max_tracks < counts['n_tracks']: - print(f"ERROR: max_tracks ({self.track_config.max_tracks:,}) < unique tracks ({counts['n_tracks']:,}). Tracks may be lost!") - - def _validate_post_simulation(self, track_hits, response_signals): - """Check for truncation after simulation.""" - for plane_key, th in track_hits.items(): - actual_hits = int(th['num_hits']) - if actual_hits >= self.track_config.max_keys: - print(f"ERROR: Plane {plane_key}: num_hits ({actual_hits:,}) >= max_keys ({self.track_config.max_keys:,}). Data truncated!") - - if self.use_bucketed: - for plane_key, resp in response_signals.items(): - buckets, num_active, compact_to_key, B1, B2 = resp - if int(num_active) >= self.max_active_buckets: - print(f"ERROR: Plane {plane_key}: num_active ({int(num_active):,}) >= max_active_buckets ({self.max_active_buckets:,}). Data truncated!") - - def _build_calculator(self): - """Build the JIT-compiled signal calculator.""" - # Extract all needed parameters - num_time_steps = self.time_params.num_steps - time_step_size_us = self.time_params.step_size_us - detector_half_width_cm = self.drift_params.detector_half_width_cm - velocity_cm_us = self.drift_params.velocity_cm_us - lifetime_us = self.drift_params.lifetime_us - diffusion_long_cm2_us = self.drift_params.diffusion_long_cm2_us - diffusion_trans_cm2_us = self.drift_params.diffusion_trans_cm2_us - - K_wire = self.diffusion_params.K_wire - K_time = self.diffusion_params.K_time - - all_plane_distances_cm = self.detector_config['all_plane_distances_cm'] - furthest_plane_indices = self.detector_config['furthest_plane_indices'] - angles_rad = self.detector_config['angles_rad'] - wire_spacings_cm = self.detector_config['wire_spacings_cm'] - - plane_names = self.plane_names - response_kernels = self.response_kernels - track_threshold = self.track_config.threshold - - max_tracks = self.track_config.max_tracks - max_wires = self._max_wires - max_time = self._max_time - max_keys = self.track_config.max_keys - - # Static tuples - index_offsets_tuple = self._index_offsets_tuple - max_indices_tuple = self._max_indices_tuple - min_indices_tuple = self._min_indices_tuple - num_wires_tuple = self._num_wires_tuple - - # Choose accumulation function based on mode - if self.use_bucketed: - max_buckets = self.max_active_buckets - sparse_output = self.sparse_output - - def accumulate_fn(wire_idx, time_idx, intensities, contributions, - num_wires_plane, num_time_steps, kernel_num_wires, kernel_height): - # Use sparse bucketing with two-phase algorithm - buckets, num_active, compact_to_key = accumulate_response_signals_sparse_bucketed( - wire_idx, time_idx, intensities, contributions, - num_wires_plane, num_time_steps, kernel_num_wires, kernel_height, - max_buckets - ) - - if sparse_output: - B1 = 2 * kernel_num_wires - B2 = 2 * kernel_height - return (buckets, num_active, compact_to_key, B1, B2) - else: - B1 = 2 * kernel_num_wires - B2 = 2 * kernel_height - return sparse_buckets_to_dense( - buckets, compact_to_key, num_active, - B1, B2, num_wires_plane, num_time_steps, max_buckets - ) - - else: - def accumulate_fn(wire_idx, time_idx, intensities, contributions, - num_wires_plane, num_time_steps, kernel_num_wires, kernel_height): - return accumulate_response_signals( - wire_idx, time_idx, intensities, contributions, - num_wires_plane, num_time_steps, kernel_num_wires, kernel_height - ) - - @partial(jax.jit, static_argnames=( - 'max_hits_east', 'max_hits_west', # Per-side padding sizes - 'max_wire_indices_tuple', 'min_wire_indices_tuple', - 'index_offsets_tuple', 'num_wires_tuple', - 'max_tracks', 'max_wires', 'max_time', 'max_keys' - )) - def _calculate_signals_jit( - # East side inputs (side 0, x < 0) - east_positions_mm, east_charges, east_valid_mask, - east_theta, east_phi, east_track_ids, - # West side inputs (side 1, x >= 0) - west_positions_mm, west_charges, west_valid_mask, - west_theta, west_phi, west_track_ids, - # Static args - max_hits_east, max_hits_west, - max_wire_indices_tuple, min_wire_indices_tuple, - index_offsets_tuple, num_wires_tuple, - max_tracks, max_wires, max_time, max_keys - ): - """JIT-compiled calculator with separate per-side data.""" - - # Results lists - response_signals_list = [] - track_hits_list = [] - - for side_idx in range(2): - # Select data for this side - no masking needed, already split! - if side_idx == 0: # East (x < 0) - positions_mm = east_positions_mm - charges = east_charges - valid_mask = east_valid_mask - theta = east_theta - phi = east_phi - track_ids = east_track_ids - else: # West (x >= 0) - positions_mm = west_positions_mm - charges = west_charges - valid_mask = west_valid_mask - theta = west_theta - phi = west_phi - track_ids = west_track_ids - - # Convert positions to cm - positions_cm = positions_mm / 10.0 - - # Calculate drift for the furthest plane on this side - furthest_plane_idx = furthest_plane_indices[side_idx] - furthest_plane_dist_cm = all_plane_distances_cm[side_idx, furthest_plane_idx] - - # Drift to furthest plane - furthest_drift_distance_cm, furthest_drift_time_us, positions_yz_cm = compute_drift_to_plane( - positions_cm, - detector_half_width_cm, - velocity_cm_us, - furthest_plane_dist_cm - ) - - for plane_idx in range(3): - # Get plane parameters - plane_dist_cm = all_plane_distances_cm[side_idx, plane_idx] - angle_rad = angles_rad[side_idx, plane_idx] - spacing_cm = wire_spacings_cm[side_idx, plane_idx] - offset = index_offsets_tuple[side_idx][plane_idx] - max_idx_abs = max_wire_indices_tuple[side_idx][plane_idx] - min_idx_abs = min_wire_indices_tuple[side_idx][plane_idx] - num_wires_plane = num_wires_tuple[side_idx][plane_idx] - plane_type = plane_names[side_idx][plane_idx] - - # --- Shared Preprocessing --- - # Correct drift for this plane - plane_dist_difference_cm = furthest_plane_dist_cm - plane_dist_cm - drift_distance_cm, drift_time_us = correct_drift_for_plane( - furthest_drift_distance_cm, - furthest_drift_time_us, - velocity_cm_us, - plane_dist_difference_cm - ) - - # Calculate attenuation - electron_lifetime_us = lifetime_us - drift_time_us_safe = jnp.where(jnp.isnan(drift_time_us), 0.0, drift_time_us) - attenuation_factors = jnp.exp(-drift_time_us_safe / electron_lifetime_us) - - # Calculate closest wire distances - closest_wire_idx, closest_wire_distances = compute_wire_distances( - positions_yz_cm, angle_rad, spacing_cm, - max_idx_abs, offset - ) - - # Calculate angles - theta_xz, theta_y = compute_deposit_wire_angles_vmap( - theta, phi, angle_rad - ) - - # --- HIT PATH --- - # Angular scaling factor - angular_scaling_factor = compute_angular_scaling_vmap(theta_xz, theta_y) - - # Process deposits with diffusion - prepare_deposit_vmap_hit = jax.vmap( - prepare_deposit_with_diffusion, - in_axes=(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, None, None, None, None, - None, None, None, None, None, None), - ) - - hit_deposit_data = prepare_deposit_vmap_hit( - charges, # No more side_charges - data already split - drift_time_us, - drift_distance_cm, - closest_wire_idx, - closest_wire_distances, - attenuation_factors, - theta_xz, - theta_y, - angular_scaling_factor, - valid_mask, # No more valid_side_mask - data already split - K_wire, - K_time, - spacing_cm, - time_step_size_us, - diffusion_long_cm2_us, - diffusion_trans_cm2_us, - velocity_cm_us, - min_idx_abs, - num_wires_plane, - num_time_steps - ) - - # Track labeling - wire_indices_rel, time_indices, signal_values = hit_deposit_data - - # Convert relative wire indices back to absolute - wire_indices_abs = wire_indices_rel + min_idx_abs - - # Expand track IDs to match the deposit data structure - K_total = (2 * K_wire + 1) * (2 * K_time + 1) - track_ids_expanded = jnp.repeat(track_ids[:, jnp.newaxis], K_total, axis=1) - - # Flatten arrays for track labeling - wire_indices_flat = wire_indices_abs.flatten() - time_indices_flat = time_indices.flatten() - track_ids_flat = track_ids_expanded.flatten() - charges_flat = signal_values.flatten() - - # Create wire_time_indices array - wire_time_indices = jnp.stack([ - wire_indices_flat, - time_indices_flat - ], axis=1) - - # Group hits by track - (hits_by_track, num_hits, - track_boundaries, num_tracks, - track_ids_arr) = group_hits_by_track( - wire_time_indices, - track_ids_flat, - charges_flat, - min_charge_threshold=track_threshold, - max_tracks=max_tracks, - max_wires=max_wires, - max_time=max_time, - max_keys=max_keys - ) - - # Label hits (dominant track per wire,time) - num_stored = jnp.minimum(num_hits, max_keys) - labeled_hits, num_labeled = label_hits( - hits_by_track, num_stored, - track_ids_arr, - track_boundaries, num_tracks, - max_keys=max_keys, max_time=max_time - ) - - track_hit_result = { - 'labeled_hits': labeled_hits, - 'num_labeled': num_labeled, - 'hits_by_track': hits_by_track, - 'track_boundaries': track_boundaries, - 'num_hits': num_hits, - 'num_tracks': num_tracks, - 'track_ids': track_ids_arr, - } - - # --- RESPONSE PATH --- - # Calculate s parameter for diffusion - total_travel_distance_cm = detector_half_width_cm - s_values = drift_distance_cm / total_travel_distance_cm - s_values = jnp.clip(s_values, 0.0, 1.0) - - # Process deposits for response path - prepare_deposit_vmap_response = jax.vmap( - prepare_deposit_for_response, - in_axes=(0, 0, 0, 0, 0, 0, None, None, None, None), - ) - - deposit_data_kernel = prepare_deposit_vmap_response( - charges, # No more side_charges - drift_time_us, - closest_wire_idx, - closest_wire_distances, - attenuation_factors, - valid_mask, # No more valid_side_mask - spacing_cm, - time_step_size_us, - min_idx_abs, - num_wires_plane - ) - - wire_indices_rel_kernel, wire_offsets, time_indices_kernel, time_offsets, intensities = deposit_data_kernel - - # Apply diffusion response kernels - plane_kernel = response_kernels[plane_type] - DKernel = plane_kernel['DKernel'] - kernel_num_wires = plane_kernel['num_wires'] - kernel_height = plane_kernel['kernel_height'] - kernel_wire_stride = plane_kernel['wire_stride'] - kernel_wire_spacing = plane_kernel['wire_spacing'] - kernel_time_spacing = plane_kernel['time_spacing'] - - # Get kernel contributions - kernel_contributions = apply_diffusion_response( - DKernel, s_values, wire_offsets, time_offsets, - kernel_wire_stride, kernel_wire_spacing, kernel_time_spacing, kernel_num_wires - ) - - # Accumulate response signals - response_signal = accumulate_fn( - wire_indices_rel_kernel, time_indices_kernel, intensities, kernel_contributions, - num_wires_plane, num_time_steps, kernel_num_wires, kernel_height - ) - - # Store results - response_signals_list.append(response_signal) - track_hits_list.append(track_hit_result) - - return tuple(response_signals_list), tuple(track_hits_list) - - # Store raw JIT function (static args bound at call time based on tier) - self._calculator_jit_raw = _calculate_signals_jit - - def __call__(self, deposit_data: DepositData): - """Process deposits through both paths.""" - return self.process_event(deposit_data) - - def process_event(self, deposit_data: DepositData): - """ - Process a single event through both simulation paths. - - Handles splitting by side and padding internally. - - Parameters - ---------- - deposit_data : DepositData - Input data containing positions, charges, and track IDs. - Can be any size - will be split and padded to tiers internally. - - Returns - ------- - response_signals : dict[(side, plane)] -> jnp.ndarray or sparse tuple - Full detector response (W × T) for each plane. - track_hits : dict[(side, plane)] -> dict - Track labeling information for each plane. - """ - # Split and pad data by side - print(" Splitting and padding data by side...") - east_data, west_data, counts = self._split_and_pad_data(deposit_data) - - # Pre-simulation validation - self._validate_pre_simulation(counts) - - # Get tier sizes (become static args) - max_hits_east = east_data.positions_mm.shape[0] - max_hits_west = west_data.positions_mm.shape[0] - - # Call JIT-compiled calculator - response_tuple, track_hits_tuple = self._calculator_jit_raw( - # East data - east_data.positions_mm, east_data.charges, east_data.valid_mask, - east_data.theta, east_data.phi, east_data.track_ids, - # West data - west_data.positions_mm, west_data.charges, west_data.valid_mask, - west_data.theta, west_data.phi, west_data.track_ids, - # Static args - max_hits_east=max_hits_east, - max_hits_west=max_hits_west, - max_wire_indices_tuple=self._max_indices_tuple, - min_wire_indices_tuple=self._min_indices_tuple, - index_offsets_tuple=self._index_offsets_tuple, - num_wires_tuple=self._num_wires_tuple, - max_tracks=self.track_config.max_tracks, - max_wires=self._max_wires, - max_time=self._max_time, - max_keys=self.track_config.max_keys - ) - - # Convert tuples to dictionaries - response_signals = {} - track_hits = {} - - idx = 0 - for side_idx in range(2): - for plane_idx in range(3): - response_signals[(side_idx, plane_idx)] = response_tuple[idx] - track_hits[(side_idx, plane_idx)] = track_hits_tuple[idx] - idx += 1 - - # Post-process track hits with proper boundary extraction - for plane_key, track_result in track_hits.items(): - num_hits = track_result['num_hits'] - num_labeled = track_result['num_labeled'] - num_tracks = track_result['num_tracks'] - - # Extract valid portions - track_result['hits_by_track'] = track_result['hits_by_track'][:num_hits] - track_result['labeled_hits'] = track_result['labeled_hits'][:num_labeled] - track_result['track_boundaries'] = track_result['track_boundaries'][:num_tracks] - - # Post-simulation validation - self._validate_post_simulation(track_hits, response_signals) - - return response_signals, track_hits - - def warm_up(self): - """Trigger JIT compilation with dummy data for smallest tier.""" - print("Triggering JIT compilation...") - - # Warm up with smallest tier (fast) - min_tier = self.padding_tiers[0] - - dummy_east = DepositData( - positions_mm=jnp.zeros((min_tier, 3), dtype=jnp.float32), - charges=jnp.zeros((min_tier,), dtype=jnp.float32), - valid_mask=jnp.zeros((min_tier,), dtype=bool), - theta=jnp.zeros((min_tier,), dtype=jnp.float32), - phi=jnp.zeros((min_tier,), dtype=jnp.float32), - track_ids=jnp.zeros((min_tier,), dtype=jnp.int32) - ) - dummy_west = DepositData( - positions_mm=jnp.zeros((min_tier, 3), dtype=jnp.float32), - charges=jnp.zeros((min_tier,), dtype=jnp.float32), - valid_mask=jnp.zeros((min_tier,), dtype=bool), - theta=jnp.zeros((min_tier,), dtype=jnp.float32), - phi=jnp.zeros((min_tier,), dtype=jnp.float32), - track_ids=jnp.zeros((min_tier,), dtype=jnp.int32) - ) - - # Call directly to avoid split/pad logic - _ = self._calculator_jit_raw( - dummy_east.positions_mm, dummy_east.charges, dummy_east.valid_mask, - dummy_east.theta, dummy_east.phi, dummy_east.track_ids, - dummy_west.positions_mm, dummy_west.charges, dummy_west.valid_mask, - dummy_west.theta, dummy_west.phi, dummy_west.track_ids, - max_hits_east=min_tier, - max_hits_west=min_tier, - max_wire_indices_tuple=self._max_indices_tuple, - min_wire_indices_tuple=self._min_indices_tuple, - index_offsets_tuple=self._index_offsets_tuple, - num_wires_tuple=self._num_wires_tuple, - max_tracks=self.track_config.max_tracks, - max_wires=self._max_wires, - max_time=self._max_time, - max_keys=self.track_config.max_keys - ) - print(f"JIT compilation finished (tier {min_tier:,}). Other tiers compile on first use.") - - -# ============================================================================= -# CONVENIENCE FUNCTION -# ============================================================================= - -def run_simulation(config_path, data_path, event_idx=0, - num_s=16, - response_path="tools/responses/", - track_threshold=1.0, - padding_tiers=PADDING_TIERS): - """ - Run the detector simulation for a specific event. - - Convenience function that creates a DetectorSimulator and processes one event. - Uses automatic per-side padding. - - Parameters - ---------- - config_path : str - Path to detector configuration YAML file. - data_path : str - Path to particle step data HDF5 file. - event_idx : int, optional - Index of event to process, by default 0. - num_s : int, optional - Number of diffusion levels in kernel interpolation, by default 16. - response_path : str, optional - Path to wire response kernel data. - track_threshold : float, optional - Minimum charge threshold for track labeling, by default 1.0. - padding_tiers : tuple of int, optional - Available padding tier sizes. - - Returns - ------- - response_signals : dict - Wire signals with detector response, keyed by (side_idx, plane_idx). - track_hits : dict - Track labeling results, keyed by (side_idx, plane_idx). - simulator : DetectorSimulator - The simulator instance (for reuse with additional events). - """ - print("="*60) - print(" LArTPC Detector Simulation (V2 - Per-Side Padding)") - print("="*60) - print(f"Config: {config_path}, Data: {data_path} (Event {event_idx})") - - # Load configuration - if not os.path.exists(config_path): - raise FileNotFoundError(f"Config file not found: {config_path}") - - try: - detector_config = generate_detector(config_path) - if detector_config is None: - raise ValueError(f"Error loading detector configuration from {config_path}") - print(f"Successfully loaded detector config from {config_path}") - except Exception as e: - print(f"ERROR loading config file '{config_path}': {e}") - traceback.print_exc() - raise - - # Create diffusion params - diffusion_params = create_diffusion_params( - max_sigma_trans_unitless=detector_config['max_sigma_trans_unitless'], - max_sigma_long_unitless=detector_config['max_sigma_long_unitless'], - num_s=num_s, - n_sigma=3.0 - ) - - # Create track config - track_config = create_track_hits_config(threshold=track_threshold) - - # Create simulator - try: - simulator = DetectorSimulator( - detector_config, - response_path=response_path, - track_config=track_config, - diffusion_params=diffusion_params, - padding_tiers=padding_tiers - ) - simulator.warm_up() - except Exception as e: - print(f"\n--- Error during simulator creation: ---") - traceback.print_exc() - raise - - # Process event - try: - print(f"\n--- Processing Event {event_idx} ---") - step_data = load_particle_step_data(data_path, event_idx) - event_positions_mm = jnp.asarray(step_data.get('position', jnp.empty((0, 3))), dtype=jnp.float32) - - n_hits = event_positions_mm.shape[0] - print(f"Loaded {n_hits:,} steps from event {event_idx}.") - - if n_hits == 0: - print("WARNING: Event contains no particle steps.") - return {}, {}, simulator - - # Get recombined charge - recomb_charge = recombine_steps(step_data, detector_config) - recomb_charge = jnp.asarray(recomb_charge, dtype=jnp.float32) - - # Extract angles and track IDs - event_theta = jnp.asarray(step_data.get('theta', jnp.zeros((n_hits,))), dtype=jnp.float32) - event_phi = jnp.asarray(step_data.get('phi', jnp.zeros((n_hits,))), dtype=jnp.float32) - event_track_ids = jnp.asarray(step_data.get('track_id', jnp.ones((n_hits,))), dtype=jnp.int32) - - print(f"Unique tracks: {len(jnp.unique(event_track_ids)):,}") - - # Create deposit data (no manual padding needed!) - deposit_data = DepositData( - positions_mm=event_positions_mm, - charges=recomb_charge, - valid_mask=jnp.ones(n_hits, dtype=bool), - theta=event_theta, - phi=event_phi, - track_ids=event_track_ids - ) - - # Run simulation (splitting and padding handled internally) - print("Running simulation...") - response_signals, track_hits = simulator(deposit_data) - - # Ensure calculations complete - for key, arr in response_signals.items(): - if arr is not None: - if isinstance(arr, tuple): - jax.block_until_ready(arr[0]) - else: - jax.block_until_ready(arr) - - print("\nSimulation complete.") - print("Track labeling results:") - for plane_key, results in track_hits.items(): - num_labeled = results['num_labeled'] - num_hits = results['num_hits'] - print(f" Plane {plane_key}: {num_labeled} labeled hits, {num_hits} total hits") - - return response_signals, track_hits, simulator - - except Exception as e: - print(f"\n--- Error during event processing: ---") - traceback.print_exc() - raise diff --git a/closure/archive/gradient_test/gradient_test/tools/sparse_utils.py b/closure/archive/gradient_test/gradient_test/tools/sparse_utils.py deleted file mode 100644 index 1af061a..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/sparse_utils.py +++ /dev/null @@ -1,143 +0,0 @@ -""" -Sparse utilities for converting between dense, bucket, and truly sparse formats. - -This module provides functions for converting wire signals between different -storage formats: dense arrays, sparse buckets, and truly sparse (indices, values). - -Truly sparse format: - - indices: (N, 2) int32 array with [wire_idx, time_idx] per row - - values: (N,) float32 array with signal values -""" - -import jax.numpy as jnp -import numpy as np - - -def dense_to_sparse(dense_array, threshold=0.0): - """ - Convert dense (num_wires, num_time_steps) array to sparse format. - - Parameters - ---------- - dense_array : jnp.ndarray - Array of shape (num_wires, num_time_steps) containing signal values. - threshold : float, optional - Only include values with |value| > threshold (keeps sign), by default 0.0. - - Returns - ------- - indices : jnp.ndarray - Array of shape (N, 2) with [wire_idx, time_idx] per row. - values : jnp.ndarray - Array of shape (N,) with signal values (preserves sign). - """ - # Use absolute value for threshold check, but keep original signed values - mask = jnp.abs(dense_array) > threshold - wire_indices, time_indices = jnp.where(mask) - indices = jnp.stack([wire_indices, time_indices], axis=1) - values = dense_array[mask] - return indices.astype(jnp.int32), values.astype(jnp.float32) - - -def sparse_buckets_to_sparse(buckets, compact_to_key, num_active, - B1, B2, num_wires, num_time_steps, - threshold=0.0): - """ - Convert sparse buckets format directly to truly sparse (indices, values). - - Parameters - ---------- - buckets : jnp.ndarray - Array of shape (max_buckets, B1, B2) containing bucket data. - compact_to_key : jnp.ndarray - Array of shape (max_buckets,) mapping compact index to bucket keys. - num_active : int - Number of active buckets. - B1 : int - Bucket dimension in wire direction. - B2 : int - Bucket dimension in time direction. - num_wires : int - Total number of wires in detector. - num_time_steps : int - Total number of time steps in detector. - threshold : float, optional - Only include values with |value| > threshold (keeps sign), by default 0.0. - - Returns - ------- - indices : jnp.ndarray - Array of shape (N, 2) with [wire_idx, time_idx] per row. - values : jnp.ndarray - Array of shape (N,) with signal values (preserves sign). - """ - NUM_BUCKETS_T = (num_time_steps + B2 - 1) // B2 - - all_indices = [] - all_values = [] - - for i in range(int(num_active)): - key = int(compact_to_key[i]) - bucket_w = key // NUM_BUCKETS_T - bucket_t = key % NUM_BUCKETS_T - - w_start = bucket_w * B1 - t_start = bucket_t * B2 - - bucket_data = np.array(buckets[i]) - # Use absolute value for threshold check, but keep original signed values - mask = np.abs(bucket_data) > threshold - local_w, local_t = np.where(mask) - - global_w = w_start + local_w - global_t = t_start + local_t - - # Filter to valid detector range - valid = (global_w < num_wires) & (global_t < num_time_steps) - - if np.any(valid): - all_indices.append(np.stack([global_w[valid], global_t[valid]], axis=1)) - all_values.append(bucket_data[mask][valid]) - - if all_indices: - indices = np.concatenate(all_indices, axis=0) - values = np.concatenate(all_values, axis=0) - else: - indices = np.empty((0, 2), dtype=np.int32) - values = np.empty((0,), dtype=np.float32) - - return jnp.array(indices, dtype=jnp.int32), jnp.array(values, dtype=jnp.float32) - - -def sparse_to_dense(indices, values, num_wires, num_time_steps): - """ - Convert sparse (indices, values) format to dense array using .at.add. - - Parameters - ---------- - indices : jnp.ndarray - Array of shape (N, 2) with [wire_idx, time_idx] per row. - values : jnp.ndarray - Array of shape (N,) with signal values. - num_wires : int - Number of wires in output array. - num_time_steps : int - Number of time steps in output array. - - Returns - ------- - dense : jnp.ndarray - Array of shape (num_wires, num_time_steps) with accumulated values. - """ - dense = jnp.zeros((num_wires, num_time_steps), dtype=jnp.float32) - - if len(indices) == 0: - return dense - - wire_idx = indices[:, 0] - time_idx = indices[:, 1] - - # Use .at.add to handle duplicate indices (sum contributions) - dense = dense.at[wire_idx, time_idx].add(values) - - return dense diff --git a/closure/archive/gradient_test/gradient_test/tools/track_hits.py b/closure/archive/gradient_test/gradient_test/tools/track_hits.py deleted file mode 100644 index 7aa0ca8..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/track_hits.py +++ /dev/null @@ -1,262 +0,0 @@ -""" -Track hit labeling module for LArTPC simulation. - -This module provides functions to track which particles (tracks) contribute -to each wire signal in the detector simulation. It uses a K_wire x K_time -neighbor system to aggregate charge deposits and determine the dominant -contributor at each (wire, time) location. - -The track labeling runs in parallel with the main simulation to provide -particle attribution data for physics analysis. -""" - -import jax -import jax.numpy as jnp -from functools import partial - - -@partial(jax.jit, static_argnames=['max_tracks', 'max_wires', 'max_time', 'max_keys']) -def group_hits_by_track(wire_time_indices, track_ids, charge_deposits, - min_charge_threshold=0.0, - max_tracks=10000, max_wires=2000, max_time=2000, - max_keys=1000000): - """ - Aggregate charge deposits by track and location for LArTPC simulation data. - - This function groups charge deposits by (track_id, wire, time) and sums - the charges at each location. It's used in the hit path to - track particle contributions. - - Parameters - ---------- - wire_time_indices : jnp.ndarray, shape (N, 2) - Wire and time indices for each charge deposit. - track_ids : jnp.ndarray, shape (N,) - Track ID for each charge deposit. - charge_deposits : jnp.ndarray, shape (N,) - Charge value for each deposit. - min_charge_threshold : float - Minimum charge to keep a hit (default: 0.0). - max_tracks : int - Maximum number of tracks (static). - max_wires : int - Maximum number of wires (static). - max_time : int - Maximum time bins (static). - max_keys : int - Maximum number of unique (track, wire, time) combinations (static). - - Returns - ------- - hits_by_track : jnp.ndarray, shape (max_keys, 3) - Aggregated hits [wire, time, charge]. - num_hits : int - Number of unique (track, wire, time) combinations found. - track_boundaries : jnp.ndarray, shape (max_tracks,) - Indices where track boundaries occur in sorted data. - num_tracks : int - Number of track boundaries found. - track_ids_at_boundaries : jnp.ndarray, shape (max_tracks,) - Track IDs at each boundary position. - """ - N = wire_time_indices.shape[0] - - # Step 1: Sort by (track, wire, time) - composite_key = (track_ids.astype(jnp.int32) * (max_wires * max_time) + - wire_time_indices[:, 0].astype(jnp.int32) * max_time + - wire_time_indices[:, 1].astype(jnp.int32)) - - sorted_keys, sort_indices = jax.lax.sort_key_val(composite_key, jnp.arange(N)) - - sorted_wires = wire_time_indices[sort_indices, 0] - sorted_times = wire_time_indices[sort_indices, 1] - sorted_tracks = track_ids[sort_indices] - sorted_charges = charge_deposits[sort_indices] - - # Step 2: Find boundaries and aggregate - key_boundaries = jnp.ones(N, dtype=bool) - key_boundaries = key_boundaries.at[1:].set(sorted_keys[1:] != sorted_keys[:-1]) - - segment_ids = jnp.cumsum(key_boundaries) - 1 - summed_charges = jax.ops.segment_sum(sorted_charges, segment_ids, num_segments=N) - aggregated_charges = summed_charges[segment_ids] - - # Step 3: Apply threshold and extract unique entries - segment_ends = jnp.roll(key_boundaries, -1).at[-1].set(True) - threshold_mask = segment_ends & (aggregated_charges > min_charge_threshold) - - unique_indices = jnp.where(threshold_mask, size=max_keys, fill_value=0)[0] - num_unique = jnp.sum(threshold_mask) - - num_stored = jnp.minimum(num_unique, max_keys) - valid_mask = jnp.arange(max_keys) < num_stored - - # Step 4: Build hits_by_track array (without track column) - hits_by_track = jnp.stack([ - jnp.where(valid_mask, sorted_wires[unique_indices], 0), - jnp.where(valid_mask, sorted_times[unique_indices], 0), - jnp.where(valid_mask, aggregated_charges[unique_indices], 0) - ], axis=1) - - # Step 5: Key boundaries count - num_hits = num_unique - - # Step 6: Track boundaries and track IDs - # Build temporary track array for boundary detection - temp_track_array = jnp.where(valid_mask, sorted_tracks[unique_indices], 0) - track_changes = jnp.ones(max_keys, dtype=bool) - track_changes = track_changes.at[1:].set( - (temp_track_array[1:] != temp_track_array[:-1]) & - (jnp.arange(1, max_keys) < num_stored) - ) - track_boundaries = jnp.where(track_changes, size=max_tracks, fill_value=max_keys)[0] - num_tracks = jnp.sum(track_changes & (jnp.arange(max_keys) < num_stored)) - - # Extract track IDs at boundary positions - track_ids_at_boundaries = jnp.where( - jnp.arange(max_tracks) < num_tracks, - temp_track_array[track_boundaries], - 0 - ) - - return (hits_by_track, num_hits, - track_boundaries, num_tracks, - track_ids_at_boundaries) - - -@partial(jax.jit, static_argnames=['max_keys', 'max_time']) -def label_hits(hits_by_track, num_stored, track_ids_at_boundaries, - track_boundaries, num_tracks, - max_keys=1000000, max_time=2000): - """ - Determine which track owns each pixel based on maximum charge. - - For each unique (wire, time) location, this function determines which - track contributed the most charge and returns that as the "labeled" hit. - - Parameters - ---------- - hits_by_track : jnp.ndarray, shape (max_keys, 3) - Array of aggregated hits [wire, time, total_charge]. - num_stored : int - Number of valid entries in hits_by_track. - track_ids_at_boundaries : jnp.ndarray, shape (max_tracks,) - Track IDs at each boundary position. - track_boundaries : jnp.ndarray, shape (max_tracks,) - Indices where track boundaries occur. - num_tracks : int - Number of valid track boundaries. - max_keys : int - Maximum size of arrays (must match hits_by_track shape). - max_time : int - Maximum time index for creating composite keys. - - Returns - ------- - labeled_hits : jnp.ndarray, shape (max_keys, 4) - Array of labeled hits with highest charge per (wire,time) [track_id, wire, time, charge]. - num_labeled : int - Number of unique (wire,time) locations. - """ - # Rebroadcast track IDs from boundaries using searchsorted - # Each entry belongs to the track segment it falls into - # Use masking to avoid dynamic slicing in JIT - max_tracks_arr = track_boundaries.shape[0] - valid_boundaries_mask = jnp.arange(max_tracks_arr) < num_tracks - masked_boundaries = jnp.where(valid_boundaries_mask, track_boundaries, 1e9) - - boundary_idx = jnp.searchsorted(masked_boundaries, - jnp.arange(max_keys), - side='right') - 1 - boundary_idx = jnp.clip(boundary_idx, 0, jnp.maximum(num_tracks - 1, 0)) - - # Only assign track IDs to valid entries - rebroadcast_track_ids = jnp.where( - jnp.arange(max_keys) < num_stored, - track_ids_at_boundaries[boundary_idx], - 0 - ) - - # Create composite key for (wire, time, -charge) sorting - wire_time_key = hits_by_track[:, 0].astype(jnp.int32) * max_time + hits_by_track[:, 1].astype(jnp.int32) - sort_keys = jnp.stack([wire_time_key, -hits_by_track[:, 2]], axis=1) - sorted_indices = jnp.lexsort((sort_keys[:, 1], sort_keys[:, 0])) - - sorted_hits_by_track = hits_by_track[sorted_indices] - sorted_track_ids = rebroadcast_track_ids[sorted_indices] - - # Mark first occurrence of each (wire, time) - wire_time_first = jnp.ones(max_keys, dtype=bool) - wire_time_first = wire_time_first.at[1:].set( - (sorted_hits_by_track[1:, 0] != sorted_hits_by_track[:-1, 0]) | - (sorted_hits_by_track[1:, 1] != sorted_hits_by_track[:-1, 1]) - ) - - # Only consider valid entries - is_valid_entry = (jnp.arange(max_keys) < num_stored)[sorted_indices] - wire_time_first = wire_time_first & is_valid_entry - - # Extract labeled hits - labeled_indices = jnp.where(wire_time_first, size=max_keys, fill_value=0)[0] - num_labeled = jnp.sum(wire_time_first) - - valid_labeled_mask = jnp.arange(max_keys) < num_labeled - - labeled_hits = jnp.stack([ - jnp.where(valid_labeled_mask, sorted_track_ids[labeled_indices], 0), - jnp.where(valid_labeled_mask, sorted_hits_by_track[labeled_indices, 0], 0), - jnp.where(valid_labeled_mask, sorted_hits_by_track[labeled_indices, 1], 0), - jnp.where(valid_labeled_mask, sorted_hits_by_track[labeled_indices, 2], 0) - ], axis=1) - - return labeled_hits, num_labeled - - -def sparse_hits_to_dense(track_hit_result, num_wires, num_time_steps, min_wire_idx=0): - """ - Convert sparse track hits to dense 2D array. - - Uses hits_by_track which contains [wire, time, charge] per hit. - This function should be called OUTSIDE the simulation when dense - hit signals are needed for visualization. - - Parameters - ---------- - track_hit_result : dict - Output from track labeling containing: - - 'hits_by_track': jnp.ndarray, shape (max_keys, 3) with [wire, time, charge] - - 'num_hits': int, number of valid entries - num_wires : int - Number of wires in the output array. - num_time_steps : int - Number of time steps in the output array. - min_wire_idx : int, optional - Minimum wire index to subtract (for relative indexing). Default: 0. - - Returns - ------- - dense : jnp.ndarray, shape (num_wires, num_time_steps) - Dense 2D array of accumulated charges. - """ - hits_by_track = track_hit_result['hits_by_track'] - num_hits = track_hit_result['num_hits'] - - # Initialize dense array - dense = jnp.zeros((num_wires, num_time_steps), dtype=jnp.float32) - - # Get valid hits - num_valid = int(num_hits) - if num_valid > 0: - valid_hits = hits_by_track[:num_valid] - wire_indices = valid_hits[:, 0].astype(jnp.int32) - min_wire_idx - time_indices = valid_hits[:, 1].astype(jnp.int32) - charges = valid_hits[:, 2] - - # Clip indices to valid range - wire_indices = jnp.clip(wire_indices, 0, num_wires - 1) - time_indices = jnp.clip(time_indices, 0, num_time_steps - 1) - - # Accumulate charges - dense = dense.at[wire_indices, time_indices].add(charges) - - return dense diff --git a/closure/archive/gradient_test/gradient_test/tools/visualization.py b/closure/archive/gradient_test/gradient_test/tools/visualization.py deleted file mode 100644 index 5ba3ad2..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/visualization.py +++ /dev/null @@ -1,1377 +0,0 @@ -""" -Visualization utilities for LArTPC wire signals. - -This module provides functions for visualizing wire signals from TPC simulations, -including multi-plane displays with logarithmic scaling, track coloring, and -customizable color schemes for different plane types (U, V, Y). - -Supports both dense and sparse data formats: - - Dense: (num_wires, num_time_steps) arrays - - Sparse: tuples of (indices, values) where - - indices: (N, 2) int32 array with [wire_idx, time_idx] per row (relative) - - values: (N,) float32 array with signal values - -Use `sparse_data=True` parameter to enable sparse visualization mode. -""" - -import numpy as np -import jax.numpy as jnp -import jax -import matplotlib.pyplot as plt -from matplotlib.colors import LogNorm, Normalize, SymLogNorm -import matplotlib.gridspec as gridspec -import matplotlib.colors as mcolors -from mpl_toolkits.axes_grid1 import make_axes_locatable - - -def visualize_wire_signals(wire_signals_dict, simulation_params, figsize=(20, 10), - log_norm=False, sparse_data=False, point_size=0.1): - """ - Visualize wire signals stored in a dictionary, using different color schemes per plane type. - - Parameters - ---------- - wire_signals_dict : dict - Dictionary of wire signals, keyed by (side_idx, plane_idx). - If sparse_data=False: values are dense (num_wires, num_time_steps) arrays. - If sparse_data=True: values are tuples (indices, values) where - indices is (N, 2) with [wire_idx, time_idx] (relative) and values is (N,). - simulation_params : dict - Dictionary containing simulation parameters. - figsize : tuple, optional - Figure size (width, height) in inches, by default (20, 10). - log_norm : bool, optional - If True, use logarithmic normalization for all plots, by default False. - sparse_data : bool, optional - If True, expect sparse format (indices, values). If False, expect dense arrays. - point_size : float, optional - Size of scatter points when using sparse_data=True, by default 0.1. - - Returns - ------- - matplotlib.figure.Figure - The matplotlib Figure object. - """ - # Extract pre-calculated parameters - num_time_steps = simulation_params['num_time_steps'] - time_step_size_us = simulation_params['time_step_size_us'] - num_wires_actual = simulation_params['num_wires_actual'] - max_abs_indices = simulation_params['max_abs_indices'] - min_abs_indices = simulation_params['min_abs_indices'] - - side_names = ['West Side (x < 0)', 'East Side (x > 0)'] - plane_types = ['First Induction (U)', 'Second Induction (V)', 'Collection (Y)'] - - # Plane name mapping - plane_name_mapping = { - (0, 0): 'U-plane', (0, 1): 'V-plane', (0, 2): 'Y-plane', - (1, 0): 'U-plane', (1, 1): 'V-plane', (1, 2): 'Y-plane', - } - - # Define colormap settings - cmap_settings = { - 'U-plane': {'cmap': 'seismic'}, - 'V-plane': {'cmap': 'seismic'}, - 'Y-plane': {'cmap': 'seismic'} - } - - # Find min/max values for each plane type - plane_min_max = { - 'U-plane': {'min': float('inf'), 'max': -float('inf')}, - 'V-plane': {'min': float('inf'), 'max': -float('inf')}, - 'Y-plane': {'min': float('inf'), 'max': -float('inf')} - } - - # Pre-convert all arrays once to avoid repeated device-to-host transfers - converted_signals = {} - for key, signal_data in wire_signals_dict.items(): - if sparse_data: - indices, values = signal_data - converted_signals[key] = (np.asarray(indices), np.asarray(values)) - else: - converted_signals[key] = np.asarray(signal_data) - - # Calculate min/max for each plane type using pre-converted arrays - for s in range(2): - for p in range(3): - if (s, p) in converted_signals and num_wires_actual[s, p] > 0: - plane_name = plane_name_mapping[(s, p)] - if sparse_data: - indices_np, values_np = converted_signals[(s, p)] - if len(values_np) > 0: - plane_min_max[plane_name]['min'] = min(plane_min_max[plane_name]['min'], values_np.min()) - plane_min_max[plane_name]['max'] = max(plane_min_max[plane_name]['max'], values_np.max()) - else: - signal_data = converted_signals[(s, p)] - if signal_data.size > 0: - plane_min_max[plane_name]['min'] = min(plane_min_max[plane_name]['min'], signal_data.min()) - plane_min_max[plane_name]['max'] = max(plane_min_max[plane_name]['max'], signal_data.max()) - - # Set fixed ranges if no data found - ensure symmetric range around zero - for plane_name in plane_min_max: - if plane_min_max[plane_name]['min'] == float('inf'): - plane_min_max[plane_name]['min'] = -25 - plane_min_max[plane_name]['max'] = 25 - else: - max_abs_val = max(abs(plane_min_max[plane_name]['min']), abs(plane_min_max[plane_name]['max'])) - plane_min_max[plane_name]['min'] = -max_abs_val - plane_min_max[plane_name]['max'] = max_abs_val - - print(" Visualization Norms by Plane Type:") - for plane_name in plane_min_max: - print(f" - {plane_name}: min={plane_min_max[plane_name]['min']:.2e}, max={plane_min_max[plane_name]['max']:.2e}") - - # Create figure and plot with white background - fig = plt.figure(figsize=figsize, facecolor='white') - gs = gridspec.GridSpec(2, 3, figure=fig, hspace=0.35, wspace=0.30) - max_time_axis = num_time_steps * time_step_size_us - title_size, label_size, tick_size = 14, 12, 10 - - for side_idx in range(2): - for plane_idx in range(3): - ax = fig.add_subplot(gs[side_idx, plane_idx]) - ax.set_facecolor('white') - ax.grid(False) - min_idx_abs = int(min_abs_indices[side_idx, plane_idx]) - max_idx_abs = int(max_abs_indices[side_idx, plane_idx]) - actual_wire_count = int(num_wires_actual[side_idx, plane_idx]) - plot_title = f"{side_names[side_idx]}\n{plane_types[plane_idx]}" - plane_name = plane_name_mapping[(side_idx, plane_idx)] - - if (side_idx, plane_idx) not in converted_signals or actual_wire_count == 0: - ax.text(0.5, 0.5, "(0 wires active)", color='grey', ha='center', va='center', transform=ax.transAxes) - ax.set_title(plot_title, fontsize=title_size, pad=10, color='black') - ax.set_xlabel('Absolute Wire Index', fontsize=label_size, color='black') - ax.set_ylabel('Time (μs)', fontsize=label_size, color='black') - ax.tick_params(axis='both', which='major', labelsize=tick_size, colors='black') - ax.set_xlim(min_idx_abs, max_idx_abs + 1) - ax.set_ylim(0, max_time_axis) - ax.set_box_aspect(1) - continue - - # Get colormap settings - cmap = cmap_settings[plane_name]['cmap'] - vmin = plane_min_max[plane_name]['min'] - vmax = plane_min_max[plane_name]['max'] - - if sparse_data: - # Sparse visualization using scatter plot (use pre-converted arrays) - indices_np, values_np = converted_signals[(side_idx, plane_idx)] - if len(values_np) == 0: - ax.text(0.5, 0.5, "(No data)", color='grey', ha='center', va='center', transform=ax.transAxes) - else: - - # Convert relative wire indices to absolute - wire_abs = indices_np[:, 0] + min_idx_abs - time_us = indices_np[:, 1] * time_step_size_us - - # Create normalization - if log_norm: - max_abs_val = max(abs(vmin), abs(vmax)) - linthresh = max(1e-8, 0.015 * max_abs_val) - norm = SymLogNorm(linthresh=linthresh, linscale=1.0, vmin=vmin, vmax=vmax, clip=True) - else: - norm = Normalize(vmin=vmin, vmax=vmax) - - sc = ax.scatter(wire_abs, time_us, c=values_np, cmap=cmap, norm=norm, - s=point_size, marker='s', linewidths=0) - - # Add colorbar - divider = make_axes_locatable(ax) - cax = divider.append_axes('right', size='4%', pad=0.08) - cbar = fig.colorbar(sc, cax=cax) - cbar.ax.tick_params(labelsize=tick_size, colors='black') - cbar.set_label('Signal Strength', fontsize=label_size, color='black') - else: - # Dense visualization using imshow (use pre-converted arrays) - signal_data_to_plot = converted_signals[(side_idx, plane_idx)] - extent_xmin = min_idx_abs - extent_xmax = max_idx_abs + 1 - extent = [extent_xmin, extent_xmax, 0, max_time_axis] - - if log_norm: - max_abs_val = max(abs(vmin), abs(vmax)) - linthresh = max(1e-8, 0.015 * max_abs_val) - norm = SymLogNorm(linthresh=linthresh, linscale=1.0, vmin=vmin, vmax=vmax, clip=True) - im = ax.imshow(signal_data_to_plot.T, aspect='auto', origin='lower', extent=extent, - cmap=cmap, norm=norm) - else: - im = ax.imshow(signal_data_to_plot.T, aspect='auto', origin='lower', extent=extent, - cmap=cmap, vmin=vmin, vmax=vmax) - - divider = make_axes_locatable(ax) - cax = divider.append_axes('right', size='4%', pad=0.08) - cbar = fig.colorbar(im, cax=cax) - cbar.ax.tick_params(labelsize=tick_size, colors='black') - cbar.set_label('Signal Strength', fontsize=label_size, color='black') - - ax.set_ylim(0, max_time_axis) - ax.set_xlim(min_idx_abs, max_idx_abs + 1) - ax.set_box_aspect(1) - ax.set_title(plot_title, fontsize=title_size, pad=10, color='black') - ax.set_xlabel('Absolute Wire Index', fontsize=label_size, color='black') - ax.set_ylabel('Time (μs)', fontsize=label_size, color='black') - ax.tick_params(axis='both', which='major', labelsize=tick_size, colors='black') - - return fig - - -def visualize_single_plane(wire_signals_dict, simulation_params, side_idx=0, plane_idx=0, - figsize=(10, 10), log_norm=False, sparse_data=False, point_size=0.5): - """ - Visualize wire signals for a single side/plane combination using appropriate color scheme. - - Parameters - ---------- - wire_signals_dict : dict - Dictionary of wire signals, keyed by (side_idx, plane_idx). - If sparse_data=False: values are dense arrays. - If sparse_data=True: values are tuples (indices, values). - simulation_params : dict - Dictionary containing simulation parameters. - side_idx : int, optional - Index of the side to plot (0=West, 1=East), by default 0. - plane_idx : int, optional - Index of the plane to plot (0=U, 1=V, 2=Y), by default 0. - figsize : tuple, optional - Figure size (width, height) in inches, by default (10, 10). - log_norm : bool, optional - If True, use logarithmic normalization, by default False. - sparse_data : bool, optional - If True, expect sparse format (indices, values). - point_size : float, optional - Size of scatter points when using sparse_data=True, by default 0.5. - - Returns - ------- - matplotlib.figure.Figure - The matplotlib Figure object. - """ - print(f"--- Starting Visualization for Side {side_idx}, Plane {plane_idx} ---") - - num_time_steps = simulation_params['num_time_steps'] - time_step_size_us = simulation_params['time_step_size_us'] - num_wires_actual = simulation_params['num_wires_actual'] - max_abs_indices = simulation_params['max_abs_indices'] - min_abs_indices = simulation_params['min_abs_indices'] - - side_names = ['West Side (x < 0)', 'East Side (x > 0)'] - plane_types = ['First Induction (U)', 'Second Induction (V)', 'Collection (Y)'] - - plane_name_mapping = { - (0, 0): 'U-plane', (0, 1): 'V-plane', (0, 2): 'Y-plane', - (1, 0): 'U-plane', (1, 1): 'V-plane', (1, 2): 'Y-plane', - } - - cmap_settings = { - 'U-plane': {'cmap': 'seismic'}, - 'V-plane': {'cmap': 'seismic'}, - 'Y-plane': {'cmap': 'seismic'} - } - - s, p = side_idx, plane_idx - plane_name = plane_name_mapping[(s, p)] - - # Find min/max across both sides for the same plane type - min_val, max_val = float('inf'), -float('inf') - - for check_side in range(2): - check_key = (check_side, p) - if check_key in wire_signals_dict and num_wires_actual[check_side, p] > 0: - if sparse_data: - indices, values = wire_signals_dict[check_key] - if len(values) > 0: - values_np = np.array(values) - min_val = min(min_val, values_np.min()) - max_val = max(max_val, values_np.max()) - else: - signal_data = np.array(wire_signals_dict[check_key]) - if signal_data.size > 0: - min_val = min(min_val, signal_data.min()) - max_val = max(max_val, signal_data.max()) - - if min_val == float('inf'): - min_val, max_val = -25, 25 - else: - max_abs_val = max(abs(min_val), abs(max_val)) - min_val, max_val = -max_abs_val, max_abs_val - - print(f" Visualization Norm for {plane_name}: min={min_val:.2e}, max={max_val:.2e}") - - fig = plt.figure(figsize=figsize, facecolor='white') - ax = fig.add_subplot(1, 1, 1) - ax.set_facecolor('white') - ax.grid(False) - max_time_axis = num_time_steps * time_step_size_us - title_size, label_size, tick_size = 14, 12, 10 - - min_idx_abs = int(min_abs_indices[s, p]) - max_idx_abs = int(max_abs_indices[s, p]) - actual_wire_count = int(num_wires_actual[s, p]) - plot_title = f"{side_names[s]}\n{plane_types[p]}" - - if (s, p) not in wire_signals_dict or actual_wire_count == 0: - ax.text(0.5, 0.5, "(0 wires active)", color='grey', ha='center', va='center', transform=ax.transAxes) - ax.set_title(plot_title, fontsize=title_size, pad=10, color='black') - ax.set_xlabel('Wire Index', fontsize=label_size, color='black') - ax.set_ylabel('Time (μs)', fontsize=label_size, color='black') - ax.tick_params(axis='both', which='major', labelsize=tick_size, colors='black') - ax.set_xlim(min_idx_abs, max_idx_abs + 1) - ax.set_ylim(0, max_time_axis) - ax.set_box_aspect(1) - return fig - - cmap = cmap_settings[plane_name]['cmap'] - vmin, vmax = min_val, max_val - - if sparse_data: - indices, values = wire_signals_dict[(s, p)] - if len(values) == 0: - ax.text(0.5, 0.5, "(No data)", color='grey', ha='center', va='center', transform=ax.transAxes) - else: - indices_np = np.array(indices) - values_np = np.array(values) - - wire_abs = indices_np[:, 0] + min_idx_abs - time_us = indices_np[:, 1] * time_step_size_us - - if log_norm: - max_abs_val = max(abs(vmin), abs(vmax)) - linthresh = max(1e-8, 0.01 * max_abs_val) - norm = SymLogNorm(linthresh=linthresh, linscale=1.0, vmin=vmin, vmax=vmax, clip=True) - else: - norm = Normalize(vmin=vmin, vmax=vmax) - - sc = ax.scatter(wire_abs, time_us, c=values_np, cmap=cmap, norm=norm, - s=point_size, marker='s', linewidths=0) - - divider = make_axes_locatable(ax) - cax = divider.append_axes('right', size='4%', pad=0.08) - cbar = fig.colorbar(sc, cax=cax) - cbar.ax.tick_params(labelsize=tick_size, colors='black') - cbar.set_label('Signal Strength', fontsize=label_size, color='black') - cbar.outline.set_edgecolor('white') - else: - signal_data_to_plot = np.array(wire_signals_dict[(s, p)]) - extent_xmin = min_idx_abs - extent_xmax = max_idx_abs + 1 - extent = [extent_xmin, extent_xmax, 0, max_time_axis] - - if log_norm: - max_abs_val = max(abs(vmin), abs(vmax)) - linthresh = max(1e-8, 0.01 * max_abs_val) - norm = SymLogNorm(linthresh=linthresh, linscale=1.0, vmin=vmin, vmax=vmax, clip=True) - im = ax.imshow(signal_data_to_plot.T, aspect='auto', origin='lower', extent=extent, - cmap=cmap, norm=norm) - else: - im = ax.imshow(signal_data_to_plot.T, aspect='auto', origin='lower', extent=extent, - cmap=cmap, vmin=vmin, vmax=vmax) - - divider = make_axes_locatable(ax) - cax = divider.append_axes('right', size='4%', pad=0.08) - cbar = fig.colorbar(im, cax=cax) - cbar.ax.tick_params(labelsize=tick_size, colors='black') - cbar.set_label('Signal Strength', fontsize=label_size, color='black') - cbar.outline.set_edgecolor('white') - - ax.set_ylim(0, max_time_axis) - ax.set_xlim(min_idx_abs, max_idx_abs + 1) - ax.set_box_aspect(1) - ax.set_title(plot_title, fontsize=title_size, pad=10, color='black') - ax.set_xlabel('Absolute Wire Index', fontsize=label_size, color='black') - ax.set_ylabel('Time (μs)', fontsize=label_size, color='black') - ax.tick_params(axis='both', which='major', labelsize=tick_size, colors='black') - - return fig - - -def visualize_diffused_charge(wire_signals_dict, simulation_params, figsize=(20, 10), - log_norm=False, threshold=100, sparse_data=False, point_size=0.5): - """ - Visualize diffused charge (hit signals) with proper scaling. - - Uses YlOrRd colormap with dark background and threshold masking for - better visualization of charge deposits. - - Parameters - ---------- - wire_signals_dict : dict - Dictionary of wire signals, keyed by (side_idx, plane_idx). - If sparse_data=False: values are dense arrays. - If sparse_data=True: values are tuples (indices, values). - simulation_params : dict - Dictionary containing simulation parameters. - figsize : tuple, optional - Figure size (width, height) in inches, by default (20, 10). - log_norm : bool, optional - If True, use logarithmic normalization for all plots, by default False. - threshold : float, optional - Values below this threshold are masked/hidden, by default 100. - sparse_data : bool, optional - If True, expect sparse format (indices, values). - point_size : float, optional - Size of scatter points when using sparse_data=True, by default 0.5. - - Returns - ------- - matplotlib.figure.Figure - The matplotlib Figure object. - """ - num_time_steps = simulation_params['num_time_steps'] - time_step_size_us = simulation_params['time_step_size_us'] - num_wires_actual = simulation_params['num_wires_actual'] - max_abs_indices = simulation_params['max_abs_indices'] - min_abs_indices = simulation_params['min_abs_indices'] - - side_names = ['West Side (x < 0)', 'East Side (x > 0)'] - plane_types = ['First Induction (U)', 'Second Induction (V)', 'Collection (Y)'] - - # Find global min/max - global_min, global_max = float('inf'), -float('inf') - all_values = [] - - for s in range(2): - for p in range(3): - if (s, p) in wire_signals_dict and num_wires_actual[s, p] > 0: - if sparse_data: - indices, values = wire_signals_dict[(s, p)] - if len(values) > 0: - values_np = np.array(values) - valid_data = values_np[values_np > threshold] - if len(valid_data) > 0: - global_min = min(global_min, valid_data.min()) - global_max = max(global_max, valid_data.max()) - all_values.append(valid_data) - else: - signal_data = np.array(wire_signals_dict[(s, p)]) - if signal_data.size > 0: - valid_data = signal_data[signal_data > threshold] - if valid_data.size > 0: - global_min = min(global_min, valid_data.min()) - global_max = max(global_max, valid_data.max()) - all_values.append(valid_data.flatten()) - - if global_min == float('inf'): - global_min, global_max = threshold, threshold * 10 - elif all_values: - all_values_concat = np.concatenate(all_values) - if len(all_values_concat) > 0: - p1, p99 = np.percentile(all_values_concat, [1, 99]) - global_min = max(global_min, p1) - global_max = min(global_max, p99) - - print(f" Diffused Charge Range: min={global_min:.2e}, max={global_max:.2e}") - background_color = '#1a1a1a' - colormap_name = 'YlOrRd' - - fig = plt.figure(figsize=figsize, facecolor="white") - gs = gridspec.GridSpec(2, 3, figure=fig, hspace=0.35, wspace=0.30) - max_time_axis = num_time_steps * time_step_size_us - - for side_idx in range(2): - for plane_idx in range(3): - ax = fig.add_subplot(gs[side_idx, plane_idx]) - ax.set_facecolor(background_color) - ax.grid(True, alpha=0.3, color='#505050', linestyle='--', linewidth=0.5) - - min_idx_abs = int(min_abs_indices[side_idx, plane_idx]) - max_idx_abs = int(max_abs_indices[side_idx, plane_idx]) - actual_wire_count = int(num_wires_actual[side_idx, plane_idx]) - plot_title = f"{side_names[side_idx]}\n{plane_types[plane_idx]}" - - if (side_idx, plane_idx) not in wire_signals_dict or actual_wire_count == 0: - ax.text(0.5, 0.5, "(0 wires active)", color='gray', ha='center', va='center', transform=ax.transAxes) - ax.set_title(plot_title, fontsize=14, pad=10) - ax.set_xlim(min_idx_abs, max_idx_abs + 1) - ax.set_ylim(0, max_time_axis) - ax.set_box_aspect(1) - continue - - cmap = plt.cm.get_cmap(colormap_name).copy() - vmin_plot = max(threshold, global_min) - vmax_plot = global_max - - if sparse_data: - indices, values = wire_signals_dict[(side_idx, plane_idx)] - if len(values) == 0: - ax.text(0.5, 0.5, "(No data)", color='gray', ha='center', va='center', transform=ax.transAxes) - else: - indices_np = np.array(indices) - values_np = np.array(values) - - # Apply threshold filter - mask = values_np > threshold - if np.sum(mask) == 0: - ax.text(0.5, 0.5, "(Below threshold)", color='gray', ha='center', va='center', transform=ax.transAxes) - else: - wire_abs = indices_np[mask, 0] + min_idx_abs - time_us = indices_np[mask, 1] * time_step_size_us - filtered_values = values_np[mask] - - if log_norm: - norm = LogNorm(vmin=vmin_plot, vmax=vmax_plot, clip=True) - else: - norm = Normalize(vmin=vmin_plot, vmax=vmax_plot) - - sc = ax.scatter(wire_abs, time_us, c=filtered_values, cmap=cmap, norm=norm, - s=point_size, marker='s', linewidths=0) - - divider = make_axes_locatable(ax) - cax = divider.append_axes('right', size='4%', pad=0.08) - cbar = fig.colorbar(sc, cax=cax) - cbar.set_label('Diffused Charge', fontsize=12) - else: - signal_data_to_plot = np.array(wire_signals_dict[(side_idx, plane_idx)]) - extent = [min_idx_abs, max_idx_abs + 1, 0, max_time_axis] - masked_data = np.ma.masked_where(signal_data_to_plot.T <= threshold, signal_data_to_plot.T) - - cmap.set_bad(background_color) - cmap.set_under(background_color) - - if log_norm: - norm = LogNorm(vmin=vmin_plot, vmax=vmax_plot, clip=True) - im = ax.imshow(masked_data, aspect='auto', origin='lower', extent=extent, - cmap=cmap, norm=norm, interpolation='nearest') - else: - im = ax.imshow(masked_data, aspect='auto', origin='lower', extent=extent, - cmap=cmap, vmin=vmin_plot, vmax=vmax_plot, interpolation='nearest') - - divider = make_axes_locatable(ax) - cax = divider.append_axes('right', size='4%', pad=0.08) - cbar = fig.colorbar(im, cax=cax) - cbar.set_label('Diffused Charge', fontsize=12) - - ax.set_ylim(0, max_time_axis) - ax.set_xlim(min_idx_abs, max_idx_abs + 1) - ax.set_box_aspect(1) - ax.set_title(plot_title, fontsize=14, pad=10) - ax.set_xlabel('Absolute Wire Index', fontsize=12) - ax.set_ylabel('Time (μs)', fontsize=12) - - return fig - - -def visualize_diffused_charge_single_plane(wire_signals_dict, simulation_params, side_idx=0, plane_idx=0, - figsize=(10, 10), log_norm=False, threshold=100, - sparse_data=False, point_size=1.0): - """ - Visualize diffused charge for a single side/plane combination. - - Parameters - ---------- - wire_signals_dict : dict - Dictionary of wire signals, keyed by (side_idx, plane_idx). - simulation_params : dict - Dictionary containing simulation parameters. - side_idx : int, optional - Index of the side to plot (0=West, 1=East), by default 0. - plane_idx : int, optional - Index of the plane to plot (0=U, 1=V, 2=Y), by default 0. - figsize : tuple, optional - Figure size (width, height) in inches, by default (10, 10). - log_norm : bool, optional - If True, use logarithmic normalization, by default False. - threshold : float, optional - Values below this threshold are masked/hidden, by default 100. - sparse_data : bool, optional - If True, expect sparse format (indices, values). - point_size : float, optional - Size of scatter points when using sparse_data=True, by default 1.0. - - Returns - ------- - matplotlib.figure.Figure - The matplotlib Figure object. - """ - print(f"--- Visualizing Diffused Charge for Side {side_idx}, Plane {plane_idx} ---") - - num_time_steps = simulation_params['num_time_steps'] - time_step_size_us = simulation_params['time_step_size_us'] - num_wires_actual = simulation_params['num_wires_actual'] - max_abs_indices = simulation_params['max_abs_indices'] - min_abs_indices = simulation_params['min_abs_indices'] - - side_names = ['West Side (x < 0)', 'East Side (x > 0)'] - plane_types = ['First Induction (U)', 'Second Induction (V)', 'Collection (Y)'] - - s, p = side_idx, plane_idx - min_val, max_val = float('inf'), -float('inf') - - for check_side in range(2): - check_key = (check_side, p) - if check_key in wire_signals_dict and num_wires_actual[check_side, p] > 0: - if sparse_data: - indices, values = wire_signals_dict[check_key] - if len(values) > 0: - values_np = np.array(values) - valid_data = values_np[values_np > threshold] - if len(valid_data) > 0: - min_val = min(min_val, valid_data.min()) - max_val = max(max_val, valid_data.max()) - else: - signal_data = np.array(wire_signals_dict[check_key]) - if signal_data.size > 0: - valid_data = signal_data[signal_data > threshold] - if valid_data.size > 0: - min_val = min(min_val, valid_data.min()) - max_val = max(max_val, valid_data.max()) - - if min_val == float('inf'): - min_val, max_val = threshold, threshold * 10 - - print(f" Visualization Range: min={min_val:.2e}, max={max_val:.2e}") - - background_color = '#1a1a1a' - colormap_name = 'YlOrRd' - - fig = plt.figure(figsize=figsize, facecolor='white') - ax = fig.add_subplot(1, 1, 1) - ax.set_facecolor(background_color) - ax.grid(True, alpha=0.3, color='#505050', linestyle='--', linewidth=0.5) - max_time_axis = num_time_steps * time_step_size_us - - min_idx_abs = int(min_abs_indices[s, p]) - max_idx_abs = int(max_abs_indices[s, p]) - actual_wire_count = int(num_wires_actual[s, p]) - plot_title = f"{side_names[s]}\n{plane_types[p]}" - - if (s, p) not in wire_signals_dict or actual_wire_count == 0: - ax.text(0.5, 0.5, "(0 wires active)", color='gray', ha='center', va='center', transform=ax.transAxes) - ax.set_title(plot_title, fontsize=14, pad=10) - ax.set_xlabel('Absolute Wire Index', fontsize=12) - ax.set_ylabel('Time (μs)', fontsize=12) - ax.set_xlim(min_idx_abs, max_idx_abs + 1) - ax.set_ylim(0, max_time_axis) - ax.set_box_aspect(1) - return fig - - cmap = plt.cm.get_cmap(colormap_name).copy() - vmin_plot = max(threshold, min_val) - vmax_plot = max_val - - if sparse_data: - indices, values = wire_signals_dict[(s, p)] - if len(values) == 0: - ax.text(0.5, 0.5, "(No data)", color='gray', ha='center', va='center', transform=ax.transAxes) - else: - indices_np = np.array(indices) - values_np = np.array(values) - - mask = values_np > threshold - if np.sum(mask) == 0: - ax.text(0.5, 0.5, "(Below threshold)", color='gray', ha='center', va='center', transform=ax.transAxes) - else: - wire_abs = indices_np[mask, 0] + min_idx_abs - time_us = indices_np[mask, 1] * time_step_size_us - filtered_values = values_np[mask] - - if log_norm: - norm = LogNorm(vmin=vmin_plot, vmax=vmax_plot, clip=True) - else: - norm = Normalize(vmin=vmin_plot, vmax=vmax_plot) - - sc = ax.scatter(wire_abs, time_us, c=filtered_values, cmap=cmap, norm=norm, - s=point_size, marker='s', linewidths=0) - - divider = make_axes_locatable(ax) - cax = divider.append_axes('right', size='4%', pad=0.08) - cbar = fig.colorbar(sc, cax=cax) - cbar.set_label('Diffused Charge', fontsize=12) - else: - signal_data_to_plot = np.array(wire_signals_dict[(s, p)]) - extent = [min_idx_abs, max_idx_abs + 1, 0, max_time_axis] - masked_data = np.ma.masked_where(signal_data_to_plot.T <= threshold, signal_data_to_plot.T) - - cmap.set_bad(background_color) - cmap.set_under(background_color) - - if log_norm: - norm = LogNorm(vmin=vmin_plot, vmax=vmax_plot, clip=True) - im = ax.imshow(masked_data, aspect='auto', origin='lower', extent=extent, - cmap=cmap, norm=norm, interpolation='nearest') - else: - im = ax.imshow(masked_data, aspect='auto', origin='lower', extent=extent, - cmap=cmap, vmin=vmin_plot, vmax=vmax_plot, interpolation='nearest') - - divider = make_axes_locatable(ax) - cax = divider.append_axes('right', size='4%', pad=0.08) - cbar = fig.colorbar(im, cax=cax) - cbar.set_label('Diffused Charge', fontsize=12) - - ax.set_ylim(0, max_time_axis) - ax.set_xlim(min_idx_abs, max_idx_abs + 1) - ax.set_box_aspect(1) - ax.set_title(plot_title, fontsize=14, pad=10) - ax.set_xlabel('Absolute Wire Index', fontsize=12) - ax.set_ylabel('Time (μs)', fontsize=12) - - return fig - - -def get_top_tracks_by_charge(track_hits_dict, top_n=20): - """ - Find top tracks by total charge across all planes. - - Parameters - ---------- - track_hits_dict : dict - Dictionary of track hits results, keyed by (side_idx, plane_idx). - Each entry should contain 'num_labeled' and 'labeled_hits' arrays. - top_n : int, optional - Number of top tracks to return, by default 20. - - Returns - ------- - list - List of tuples (track_id, total_charge) sorted by charge descending. - """ - all_track_ids = [] - all_charges = [] - - for plane_key, results in track_hits_dict.items(): - num_labeled = int(results['num_labeled']) - if num_labeled > 0: - labeled = results['labeled_hits'][:num_labeled] - all_track_ids.append(jnp.asarray(labeled[:, 0], dtype=jnp.int32)) - all_charges.append(jnp.asarray(labeled[:, 3])) - - if not all_track_ids: - return [] - - all_track_ids = jnp.concatenate(all_track_ids) - all_charges = jnp.concatenate(all_charges) - - sort_idx = jnp.argsort(all_track_ids) - sorted_ids = all_track_ids[sort_idx] - sorted_charges = all_charges[sort_idx] - - is_new_track = jnp.concatenate([jnp.array([True]), sorted_ids[1:] != sorted_ids[:-1]]) - unique_indices = jnp.where(is_new_track)[0] - unique_tracks = sorted_ids[unique_indices] - - segment_ids = jnp.cumsum(is_new_track) - 1 - track_totals = jax.ops.segment_sum(sorted_charges, segment_ids, num_segments=len(unique_indices)) - - top_indices = jnp.argsort(track_totals)[-top_n:][::-1] - return [(int(unique_tracks[i]), float(track_totals[i])) for i in top_indices] - - -def visualize_track_labels(track_hits_dict, simulation_params, top_tracks_by_charge, - max_tracks=15, figsize=(20, 12)): - """ - Visualize track labels with distinct colors for top tracks by charge. - - Uses hash-based coloring for non-top tracks to ensure visual distinction. - - Parameters - ---------- - track_hits_dict : dict - Dictionary of track hits results, keyed by (side_idx, plane_idx). - Each entry should contain 'num_labeled' and 'labeled_hits' arrays. - simulation_params : dict - Dictionary containing simulation parameters. - top_tracks_by_charge : list - List of tuples (track_id, total_charge) from get_top_tracks_by_charge. - max_tracks : int, optional - Maximum number of tracks to show in legend, by default 15. - figsize : tuple, optional - Figure size (width, height) in inches, by default (20, 12). - - Returns - ------- - matplotlib.figure.Figure - The matplotlib Figure object. - """ - num_time_steps = simulation_params['num_time_steps'] - time_step_size_us = simulation_params['time_step_size_us'] - max_abs_indices = simulation_params['max_abs_indices'] - min_abs_indices = simulation_params['min_abs_indices'] - - side_names = ['West Side (x < 0)', 'East Side (x > 0)'] - plane_types = ['First Induction (U)', 'Second Induction (V)', 'Collection (Y)'] - - fig = plt.figure(figsize=figsize, facecolor='white') - gs = gridspec.GridSpec(2, 4, figure=fig, hspace=0.35, wspace=0.30, width_ratios=[1, 1, 1, 0.12]) - max_time_axis = num_time_steps * time_step_size_us - - distinct_colors = ['#FF0000', '#0000FF', '#00FF00', '#FF00FF', '#00FFFF', - '#FFD700', '#FF8C00', '#8B008B', '#228B22', '#4B0082', - '#FF1493', '#00CED1', '#FF4500', '#9400D3', '#32CD32', - '#8B4513', '#20B2AA', '#FF69B4', '#4169E1', '#DC143C'] - distinct_colors_rgba = [mcolors.to_rgba(c) for c in distinct_colors] - - top_tracks = [tid for tid, _ in top_tracks_by_charge[:max_tracks]] - top_track_to_color = {tid: distinct_colors_rgba[i] for i, tid in enumerate(top_tracks[:len(distinct_colors)])} - cmap = plt.cm.hsv - - def get_track_colors_vectorized(track_ids): - track_ids = np.asarray(track_ids, dtype=np.int64) - colors = np.zeros((len(track_ids), 4)) - hash_values = (track_ids * 2654435761) % 2**32 - colors[:] = cmap(hash_values / (2**32 - 1)) - for tid, color in top_track_to_color.items(): - colors[track_ids == tid] = color - return colors - - for side_idx in range(2): - for plane_idx in range(3): - ax = fig.add_subplot(gs[side_idx, plane_idx]) - ax.set_facecolor('black') - - min_idx_abs = int(min_abs_indices[side_idx, plane_idx]) - max_idx_abs = int(max_abs_indices[side_idx, plane_idx]) - - ax.set_xlim(min_idx_abs, max_idx_abs + 1) - ax.set_ylim(0, max_time_axis) - ax.set_box_aspect(1) - ax.set_title(f"{side_names[side_idx]}\n{plane_types[plane_idx]}", fontsize=14, pad=10) - ax.set_xlabel('Absolute Wire Index', fontsize=12) - ax.set_ylabel('Time (μs)', fontsize=12) - - plane_key = (side_idx, plane_idx) - results = track_hits_dict[plane_key] - num_labeled = int(results['num_labeled']) - - if num_labeled > 0: - labeled = np.array(results['labeled_hits'][:num_labeled]) - tracks = labeled[:, 0].astype(np.int64) - wires = labeled[:, 1] - times = labeled[:, 2] * time_step_size_us - - colors = get_track_colors_vectorized(tracks) - ax.scatter(wires, times, c=colors, s=0.5, alpha=0.8) - ax.text(0.02, 0.98, f"{num_labeled:,} hits\n{len(np.unique(tracks))} tracks", - transform=ax.transAxes, va='top', ha='left', - bbox=dict(facecolor='white', alpha=0.8), fontsize=10) - else: - ax.text(0.5, 0.5, "(No labeled hits)", color='grey', ha='center', va='center', transform=ax.transAxes) - - # Add colorbar - if top_tracks: - cbar_ax = fig.add_subplot(gs[:, 3]) - n_show = min(len(top_tracks), max_tracks) - cbar_ax.set_xlim(0, 1) - cbar_ax.set_ylim(0, n_show) - for i, tid in enumerate(top_tracks[:n_show]): - color = top_track_to_color.get(tid, cmap((tid * 2654435761 % 2**32) / (2**32 - 1))) - y_pos = n_show - 1 - i - rect = plt.Rectangle((0, y_pos), 0.4, 0.9, facecolor=color, edgecolor='black', linewidth=0.5) - cbar_ax.add_patch(rect) - cbar_ax.text(0.5, y_pos + 0.45, f'Track {tid}', ha='left', va='center', fontsize=8) - cbar_ax.set_xticks([]) - cbar_ax.set_yticks([]) - cbar_ax.set_title(f'Top {n_show} Tracks\n(by total charge)', fontsize=11, pad=10) - for spine in cbar_ax.spines.values(): - spine.set_visible(False) - - plt.tight_layout() - return fig - - -def visualize_track_labels_single_plane(track_hits_dict, simulation_params, top_tracks_by_charge, - side_idx=0, plane_idx=0, max_tracks=15, figsize=(12, 10)): - """ - Visualize track labels for a single side/plane with distinct colors for top tracks. - - Parameters - ---------- - track_hits_dict : dict - Dictionary of track hits results, keyed by (side_idx, plane_idx). - simulation_params : dict - Dictionary containing simulation parameters. - top_tracks_by_charge : list - List of tuples (track_id, total_charge) from get_top_tracks_by_charge. - side_idx : int, optional - Index of the side to plot (0=West, 1=East), by default 0. - plane_idx : int, optional - Index of the plane to plot (0=U, 1=V, 2=Y), by default 0. - max_tracks : int, optional - Maximum number of tracks to show in legend, by default 15. - figsize : tuple, optional - Figure size (width, height) in inches, by default (12, 10). - - Returns - ------- - matplotlib.figure.Figure - The matplotlib Figure object. - """ - print(f"--- Visualizing Track Labels for Side {side_idx}, Plane {plane_idx} ---") - - num_time_steps = simulation_params['num_time_steps'] - time_step_size_us = simulation_params['time_step_size_us'] - max_abs_indices = simulation_params['max_abs_indices'] - min_abs_indices = simulation_params['min_abs_indices'] - - side_names = ['West Side (x < 0)', 'East Side (x > 0)'] - plane_types = ['First Induction (U)', 'Second Induction (V)', 'Collection (Y)'] - - fig = plt.figure(figsize=figsize, facecolor='white') - gs = gridspec.GridSpec(1, 2, figure=fig, wspace=0.15, width_ratios=[1, 0.12]) - max_time_axis = num_time_steps * time_step_size_us - - distinct_colors = ['#FF0000', '#0000FF', '#00FF00', '#FF00FF', '#00FFFF', - '#FFD700', '#FF8C00', '#8B008B', '#228B22', '#4B0082', - '#FF1493', '#00CED1', '#FF4500', '#9400D3', '#32CD32', - '#8B4513', '#20B2AA', '#FF69B4', '#4169E1', '#DC143C'] - distinct_colors_rgba = [mcolors.to_rgba(c) for c in distinct_colors] - - top_tracks = [tid for tid, _ in top_tracks_by_charge[:max_tracks]] - top_track_to_color = {tid: distinct_colors_rgba[i] for i, tid in enumerate(top_tracks[:len(distinct_colors)])} - cmap = plt.cm.hsv - - def get_track_colors_vectorized(track_ids): - track_ids = np.asarray(track_ids, dtype=np.int64) - colors = np.zeros((len(track_ids), 4)) - hash_values = (track_ids * 2654435761) % 2**32 - colors[:] = cmap(hash_values / (2**32 - 1)) - for tid, color in top_track_to_color.items(): - colors[track_ids == tid] = color - return colors - - s, p = side_idx, plane_idx - ax = fig.add_subplot(gs[0, 0]) - ax.set_facecolor('black') - - min_idx_abs = int(min_abs_indices[s, p]) - max_idx_abs = int(max_abs_indices[s, p]) - - ax.set_xlim(min_idx_abs, max_idx_abs + 1) - ax.set_ylim(0, max_time_axis) - ax.set_box_aspect(1) - ax.set_title(f"{side_names[s]}\n{plane_types[p]}", fontsize=14, pad=10) - ax.set_xlabel('Absolute Wire Index', fontsize=12) - ax.set_ylabel('Time (μs)', fontsize=12) - - plane_key = (s, p) - results = track_hits_dict[plane_key] - num_labeled = int(results['num_labeled']) - - if num_labeled > 0: - labeled = np.array(results['labeled_hits'][:num_labeled]) - tracks = labeled[:, 0].astype(np.int64) - wires = labeled[:, 1] - times = labeled[:, 2] * time_step_size_us - - colors = get_track_colors_vectorized(tracks) - ax.scatter(wires, times, c=colors, s=0.5, alpha=0.8) - ax.text(0.02, 0.98, f"{num_labeled:,} hits\n{len(np.unique(tracks))} tracks", - transform=ax.transAxes, va='top', ha='left', - bbox=dict(facecolor='white', alpha=0.8), fontsize=10) - print(f" {num_labeled:,} labeled hits, {len(np.unique(tracks))} unique tracks") - else: - ax.text(0.5, 0.5, "(No labeled hits)", color='grey', ha='center', va='center', transform=ax.transAxes) - print(" No labeled hits found") - - # Add colorbar/legend - if top_tracks: - cbar_ax = fig.add_subplot(gs[0, 1]) - n_show = min(len(top_tracks), max_tracks) - cbar_ax.set_xlim(0, 1) - cbar_ax.set_ylim(0, n_show) - for i, tid in enumerate(top_tracks[:n_show]): - color = top_track_to_color.get(tid, cmap((tid * 2654435761 % 2**32) / (2**32 - 1))) - y_pos = n_show - 1 - i - rect = plt.Rectangle((0, y_pos), 0.4, 0.9, facecolor=color, edgecolor='black', linewidth=0.5) - cbar_ax.add_patch(rect) - cbar_ax.text(0.5, y_pos + 0.45, f'Track {tid}', ha='left', va='center', fontsize=8) - cbar_ax.set_xticks([]) - cbar_ax.set_yticks([]) - cbar_ax.set_title(f'Top {n_show} Tracks\n(by total charge)', fontsize=11, pad=10) - for spine in cbar_ax.spines.values(): - spine.set_visible(False) - - plt.tight_layout() - return fig - - -def visualize_active_buckets(response_signals, simulation_params, figsize=(20, 10)): - """ - Visualize active buckets in the bucketed simulation output. - - Active buckets are shown as colored rectangles, empty buckets as dark background. - Shows the number of active buckets and coverage percentage for each plane. - - Parameters - ---------- - response_signals : dict - Dictionary of response signals from bucketed simulation. - Each entry is (buckets, num_active, compact_to_key, B1, B2). - simulation_params : dict - Dictionary containing simulation parameters. - figsize : tuple - Figure size (width, height) in inches. - - Returns - ------- - matplotlib.figure.Figure - The matplotlib Figure object. - """ - num_time_steps = simulation_params['num_time_steps'] - time_step_size_us = simulation_params['time_step_size_us'] - num_wires_actual = simulation_params['num_wires_actual'] - max_abs_indices = simulation_params['max_abs_indices'] - min_abs_indices = simulation_params['min_abs_indices'] - - side_names = ['East Side (x < 0)', 'West Side (x >= 0)'] - plane_types = ['First Induction (U)', 'Second Induction (V)', 'Collection (Y)'] - - fig = plt.figure(figsize=figsize, facecolor='white') - gs = gridspec.GridSpec(2, 3, figure=fig, hspace=0.35, wspace=0.30) - max_time_axis = num_time_steps * time_step_size_us - title_size, label_size, tick_size = 14, 12, 10 - - for side_idx in range(2): - for plane_idx in range(3): - ax = fig.add_subplot(gs[side_idx, plane_idx]) - ax.set_facecolor('#1a1a1a') - - plane_key = (side_idx, plane_idx) - min_idx_abs = int(min_abs_indices[side_idx, plane_idx]) - max_idx_abs = int(max_abs_indices[side_idx, plane_idx]) - num_wires = int(num_wires_actual[side_idx, plane_idx]) - - if plane_key not in response_signals: - ax.text(0.5, 0.5, "(No data)", color='grey', ha='center', va='center', transform=ax.transAxes) - ax.set_title(f"{side_names[side_idx]}\n{plane_types[plane_idx]}", fontsize=title_size, pad=10) - continue - - buckets, num_active, compact_to_key, B1, B2 = response_signals[plane_key] - num_active_int = int(num_active) - B1_int = int(B1) - B2_int = int(B2) - - num_buckets_w = (num_wires + B1_int - 1) // B1_int - num_buckets_t = (num_time_steps + B2_int - 1) // B2_int - total_buckets = num_buckets_w * num_buckets_t - coverage_pct = (num_active_int / total_buckets) * 100 if total_buckets > 0 else 0 - - active_keys = np.array(compact_to_key[:num_active_int]) - bucket_w_indices = active_keys // num_buckets_t - bucket_t_indices = active_keys % num_buckets_t - - bucket_grid = np.zeros((num_buckets_w, num_buckets_t)) - for bw, bt in zip(bucket_w_indices, bucket_t_indices): - if 0 <= bw < num_buckets_w and 0 <= bt < num_buckets_t: - bucket_grid[bw, bt] = 1 - - extent = [ - min_idx_abs, - min_idx_abs + num_buckets_w * B1_int, - 0, - num_buckets_t * B2_int * time_step_size_us - ] - - cmap = plt.cm.YlOrRd.copy() - cmap.set_under('#1a1a1a') - - im = ax.imshow( - bucket_grid.T, - aspect='auto', - origin='lower', - extent=extent, - cmap=cmap, - vmin=0.5, - vmax=1.0, - interpolation='nearest' - ) - - ax.set_xlim(min_idx_abs, max_idx_abs + 1) - ax.set_ylim(0, max_time_axis) - ax.set_box_aspect(1) - - plot_title = f"{side_names[side_idx]}\n{plane_types[plane_idx]}" - ax.set_title(plot_title, fontsize=title_size, pad=10) - - ax.set_xlabel('Absolute Wire Index', fontsize=label_size) - ax.set_ylabel('Time (μs)', fontsize=label_size) - ax.tick_params(axis='both', which='major', labelsize=tick_size) - - info_text = f"Active: {num_active_int:,}\nTotal: {total_buckets:,}\nCoverage: {coverage_pct:.1f}%\nBucket: {B1_int}x{B2_int}" - ax.text( - 0.02, 0.98, info_text, - transform=ax.transAxes, - va='top', ha='left', - fontsize=9, - bbox=dict(facecolor='white', alpha=0.85, edgecolor='gray', boxstyle='round,pad=0.3') - ) - - fig.suptitle('Active Buckets Visualization (Bucketed Mode)', fontsize=16, y=0.98) - return fig - - -def visualize_by_index(wire_signals_dict, simulation_params, indices_list, figsize=(10, 8), - sparse_data=False): - """ - Visualize wire signals at specific wire indices across time. - - Parameters - ---------- - wire_signals_dict : dict - Dictionary of wire signals, keyed by (side_idx, plane_idx). - simulation_params : dict - Dictionary containing simulation parameters. - indices_list : list - List of wire indices to plot. - figsize : tuple, optional - Figure size (width, height) in inches, by default (10, 8). - sparse_data : bool, optional - If True, expect sparse format (indices, values). - - Returns - ------- - matplotlib.figure.Figure - The matplotlib Figure object. - """ - num_time_steps = simulation_params['num_time_steps'] - time_step_size_us = simulation_params['time_step_size_us'] - num_wires_actual = simulation_params['num_wires_actual'] - max_abs_indices = simulation_params['max_abs_indices'] - min_abs_indices = simulation_params['min_abs_indices'] - - side_names = ['West Side (x < 0)', 'East Side (x > 0)'] - plane_types = ['First Induction (U)', 'Second Induction (V)', 'Collection (Y)'] - - time_axis = np.arange(num_time_steps) * time_step_size_us - - fig, axes = plt.subplots(2, 3, figsize=figsize) - if axes.ndim == 1: - axes = axes.reshape(1, -1) - - for side_idx in range(2): - for plane_idx in range(3): - ax = axes[side_idx, plane_idx] - - plane_key = (side_idx, plane_idx) - min_idx_abs = int(min_abs_indices[side_idx, plane_idx]) - max_idx_abs = int(max_abs_indices[side_idx, plane_idx]) - actual_wire_count = int(num_wires_actual[side_idx, plane_idx]) - - plot_title = f"{side_names[side_idx]}\n{plane_types[plane_idx]}" - ax.set_title(plot_title, fontsize=12) - - if plane_key not in wire_signals_dict or actual_wire_count == 0: - ax.text(0.5, 0.5, "(0 wires active)", ha='center', va='center', transform=ax.transAxes) - ax.set_xlabel('Time (μs)') - ax.set_ylabel('Signal Strength') - continue - - if sparse_data: - indices, values = wire_signals_dict[plane_key] - if len(values) == 0: - ax.text(0.5, 0.5, "(No data)", ha='center', va='center', transform=ax.transAxes) - ax.set_xlabel('Time (μs)') - ax.set_ylabel('Signal Strength') - continue - - indices_np = np.array(indices) - values_np = np.array(values) - - for wire_idx in indices_list: - rel_idx = wire_idx - min_idx_abs - mask = indices_np[:, 0] == rel_idx - if np.any(mask): - wire_times = indices_np[mask, 1] * time_step_size_us - wire_values = values_np[mask] - sort_order = np.argsort(wire_times) - ax.plot(wire_times[sort_order], wire_values[sort_order], - label=f'Wire {wire_idx}', alpha=0.8, marker='.', markersize=1, linestyle='-') - else: - signal_data = np.array(wire_signals_dict[plane_key]) - - for wire_idx in indices_list: - rel_idx = wire_idx - min_idx_abs - if 0 <= rel_idx < signal_data.shape[0]: - wire_signal = signal_data[rel_idx, :] - ax.plot(time_axis, wire_signal, label=f'Wire {wire_idx}', alpha=0.8) - - ax.set_xlabel('Time (μs)') - ax.set_ylabel('Signal Strength') - ax.grid(True, alpha=0.3) - - if len(indices_list) <= 10: - ax.legend(fontsize=8) - - plt.tight_layout() - return fig - - -def visualize_wire_planes_colored_by_index(detector_config, figsize=(15, 10)): - """ - Visualize all 6 wire planes (3 on each side) of the LArTPC detector, - coloring the wires based on their index. - - Parameters - ---------- - detector_config : dict - Detector configuration dictionary with pre-calculated parameters. - figsize : tuple, optional - Figure size (width, height) in inches, by default (15, 10). - - Returns - ------- - matplotlib.figure.Figure - The matplotlib Figure object. - """ - # Extract detector dimensions - detector_dims = detector_config['detector']['dimensions'] - detector_y = detector_dims['y'] - detector_z = detector_dims['z'] - - # Extract wire plane information - sides = detector_config['wire_planes']['sides'] - - # Create figure and axes - 2 rows (for sides) x 3 columns (for planes) - fig, axes = plt.subplots(2, 3, figsize=figsize) - - # Set up titles for the planes - plane_types = ['First Induction (U)', 'Second Induction (V)', 'Collection (Y)'] - - # Define a colormap for the wire indices - cmap = plt.cm.viridis - - # Loop through each side (0: x < 0, 1: x > 0) - for side_idx, side in enumerate(sides): - side_desc = side['description'] - - # Loop through each plane on this side - for plane_idx, plane in enumerate(side['planes']): - ax = axes[side_idx, plane_idx] - - # Extract plane parameters - angle_deg = plane['angle'] - angle_rad = np.radians(angle_deg) - wire_spacing = plane['wire_spacing'] - distance_from_anode = plane['distance_from_anode'] - - # Display information - title = f"{side_desc}\n{plane_types[plane_idx]}" - ax.set_title(title) - - # Draw a representation of the detector boundaries - # Z is horizontal (width) and Y is vertical (height) - ax.add_patch(plt.Rectangle((0, 0), detector_z, detector_y, fill=False, color='black', linestyle='--')) - - # Calculate sine and cosine once - cos_theta = np.cos(angle_rad) - sin_theta = np.sin(angle_rad) - - # Calculate the parameter values for all four corners of the detector - corners = [ - (0, 0), # Bottom-left (y=0, z=0) - (detector_y, 0), # Top-left (y=detector_y, z=0) - (0, detector_z), # Bottom-right (y=0, z=detector_z) - (detector_y, detector_z) # Top-right (y=detector_y, z=detector_z) - ] - - # NEW PARAMETRIZATION: r = z * cos(θ) + y * sin(θ) - r_values = [z * cos_theta + y * sin_theta for y, z in corners] - r_min = min(r_values) - r_max = max(r_values) - - # Calculate index offset for negative angles - offset = 0 - if r_min < 0: - offset = int(np.abs(np.floor(r_min / wire_spacing))) + 1 - - # Calculate exact wire index range with offset applied - idx_min = int(np.floor(r_min / wire_spacing)) + offset - idx_max = int(np.ceil(r_max / wire_spacing)) + offset - - # Store the number of wires for normalization - num_wires = idx_max - idx_min + 1 - - # Draw each wire within this range - for wire_idx in range(idx_min, idx_max + 1): - # Wire parameter r (adjusted for offset) - r = (wire_idx - offset) * wire_spacing - - # Calculate intersection points with the four boundaries - # Using parametrization: r = z * cos(θ) + y * sin(θ) - intersections = [] - - # Check intersection with y=0 (bottom boundary) - # r = z * cos(θ) + 0 * sin(θ) => z = r / cos(θ) - if abs(cos_theta) > 1e-10: - z = r / cos_theta - if 0 <= z <= detector_z: - intersections.append((0, z)) - - # Check intersection with y=detector_y (top boundary) - # r = z * cos(θ) + detector_y * sin(θ) => z = (r - detector_y * sin(θ)) / cos(θ) - if abs(cos_theta) > 1e-10: - z = (r - detector_y * sin_theta) / cos_theta - if 0 <= z <= detector_z: - intersections.append((detector_y, z)) - - # Check intersection with z=0 (left boundary) - # r = 0 * cos(θ) + y * sin(θ) => y = r / sin(θ) - if abs(sin_theta) > 1e-10: - y = r / sin_theta - if 0 <= y <= detector_y: - intersections.append((y, 0)) - - # Check intersection with z=detector_z (right boundary) - # r = detector_z * cos(θ) + y * sin(θ) => y = (r - detector_z * cos(θ)) / sin(θ) - if abs(sin_theta) > 1e-10: - y = (r - detector_z * cos_theta) / sin_theta - if 0 <= y <= detector_y: - intersections.append((y, detector_z)) - - # Draw the wire if we have at least 2 intersections - if len(intersections) >= 2: - # Sort intersections appropriately - if len(intersections) > 2: - # Remove duplicates first - unique_intersections = [] - for pt in intersections: - is_duplicate = False - for existing in unique_intersections: - if abs(pt[0] - existing[0]) < 1e-6 and abs(pt[1] - existing[1]) < 1e-6: - is_duplicate = True - break - if not is_duplicate: - unique_intersections.append(pt) - intersections = unique_intersections - - if len(intersections) >= 2: - # Sort by the coordinate that varies most - p1, p2 = intersections[0], intersections[1] - dy = abs(p2[0] - p1[0]) - dz = abs(p2[1] - p1[1]) - - if dz > dy: - intersections.sort(key=lambda p: p[1]) # Sort by z - else: - intersections.sort(key=lambda p: p[0]) # Sort by y - - p1, p2 = intersections[0], intersections[-1] - - # Calculate normalized wire index for coloring - norm_idx = (wire_idx - idx_min) / max(1, num_wires - 1) - color = cmap(norm_idx) - - # Plot with Z on x-axis and Y on y-axis - ax.plot([p1[1], p2[1]], [p1[0], p2[0]], color=color, linewidth=0.8, alpha=0.7) - - # Set axis properties - Z horizontal, Y vertical - ax.set_xlabel('Z Position (cm)') - ax.set_ylabel('Y Position (cm)') - ax.set_xlim(0, detector_z) - ax.set_ylim(0, detector_y) - ax.grid(alpha=0.3) - - # Add plane info as text - info_text = f"Angle: {angle_deg}°\nSpacing: {wire_spacing} cm\nDistance from anode: {distance_from_anode} cm" - ax.text(0.05, 0.95, info_text, transform=ax.transAxes, va='top', - bbox=dict(facecolor='white', alpha=0.7)) - - # Add a mini colorbar for this subplot - divider = make_axes_locatable(ax) - cax = divider.append_axes("right", size="5%", pad=0.05) - sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=idx_min, vmax=idx_max)) - sm.set_array([]) - cbar = plt.colorbar(sm, cax=cax) - cbar.set_label('Wire Index') - - plt.tight_layout() - return fig diff --git a/closure/archive/gradient_test/gradient_test/tools/wires.py b/closure/archive/gradient_test/gradient_test/tools/wires.py deleted file mode 100644 index cd0992c..0000000 --- a/closure/archive/gradient_test/gradient_test/tools/wires.py +++ /dev/null @@ -1,1067 +0,0 @@ -""" -Wire signal calculations for LArTPC simulation. - -This module contains all wire-related calculations for processing charge deposits -into wire signals. It supports two parallel simulation paths: - -Sections: -1. SHARED: Wire geometry calculations -2. RESPONSE PATH: Kernel-based signal generation -3. HIT PATH: Direct diffusion calculation -""" - -import jax -import jax.numpy as jnp -from functools import partial - - -# ============================================================================ -# SHARED: Wire Geometry -# ============================================================================ - -@partial(jax.jit, static_argnums=(3, 4)) -def compute_wire_distances( - positions_yz_centered_cm, angle_rad, wire_spacing_cm, max_wire_idx_abs, index_offset -): - """ - Calculate the closest wire indices and distances for each hit in a detector plane. - - Parameters - ---------- - positions_yz_centered_cm : jnp.ndarray - Array of shape (n_hits, 2) containing the (y, z) positions in cm. - angle_rad : float - Wire angle in radians, measured in the YZ plane. - wire_spacing_cm : float - Spacing between wires in cm. - max_wire_idx_abs : int - Maximum absolute wire index. - index_offset : int - Wire index offset. - - Returns - ------- - closest_indices_abs : jnp.ndarray - Array of shape (n_hits,) containing the absolute indices of the closest wires. - closest_wire_distances : jnp.ndarray - Array of shape (n_hits,) containing the distances to the closest wires in cm. - """ - cos_theta = jnp.cos(angle_rad) - sin_theta = jnp.sin(angle_rad) - - # Extract y and z components from positions - P_y_cm = positions_yz_centered_cm[:, 0] # Shape: (n_hits,) - P_z_cm = positions_yz_centered_cm[:, 1] # Shape: (n_hits,) - - # Calculate r_prime (the wire coordinate) for all positions - r_prime = P_y_cm * sin_theta + P_z_cm * cos_theta # Shape: (n_hits,) - - # Calculate index and distance to closest wire - idx_rel_floor = jnp.floor(r_prime / (wire_spacing_cm + 1e-9) - 1e-9) # Shape: (n_hits,) - idx_rel_ceil = jnp.ceil(r_prime / (wire_spacing_cm + 1e-9) + 1e-9) # Shape: (n_hits,) - - dist_floor = r_prime - idx_rel_floor * wire_spacing_cm # Shape: (n_hits,) - dist_ceil = r_prime - idx_rel_ceil * wire_spacing_cm # Shape: (n_hits,) - - is_floor_closer = jnp.abs(dist_floor) <= jnp.abs(dist_ceil) # Shape: (n_hits,) - - closest_idx_rel = jnp.where(is_floor_closer, idx_rel_floor, idx_rel_ceil) # Shape: (n_hits,) - closest_wire_distances = jnp.where(is_floor_closer, dist_floor, dist_ceil) # Shape: (n_hits,) - - closest_indices_abs = (closest_idx_rel.astype(jnp.int32) + index_offset) # Shape: (n_hits,) - - return closest_indices_abs, closest_wire_distances - - -@partial(jax.jit, static_argnums=(3,)) -def calculate_k_nearest_wires(positions_yz_cm, angle_rad, wire_spacing_cm, - K, max_wire_idx_abs, index_offset): - """ - Calculate K nearest wire indices and distances for each hit in a detector plane. - - Parameters - ---------- - positions_yz_cm : jnp.ndarray - Array of shape (n_hits, 2) containing the (y, z) positions in cm. - angle_rad : float - Wire angle in radians, measured in the YZ plane. - wire_spacing_cm : float - Spacing between wires in cm. - K : int - Number of nearest wires to find. - max_wire_idx_abs : int - Maximum absolute wire index. - index_offset : int - Wire index offset. - - Returns - ------- - wire_indices : jnp.ndarray - Array of shape (n_hits, K) containing the indices of the K nearest wires. - wire_distances : jnp.ndarray - Array of shape (n_hits, K) containing the distances to K nearest wires. - """ - cos_theta = jnp.cos(angle_rad) - sin_theta = jnp.sin(angle_rad) - - # Extract y and z components - P_y_cm = positions_yz_cm[:, 0] - P_z_cm = positions_yz_cm[:, 1] - - # Calculate r_prime (the wire coordinate) for all positions - r_prime = P_y_cm * sin_theta + P_z_cm * cos_theta - - # Find the closest wire index - closest_idx_rel = jnp.round(r_prime / wire_spacing_cm).astype(jnp.int32) - closest_idx_abs = closest_idx_rel + index_offset - - # Calculate how many wires to take on each side - half_k = (K - 1) // 2 - - # Create offsets array - offsets = jnp.arange(-half_k, K - half_k) - - # Calculate indices for K nearest wires using broadcasting - # Shape: (n_hits, 1) + (K,) -> (n_hits, K) - wire_indices = closest_idx_abs[:, jnp.newaxis] + offsets - - # Calculate distances for each wire - # Shape: (n_hits, 1) - (n_hits, K) * scalar -> (n_hits, K) - wire_r_values = (wire_indices - index_offset) * wire_spacing_cm - wire_distances = r_prime[:, jnp.newaxis] - wire_r_values - - # Replace out-of-bounds indices with -1 - valid_mask = (wire_indices >= 0) & (wire_indices <= max_wire_idx_abs) - wire_indices = jnp.where(valid_mask, wire_indices, -1) - wire_distances = jnp.where(valid_mask, wire_distances, jnp.nan) - - return wire_indices, wire_distances - - -@jax.jit -def compute_deposit_wire_angles(theta, phi, wire_angle): - """ - Calculate angles between a deposit segment and a wire/plane. - - Parameters - ---------- - theta : float - Polar angle (0 to π) from the positive z-axis in radians. - phi : float - Azimuthal angle (-π to π) from the positive x-axis in radians. - wire_angle : float - Angle of the wire in the yz-plane in radians. - - Returns - ------- - angle_to_wire : float - Acute angle between segment and wire in radians (theta_xz). - angle_to_plane : float - Acute angle between segment and wire plane in radians (theta_y). - """ - # Calculate segment direction vector - dx = jnp.sin(theta) * jnp.cos(phi) - dy = jnp.sin(theta) * jnp.sin(phi) - dz = jnp.cos(theta) - - # Calculate wire direction vector - wire_dy = jnp.cos(wire_angle) - wire_dz = jnp.sin(wire_angle) - - # Calculate dot product for segment-to-wire angle - dot_product = dy * wire_dy + dz * wire_dz - - # For undirected lines, use absolute value of dot product - # This gives the acute angle between lines (0-90°) - dot_product_abs = jnp.abs(dot_product) - dot_product_clipped = jnp.clip(dot_product_abs, 0.0, 1.0) - angle_to_wire = jnp.arccos(dot_product_clipped) - - # Calculate angle to plane (always the acute angle) - dx_abs = jnp.abs(dx) - dx_clipped = jnp.clip(dx_abs, 0.0, 1.0) - angle_to_plane = jnp.arccos(dx_clipped) - - # theta_xz, theta_y - return angle_to_wire, angle_to_plane - - -# Vectorized version that can handle arrays of inputs -compute_deposit_wire_angles_vmap = jax.vmap( - compute_deposit_wire_angles, in_axes=(0, 0, None) -) - - -@partial(jax.jit, static_argnames=['clipping_value_deg']) -def compute_angular_scaling(theta_xz, theta_y, clipping_value_deg=5.0): - """ - Calculate angular scaling factors based on angles to wire and plane. - - Parameters - ---------- - theta_xz : float - Angle to wire in the xz-plane in radians. - theta_y : float - Angle to wire plane in radians. - clipping_value_deg : float, optional - Clipping value in degrees to avoid extreme angles, by default 5.0. - - Returns - ------- - scaling_factor : float - Scaling factor for signal calculation. - """ - # Clip angles to avoid extreme values - clipping_value_rad = jnp.radians(clipping_value_deg) - - theta_xz = jnp.abs(theta_xz) - theta_y = jnp.abs(theta_y) - - theta_xz = jnp.clip(theta_xz, clipping_value_rad, jnp.pi/2 - clipping_value_rad) - theta_y = jnp.clip(theta_y, clipping_value_rad, jnp.pi/2 - clipping_value_rad) - - scaling_factor = 1/(jnp.cos(theta_xz) * jnp.sin(theta_y)) - - return scaling_factor - - -compute_angular_scaling_vmap = jax.vmap( - compute_angular_scaling, in_axes=(0, 0) -) - - -# ============================================================================ -# HIT PATH: Direct Diffusion Calculation -# ============================================================================ - -@jax.jit -def compute_gaussian_diffusion( - wire_distance_cm, time_difference_us, drift_time_us, - longitudinal_diffusion_cm2_us, transverse_diffusion_cm2_us, drift_velocity_cm_us -): - """ - Calculate normalized 2D Gaussian response for charge diffusion without charge scaling. - - Parameters - ---------- - wire_distance_cm : jnp.ndarray - Distance from the hit to the wire in cm. - time_difference_us : jnp.ndarray - Time difference between drift time and bin center in μs. - drift_time_us : float - Drift time in μs. - longitudinal_diffusion_cm2_us : float - Longitudinal diffusion coefficient in cm²/μs. - transverse_diffusion_cm2_us : float - Transverse diffusion coefficient in cm²/μs. - drift_velocity_cm_us : float - Drift velocity in cm/μs. - - Returns - ------- - response : jnp.ndarray - Normalized diffusion response. - """ - # Calculate drift-dependent sigmas with diffusion - # σ² = 2Dt (where t is drift_time) - - # Spatial diffusion (transverse) - sigma_wire_squared = 2.0 * transverse_diffusion_cm2_us * drift_time_us - - # Time diffusion (longitudinal) - convert from spatial to time units - longitudinal_diffusion_us2_us = longitudinal_diffusion_cm2_us / (drift_velocity_cm_us ** 2) - sigma_time_squared = 2.0 * longitudinal_diffusion_us2_us * drift_time_us - - # Ensure minimum sigma values - min_sigma = 1e-4 - sigma_wire_squared = jnp.maximum(sigma_wire_squared, min_sigma ** 2) - sigma_time_squared = jnp.maximum(sigma_time_squared, min_sigma ** 2) - - # Calculate Gaussian terms - wire_term = -(wire_distance_cm**2) / (2.0 * sigma_wire_squared) - time_term = -(time_difference_us**2) / (2.0 * sigma_time_squared) - - # Calculate normalization factor - norm_factor = 1.0 / (2.0 * jnp.pi * jnp.sqrt(sigma_wire_squared) * jnp.sqrt(sigma_time_squared)) - - # Apply Gaussian formula - response = norm_factor * jnp.exp(wire_term + time_term) - - return jnp.maximum(response, 0.0) - - -@jax.jit -def compute_transverse_diffusion( - wire_distance_cm, drift_time_us, transverse_diffusion_cm2_us -): - """ - Calculate normalized 1D Gaussian response for wire (transverse) diffusion. - - Parameters - ---------- - wire_distance_cm : jnp.ndarray - Distance from the hit to the wire in cm. - drift_time_us : float - Drift time in μs. - transverse_diffusion_cm2_us : float - Transverse diffusion coefficient in cm²/μs. - - Returns - ------- - response : jnp.ndarray - Normalized wire diffusion response. - """ - # Spatial diffusion (transverse) - sigma_wire_squared = 2.0 * transverse_diffusion_cm2_us * drift_time_us - - # Ensure minimum sigma value - min_sigma = 1e-4 - sigma_wire_squared = jnp.maximum(sigma_wire_squared, min_sigma ** 2) - - # Calculate Gaussian term - wire_term = -(wire_distance_cm**2) / (2.0 * sigma_wire_squared) - - # Calculate normalization factor for 1D Gaussian - norm_factor = 1.0 / (jnp.sqrt(2.0 * jnp.pi * sigma_wire_squared)) - - # Apply Gaussian formula - response = norm_factor * jnp.exp(wire_term) - - return jnp.maximum(response, 0.0) - - -@jax.jit -def compute_longitudinal_diffusion( - time_difference_us, drift_time_us, - longitudinal_diffusion_cm2_us, drift_velocity_cm_us -): - """ - Calculate normalized 1D Gaussian response for time (longitudinal) diffusion. - - Parameters - ---------- - time_difference_us : jnp.ndarray - Time difference between drift time and bin center in μs. - drift_time_us : float - Drift time in μs. - longitudinal_diffusion_cm2_us : float - Longitudinal diffusion coefficient in cm²/μs. - drift_velocity_cm_us : float - Drift velocity in cm/μs. - - Returns - ------- - response : jnp.ndarray - Normalized time diffusion response. - """ - # Time diffusion (longitudinal) - convert from spatial to time units - longitudinal_diffusion_us2_us = longitudinal_diffusion_cm2_us / (drift_velocity_cm_us ** 2) - sigma_time_squared = 2.0 * longitudinal_diffusion_us2_us * drift_time_us - - # Ensure minimum sigma value - min_sigma = 1e-4 - sigma_time_squared = jnp.maximum(sigma_time_squared, min_sigma ** 2) - - # Calculate Gaussian term - time_term = -(time_difference_us**2) / (2.0 * sigma_time_squared) - - # Calculate normalization factor for 1D Gaussian - norm_factor = 1.0 / (jnp.sqrt(2.0 * jnp.pi * sigma_time_squared)) - - # Apply Gaussian formula - response = norm_factor * jnp.exp(time_term) - - return jnp.maximum(response, 0.0) - - -@partial(jax.jit, static_argnames=['K_wire', 'K_time', 'num_wires', 'num_time_steps']) -def prepare_deposit_with_diffusion( - charge, drift_time_us, drift_distance_cm, closest_index_abs, closest_wire_distance, - attenuation_factor, theta_xz_rad, theta_y_rad, angular_scaling_factor, valid_hit, - K_wire, K_time, wire_spacing_cm, time_step_size_us, - longitudinal_diffusion_cm2_us, transverse_diffusion_cm2_us, drift_velocity_cm_us, - min_idx_abs, num_wires, num_time_steps -): - """ - Prepare deposit data WITH K_wire x K_time diffusion (hit path). - - This function calculates diffusion directly in a K_wire x K_time grid - for the hit path. The diffusion is computed without detector - response to maintain accurate particle-to-signal attribution. - - Parameters - ---------- - charge : float - Charge deposited by the hit. - drift_time_us : float - Drift time of the hit in μs. - drift_distance_cm : float - Drift distance of the hit in cm. - closest_index_abs : int - Absolute index of the closest wire. - closest_wire_distance : float - Distance to the closest wire in cm. - attenuation_factor : float - Attenuation factor due to electron lifetime. - theta_xz_rad : float - Angle to wire in the xz-plane in radians. - theta_y_rad : float - Angle to wire plane in radians. - angular_scaling_factor : float - Angular scaling factor for the hit. - valid_hit : bool - Whether the hit is valid. - K_wire : int - Half-width of wire neighbors to consider. - K_time : int - Half-width of time bins to consider. - wire_spacing_cm : float - Spacing between wires in cm. - time_step_size_us : float - Size of time step in μs. - longitudinal_diffusion_cm2_us : float - Longitudinal diffusion coefficient in cm²/μs. - transverse_diffusion_cm2_us : float - Transverse diffusion coefficient in cm²/μs. - drift_velocity_cm_us : float - Drift velocity in cm/μs. - min_idx_abs : int - Minimum absolute wire index. - num_wires : int - Number of wires in the plane. - num_time_steps : int - Number of time steps in the simulation. - - Returns - ------- - tuple - Tuple containing indices and values for the hit: - (wire_indices_rel, time_indices_out, signal_values_out) - """ - # Only process if valid hit - charge = jnp.where(valid_hit, charge, 0.0) - - # 1. Calculate time bins and offsets (using K as half-width) - central_time_bin = jnp.floor(drift_time_us / time_step_size_us).astype(jnp.int32) - time_bin_offsets = jnp.arange(-K_time, K_time + 1) # 2K+1 values - time_bins = central_time_bin + time_bin_offsets - bin_center_times = (time_bins + 0.5) * time_step_size_us - time_differences_us = drift_time_us - bin_center_times # Shape: (2*K_time+1,) - - # 2. Calculate wire indices and distances (using K as half-width) - relative_indices = jnp.arange(-K_wire, K_wire + 1) # 2K+1 values - wire_indices = closest_index_abs + relative_indices # Shape: (2*K_wire+1,) - wire_distances_cm = closest_wire_distance + relative_indices * wire_spacing_cm # Shape: (2*K_wire+1,) - - # 3. Apply charge scaling and attenuation - charge_scaled = charge * angular_scaling_factor - attenuated_charge = charge_scaled * attenuation_factor - - # 4. Calculate diffusion response array ((2*K_wire+1) x (2*K_time+1)) - # Reshape for broadcasting - wire_distances_2d = jnp.expand_dims(jnp.abs(wire_distances_cm), axis=1) # Shape: (2*K_wire+1, 1) - time_differences_2d = jnp.expand_dims(time_differences_us, axis=0) # Shape: (1, 2*K_time+1) - - # Calculate normalized wire diffusion response - wire_diffusion = compute_transverse_diffusion( - wire_distances_2d, - drift_time_us, - transverse_diffusion_cm2_us - ) # Shape: (2*K_wire+1, 1) - - # Calculate normalized time diffusion response - time_diffusion = compute_longitudinal_diffusion( - time_differences_2d, - drift_time_us, - longitudinal_diffusion_cm2_us, - drift_velocity_cm_us - ) # Shape: (1, 2*K_time+1) - - # Combine wire and time diffusion responses using broadcasting - diffusion_response_normalized = wire_diffusion * time_diffusion # Shape: (2*K_wire+1, 2*K_time+1) - - # Apply charge for full diffusion response - diffusion_response = diffusion_response_normalized * attenuated_charge - - # Create validity mask - wire_valid = (wire_indices >= 0) & (wire_indices < num_wires) - time_valid = (time_bins >= 0) & (time_bins < num_time_steps) - - # Combine validity masks - expand to 2D - wire_valid_2d = wire_valid[:, jnp.newaxis] # Shape: (2*K_wire+1, 1) - time_valid_2d = time_valid[jnp.newaxis, :] # Shape: (1, 2*K_time+1) - valid_mask_2d = wire_valid_2d & time_valid_2d & valid_hit # Shape: (2*K_wire+1, 2*K_time+1) - - # Apply validity mask to zero out invalid entries - wire_indices_rel = jnp.where(wire_valid, wire_indices - min_idx_abs, 0) - time_indices_out = time_bins - signal_values_2d = jnp.where(valid_mask_2d, diffusion_response, 0.0) - - # Calculate total number of elements - num_wire_bins = 2 * K_wire + 1 - num_time_bins = 2 * K_time + 1 - - # Flatten the arrays for output - wire_indices_rel_flat = jnp.repeat(wire_indices_rel, num_time_bins) - time_indices_out_flat = jnp.tile(time_indices_out, num_wire_bins) - signal_values_out = signal_values_2d.reshape(-1) - - # Return processed indices and values - return wire_indices_rel_flat, time_indices_out_flat, signal_values_out - - -@partial(jax.jit, static_argnames=["num_wires", "num_time_steps"]) -def accumulate_signals(indices_and_values, num_wires, num_time_steps): - """ - Fill output array with calculated signal values. - - Parameters - ---------- - indices_and_values : tuple - Tuple of (wire_indices, time_indices, signal_values). - num_wires : int - Number of wires in the plane. - num_time_steps : int - Number of time steps in the simulation. - - Returns - ------- - jnp.ndarray - Filled signals array of shape (num_wires, num_time_steps). - """ - wire_indices, time_indices, signal_values = indices_and_values - - # Create output array - wire_signals = jnp.zeros((num_wires, num_time_steps)) - - # Fill array using scatter_add - wire_signals = wire_signals.at[ - wire_indices, time_indices - ].add(signal_values) - - return wire_signals - - -# ============================================================================ -# RESPONSE PATH: Kernel-based Signal Generation -# ============================================================================ - -@partial(jax.jit, static_argnames=['num_wires']) -def prepare_deposit_for_response( - charge, drift_time_us, closest_index_abs, closest_wire_distance, - attenuation_factor, valid_hit, - wire_spacing_cm, time_step_size_us, - min_idx_abs, num_wires -): - """ - Process a single hit without diffusion (handled by response kernels). - - Parameters - ---------- - charge : float - Charge deposited by the hit. - drift_time_us : float - Drift time of the hit in μs. - closest_index_abs : int - Absolute index of the closest wire. - closest_wire_distance : float - Distance to the closest wire in cm. - attenuation_factor : float - Attenuation factor due to electron lifetime. - valid_hit : bool - Whether the hit is valid. - wire_spacing_cm : float - Spacing between wires in cm. - time_step_size_us : float - Size of time step in μs. - min_idx_abs : int - Minimum absolute wire index. - num_wires : int - Number of wires in the plane. - - Returns - ------- - tuple - Tuple containing indices, offsets, and intensity: - (wire_index, wire_offset, time_index, time_offset, intensity) - """ - # Only process if valid hit - charge = jnp.where(valid_hit, charge, 0.0) - - # Calculate central time bin and offset - time_index = jnp.floor(drift_time_us / time_step_size_us).astype(jnp.int32) - time_offset = (drift_time_us / time_step_size_us) - time_index - - # Calculate wire offset (fractional part of wire position) - wire_offset = jnp.abs(closest_wire_distance) / wire_spacing_cm - - # Apply charge scaling and attenuation - intensity = charge * attenuation_factor - - # Convert to relative wire index - wire_index_rel = jnp.where( - (closest_index_abs >= 0) & (closest_index_abs < num_wires), - closest_index_abs - min_idx_abs, - -1 # Invalid index - ) - - # Set intensity to 0 for invalid hits - intensity = jnp.where( - valid_hit & (wire_index_rel >= 0), - intensity, - 0.0 - ) - - return wire_index_rel, wire_offset, time_index, time_offset, intensity - - -@partial(jax.jit, static_argnames=('num_wires', 'num_time_steps', 'kernel_num_wires', 'kernel_height')) -def accumulate_response_signals(wire_indices, time_indices, intensities, contributions, - num_wires, num_time_steps, kernel_num_wires, kernel_height): - """ - Fill signals array from kernel contributions for multiple segments. - - This function efficiently accumulates kernel contributions from multiple segments - into a signals array without explicit loops, using JAX's vectorized operations. - - Parameters - ---------- - wire_indices : jnp.ndarray - (N,) center wire index for each segment. - time_indices : jnp.ndarray - (N,) start time index for each segment. - intensities : jnp.ndarray - (N,) intensity scaling factor for each segment. - contributions : jnp.ndarray - (N, kernel_num_wires, kernel_height) kernel response for each segment. - num_wires : int - Total number of wires in output (static). - num_time_steps : int - Total number of time steps in output (static). - kernel_num_wires : int - Number of wires in kernel (static). - kernel_height : int - Number of time bins in kernel (static). - - Returns - ------- - signals : jnp.ndarray - (num_wires, num_time_steps) accumulated wire signals. - """ - # Initialize output array - signals = jnp.zeros((num_wires, num_time_steps)) - - # Calculate wire offset to center kernel on wire_indices - wire_offset = kernel_num_wires // 2 - - # Create kernel index offsets (reused for all segments) - kernel_wire_offsets = jnp.arange(kernel_num_wires) # shape: (kernel_num_wires,) - kernel_time_offsets = jnp.arange(kernel_height) # shape: (kernel_height,) - - # Compute absolute wire positions for all segments - # Shape: (N, kernel_num_wires) - wire_positions = wire_indices[:, None] - wire_offset + kernel_wire_offsets[None, :] - - # Compute absolute time positions for all segments - # Shape: (N, kernel_height) - time_positions = time_indices[:, None] + kernel_time_offsets[None, :] - - # Scale all contributions by their intensities - # Shape: (N, kernel_num_wires, kernel_height) - scaled_contributions = contributions * intensities[:, None, None] - - # Create flattened indices for scatter operation - # Flatten wire positions: (N * kernel_num_wires,) - flat_wire_indices = wire_positions.reshape(-1) - - # Create corresponding time indices for each wire - # We need to broadcast time_positions to match wire dimensions - # Shape: (N, kernel_num_wires, kernel_height) -> (N * kernel_num_wires * kernel_height,) - time_positions_broadcast = jnp.broadcast_to( - time_positions[:, None, :], - (wire_indices.shape[0], kernel_num_wires, kernel_height) - ) - flat_time_indices = time_positions_broadcast.reshape(-1) - - # Flatten contributions - # Shape: (N * kernel_num_wires * kernel_height,) - flat_contributions = scaled_contributions.reshape(-1) - - # Create 2D indices for scatter - # Wire indices need to be repeated for each time bin - wire_indices_repeated = jnp.repeat(flat_wire_indices, kernel_height) - - # Use .at[].add() to accumulate all contributions at once - # mode='drop' will silently ignore out-of-bounds indices - signals = signals.at[wire_indices_repeated, flat_time_indices].add(flat_contributions, mode='drop') - - return signals - - -# ============================================================================ -# SPARSE BUCKETED ACCUMULATION (for very large detectors) -# ============================================================================ - -@partial(jax.jit, static_argnames=('B1', 'B2', 'num_wires', 'num_time_steps', 'max_buckets')) -def build_bucket_mapping(wire_indices, time_indices, - B1, B2, num_wires, num_time_steps, max_buckets): - """ - Build point_to_compact mapping for sparse bucketing. - - Phase 1 of the sparse bucketing algorithm. For each segment at (wire, time), - its kernel can touch up to 4 buckets. This function computes which 4 buckets - each segment touches and creates a compact mapping to active bucket indices. - - Args: - wire_indices: (N,) center wire index for each segment - time_indices: (N,) start time index for each segment - B1: Bucket size in wire direction (= 2 * kernel_num_wires) - B2: Bucket size in time direction (= 2 * kernel_height) - num_wires: Total wires (X dimension) - num_time_steps: Total time steps (Y dimension) - max_buckets: Maximum active buckets to allocate - - Returns: - point_to_compact: (N, 4) int32 - maps (segment, quadrant) to compact index - num_active: scalar int32 - number of unique active buckets - compact_to_key: (max_buckets,) int32 - maps compact index to bucket key - """ - N = wire_indices.shape[0] - # Use ceiling division to ensure all buckets have unique keys - # Floor division causes collisions when dimensions don't divide evenly - NUM_BUCKETS_T = (num_time_steps + B2 - 1) // B2 - - # Wire offset: kernel_num_wires // 2, and B1 = 2 * kernel_num_wires - # So kernel_num_wires = B1 // 2, and wire_offset = B1 // 4 - wire_offset = B1 // 4 - - # Home bucket for each segment, based on kernel START position (not center) - # This must match scatter_contributions_to_buckets which uses (wire_indices - wire_offset) - home_bw = (wire_indices - wire_offset) // B1 # (N,) - home_bt = time_indices // B2 # (N,) - - # 4 potential buckets per segment (quadrants) - # Quadrant layout: - # 0: (home_bw, home_bt) - home bucket - # 1: (home_bw, home_bt + 1) - right neighbor (time) - # 2: (home_bw + 1, home_bt) - bottom neighbor (wire) - # 3: (home_bw + 1, home_bt + 1) - bottom-right neighbor - offsets_w = jnp.array([0, 0, 1, 1], dtype=jnp.int32) - offsets_t = jnp.array([0, 1, 0, 1], dtype=jnp.int32) - - bucket_bw = home_bw[:, None] + offsets_w # (N, 4) - bucket_bt = home_bt[:, None] + offsets_t # (N, 4) - - # Pack into single key: key = bw * NUM_BUCKETS_T + bt - bucket_keys = bucket_bw * NUM_BUCKETS_T + bucket_bt # (N, 4) - - # Flatten to (4N,) for sorting - flat_keys = bucket_keys.ravel() # (4N,) - - # Sort keys to group duplicates together - sorted_idx = jnp.argsort(flat_keys) - sorted_keys = flat_keys[sorted_idx] - - # Detect boundaries where key changes (marks unique entries) - is_new = jnp.concatenate([ - jnp.array([True]), - sorted_keys[1:] != sorted_keys[:-1] - ]) - - # Assign compact indices: cumsum of is_new gives 1, 1, 1, 2, 2, 3, ... - # Subtract 1 to get 0-based indices: 0, 0, 0, 1, 1, 2, ... - compact_idx_sorted = jnp.cumsum(is_new.astype(jnp.int32)) - 1 - - # Invert the sort to get compact index for each original position - compact_idx_flat = jnp.zeros(4 * N, dtype=jnp.int32) - compact_idx_flat = compact_idx_flat.at[sorted_idx].set(compact_idx_sorted) - - # Reshape back to (N, 4) - point_to_compact = compact_idx_flat.reshape(N, 4) - - # Count number of active buckets - num_active = jnp.sum(is_new.astype(jnp.int32)) - - # Build reverse mapping: compact_idx -> bucket_key - compact_to_key = jnp.zeros(max_buckets, dtype=jnp.int32) - compact_to_key = compact_to_key.at[compact_idx_sorted].set(sorted_keys, mode='drop') - - return point_to_compact, num_active, compact_to_key - - -@partial(jax.jit, static_argnames=('max_buckets', 'kernel_num_wires', 'kernel_height', 'B1', 'B2')) -def scatter_contributions_to_buckets( - wire_indices, time_indices, intensities, contributions, - point_to_compact, max_buckets, kernel_num_wires, kernel_height, B1, B2 -): - """ - Scatter (N, kernel_num_wires, kernel_height) contributions to sparse buckets. - - Phase 2 of the sparse bucketing algorithm. Scatters pre-computed kernel - contributions to sparse buckets using the mapping from Phase 1. - - Args: - wire_indices: (N,) center wire index for each segment - time_indices: (N,) start time index for each segment - intensities: (N,) intensity scaling factor for each segment - contributions: (N, kernel_num_wires, kernel_height) kernel response for each segment - point_to_compact: (N, 4) mapping from (segment, quadrant) to compact index - max_buckets: Maximum number of buckets (static) - kernel_num_wires: Number of wires in kernel (static) - kernel_height: Number of time bins in kernel (static) - B1: Bucket size in wire direction (static) - B2: Bucket size in time direction (static) - - Returns: - (max_buckets, B1, B2) array of sparse bucket contributions - """ - N = wire_indices.shape[0] - wire_offset = kernel_num_wires // 2 - - # Scale contributions by intensity - scaled = contributions * intensities[:, None, None] - - # Create index grids - n_idx = jnp.arange(N)[:, None, None] - kw_idx = jnp.arange(kernel_num_wires)[None, :, None] - kt_idx = jnp.arange(kernel_height)[None, None, :] - - # Global coordinates (wire_indices is center, offset to get start) - gw = (wire_indices[:, None, None] - wire_offset + kw_idx).astype(jnp.int32) - gt = (time_indices[:, None, None] + kt_idx).astype(jnp.int32) - - # Compute which quadrant each kernel element falls into - # Home bucket based on kernel start position - home_bw = (wire_indices[:, None, None] - wire_offset) // B1 - home_bt = time_indices[:, None, None] // B2 - - # Cell bucket for each kernel element - cell_bw = gw // B1 - cell_bt = gt // B2 - - # Quadrant offset: 0 or 1 in each direction - which_w = jnp.clip(cell_bw - home_bw, 0, 1).astype(jnp.int32) - which_t = jnp.clip(cell_bt - home_bt, 0, 1).astype(jnp.int32) - - # Quadrant index: 0, 1, 2, or 3 - quadrant = which_w * 2 + which_t - - # Gather bucket index from precomputed mapping - n_idx_expanded = jnp.broadcast_to(n_idx, (N, kernel_num_wires, kernel_height)) - bucket_idx = point_to_compact[n_idx_expanded, quadrant] - - # Local coordinates within bucket - lw = (gw % B1).astype(jnp.int32) - lt = (gt % B2).astype(jnp.int32) - - # Scatter to buckets - output = jnp.zeros((max_buckets, B1, B2), dtype=jnp.float32) - output = output.at[bucket_idx, lw, lt].add(scaled, mode='drop') - - return output - - -@partial(jax.jit, static_argnames=('max_buckets', 'kernel_num_wires', 'kernel_height', 'B1', 'B2', 'batch_size')) -def scatter_contributions_to_buckets_batched( - wire_indices, time_indices, intensities, contributions, - point_to_compact, max_buckets, kernel_num_wires, kernel_height, B1, B2, - batch_size=1000 -): - """ - Batched scatter to reduce memory from O(N × K1 × K2) to O(batch_size × K1 × K2). - - Uses jax.lax.scan to process segments in batches, avoiding materialization - of 14 arrays of shape (N, K1, K2) simultaneously. Use this for large N - where the original scatter would OOM. - - Args: - wire_indices: (N,) center wire index for each segment - time_indices: (N,) start time index for each segment - intensities: (N,) intensity scaling factor for each segment - contributions: (N, kernel_num_wires, kernel_height) kernel response - point_to_compact: (N, 4) mapping from (segment, quadrant) to compact index - max_buckets: Maximum number of buckets (static) - kernel_num_wires: Number of wires in kernel (static) - kernel_height: Number of time bins in kernel (static) - B1: Bucket size in wire direction (static) - B2: Bucket size in time direction (static) - batch_size: Number of segments to process per batch (static) - - Returns: - (max_buckets, B1, B2) array of sparse bucket contributions - """ - N = wire_indices.shape[0] - wire_offset = kernel_num_wires // 2 - - # Pad to multiple of batch_size - n_batches = (N + batch_size - 1) // batch_size - padded_N = n_batches * batch_size - pad = padded_N - N - - # Pad all inputs - wire_indices_pad = jnp.pad(wire_indices, (0, pad), constant_values=0) - time_indices_pad = jnp.pad(time_indices, (0, pad), constant_values=0) - intensities_pad = jnp.pad(intensities, (0, pad), constant_values=0.0) - contributions_pad = jnp.pad(contributions, ((0, pad), (0, 0), (0, 0)), constant_values=0.0) - point_to_compact_pad = jnp.pad(point_to_compact, ((0, pad), (0, 0)), constant_values=0) - valid_mask = jnp.arange(padded_N) < N - - # Reshape for batched processing - wire_batched = wire_indices_pad.reshape(n_batches, batch_size) - time_batched = time_indices_pad.reshape(n_batches, batch_size) - int_batched = intensities_pad.reshape(n_batches, batch_size) - contrib_batched = contributions_pad.reshape(n_batches, batch_size, kernel_num_wires, kernel_height) - p2c_batched = point_to_compact_pad.reshape(n_batches, batch_size, 4) - valid_batched = valid_mask.reshape(n_batches, batch_size) - - # Static kernel index grids - kw_idx = jnp.arange(kernel_num_wires) - kt_idx = jnp.arange(kernel_height) - - def process_batch(output, batch_data): - bw, bt, bi, bc, bp, bv = batch_data - - # Scale contributions - shape (batch_size, K1, K2) - scaled = bc * bi[:, None, None] - - # Global coordinates - shape (batch_size, K1, K2) - gw = (bw[:, None, None] - wire_offset + kw_idx[None, :, None]).astype(jnp.int32) - gt = (bt[:, None, None] + kt_idx[None, None, :]).astype(jnp.int32) - - # Home bucket - home_bw = (bw[:, None, None] - wire_offset) // B1 - home_bt = bt[:, None, None] // B2 - - # Cell bucket - cell_bw = gw // B1 - cell_bt = gt // B2 - - # Quadrant offset and index - which_w = jnp.clip(cell_bw - home_bw, 0, 1).astype(jnp.int32) - which_t = jnp.clip(cell_bt - home_bt, 0, 1).astype(jnp.int32) - quadrant = which_w * 2 + which_t - - # Gather bucket index - batch_idx = jnp.arange(batch_size)[:, None, None] - batch_idx_expanded = jnp.broadcast_to(batch_idx, (batch_size, kernel_num_wires, kernel_height)) - bucket_idx = bp[batch_idx_expanded, quadrant] - - # Local coordinates within bucket - lw = (gw % B1).astype(jnp.int32) - lt = (gt % B2).astype(jnp.int32) - - # Mask invalid segments - valid_3d = jnp.broadcast_to(bv[:, None, None], (batch_size, kernel_num_wires, kernel_height)) - masked_scaled = jnp.where(valid_3d, scaled, 0.0) - - # Scatter to output - output = output.at[bucket_idx, lw, lt].add(masked_scaled, mode='drop') - - return output, None - - # Initialize output and run batched scatter - output = jnp.zeros((max_buckets, B1, B2), dtype=jnp.float32) - output, _ = jax.lax.scan( - process_batch, - output, - (wire_batched, time_batched, int_batched, contrib_batched, p2c_batched, valid_batched) - ) - - return output - - -@partial(jax.jit, static_argnames=('num_wires', 'num_time_steps', 'kernel_num_wires', - 'kernel_height', 'max_buckets', 'batch_size')) -def accumulate_response_signals_sparse_bucketed( - wire_indices, time_indices, intensities, contributions, - num_wires, num_time_steps, kernel_num_wires, kernel_height, - max_buckets, batch_size=1000 -): - """ - Sparse bucketed accumulation using the two-phase approach. - - Memory-efficient version that only allocates active buckets. Use this - for large detectors where the dense output array would exceed GPU memory. - - Phase 1: Build bucket mapping (O(N) with sort) - Phase 2: Batched scatter to sparse buckets (O(N * K1 * K2)) - - Args: - wire_indices: (N,) center wire index for each segment - time_indices: (N,) start time index for each segment - intensities: (N,) intensity scaling factor for each segment - contributions: (N, kernel_num_wires, kernel_height) kernel response for each segment - num_wires: Total number of wires in output - num_time_steps: Total number of time steps in output - kernel_num_wires: Number of wires in kernel - kernel_height: Number of time bins in kernel - max_buckets: Maximum number of active buckets to allocate - batch_size: Batch size for scatter. Recommended: 500-2000. - - Returns: - buckets: (max_buckets, B1, B2) sparse bucket contributions - num_active: Number of active buckets - compact_to_key: (max_buckets,) mapping to original bucket keys - """ - # Bucket sizes: 2x kernel size - B1 = 2 * kernel_num_wires - B2 = 2 * kernel_height - - # Phase 1: Build mapping - point_to_compact, num_active, compact_to_key = build_bucket_mapping( - wire_indices, time_indices, B1, B2, num_wires, num_time_steps, max_buckets - ) - - # Phase 2: Batched scatter to sparse buckets - buckets = scatter_contributions_to_buckets_batched( - wire_indices, time_indices, intensities, contributions, - point_to_compact, max_buckets, kernel_num_wires, kernel_height, B1, B2, - batch_size=batch_size - ) - - return buckets, num_active, compact_to_key - - -@partial(jax.jit, static_argnames=('B1', 'B2', 'num_wires', 'num_time_steps', 'max_buckets')) -def sparse_buckets_to_dense(buckets, compact_to_key, num_active, - B1, B2, num_wires, num_time_steps, max_buckets): - """ - Convert sparse buckets back to dense (num_wires, num_time_steps) array. - - Args: - buckets: (max_buckets, B1, B2) sparse bucket contributions - compact_to_key: (max_buckets,) mapping to original bucket keys - num_active: Number of active buckets - B1: Bucket size in wire direction - B2: Bucket size in time direction - num_wires: Total number of wires - num_time_steps: Total number of time steps - max_buckets: Maximum number of buckets - - Returns: - (num_wires, num_time_steps) dense array - """ - # Use ceiling division to match build_bucket_mapping - NUM_BUCKETS_T = (num_time_steps + B2 - 1) // B2 - - def add_bucket(i, output): - key = compact_to_key[i] - bw = key // NUM_BUCKETS_T - bt = key % NUM_BUCKETS_T - - w_start = bw * B1 - t_start = bt * B2 - - w_indices = w_start + jnp.arange(B1)[:, None] - t_indices = t_start + jnp.arange(B2)[None, :] - - valid = i < num_active - bucket_data = jnp.where(valid, buckets[i], 0.0) - - output = output.at[w_indices, t_indices].add(bucket_data) - return output - - output = jnp.zeros((num_wires, num_time_steps), dtype=jnp.float32) - output = jax.lax.fori_loop(0, max_buckets, add_bucket, output) - - return output diff --git a/closure/archive/gradient_test/gradient_test/visualization.py b/closure/archive/gradient_test/gradient_test/visualization.py deleted file mode 100644 index 8a43ca4..0000000 --- a/closure/archive/gradient_test/gradient_test/visualization.py +++ /dev/null @@ -1,299 +0,0 @@ -""" -Visualization utilities for gradient testing. - -This module provides plotting functions for loss landscapes, -gradient comparisons, and diagnostic visualizations. -""" - -import matplotlib.pyplot as plt -import numpy as np -import jax.numpy as jnp -from typing import Dict, Tuple, List, Optional -import os - -try: - from .physics_params import PARAM_INFO -except ImportError: - from physics_params import PARAM_INFO - - -def plot_loss_landscape( - param_values: jnp.ndarray, - loss_values: jnp.ndarray, - param_name: str, - numerical_gradient: Optional[float] = None, - analytical_gradient: Optional[float] = None, - save_path: Optional[str] = None, - title_suffix: str = "" -) -> plt.Figure: - """ - Plot 1D loss landscape with optional gradient tangent lines. - - Parameters - ---------- - param_values : jnp.ndarray - Parameter values (x-axis). - loss_values : jnp.ndarray - Loss values (y-axis). - param_name : str - Name of the parameter. - numerical_gradient : float, optional - Numerical gradient at center point. - analytical_gradient : float, optional - Analytical gradient at center point. - save_path : str, optional - Path to save the figure. - title_suffix : str - Additional text for title. - - Returns - ------- - plt.Figure - Matplotlib figure. - """ - info = PARAM_INFO.get(param_name, {'name': param_name, 'units': '', 'latex': param_name}) - - fig, ax = plt.subplots(figsize=(10, 6)) - - # Plot loss curve - ax.plot(param_values, loss_values, 'b-', linewidth=2, label='Loss') - ax.scatter(param_values, loss_values, c='blue', s=30, zorder=5) - - # Mark center point - center_idx = len(param_values) // 2 - center_val = param_values[center_idx] - center_loss = loss_values[center_idx] - ax.scatter([center_val], [center_loss], c='red', s=100, marker='*', - zorder=10, label='Default value') - - # Plot gradient tangent lines - x_range = param_values[-1] - param_values[0] - tangent_x = np.array([center_val - 0.1 * x_range, center_val + 0.1 * x_range]) - - if numerical_gradient is not None: - tangent_y = center_loss + numerical_gradient * (tangent_x - center_val) - ax.plot(tangent_x, tangent_y, 'g--', linewidth=2, - label=f'Numerical grad: {numerical_gradient:.2e}') - - if analytical_gradient is not None: - tangent_y = center_loss + analytical_gradient * (tangent_x - center_val) - ax.plot(tangent_x, tangent_y, 'm:', linewidth=2, - label=f'Analytical grad: {analytical_gradient:.2e}') - - ax.set_xlabel(f'{info["name"]} ({info["units"]})', fontsize=12) - ax.set_ylabel('Loss', fontsize=12) - ax.set_title(f'Loss Landscape: {info["name"]} {title_suffix}', fontsize=14) - ax.legend(loc='best') - ax.grid(True, alpha=0.3) - - plt.tight_layout() - - if save_path: - fig.savefig(save_path, dpi=150, bbox_inches='tight') - print(f"Saved: {save_path}") - - return fig - - -def plot_gradient_comparison( - comparison_results: Dict, - save_path: Optional[str] = None -) -> plt.Figure: - """ - Plot bar chart comparing analytical and numerical gradients. - - Parameters - ---------- - comparison_results : dict - Results from gradient_check(). - save_path : str, optional - Path to save the figure. - - Returns - ------- - plt.Figure - Matplotlib figure. - """ - param_names = list(comparison_results.keys()) - n_params = len(param_names) - - analytical = [comparison_results[p]['analytical'] for p in param_names] - numerical = [comparison_results[p]['numerical'] for p in param_names] - - x = np.arange(n_params) - width = 0.35 - - fig, ax = plt.subplots(figsize=(10, 6)) - - bars1 = ax.bar(x - width/2, analytical, width, label='Analytical', color='blue', alpha=0.7) - bars2 = ax.bar(x + width/2, numerical, width, label='Numerical', color='green', alpha=0.7) - - # Color bars based on whether they match - for i, name in enumerate(param_names): - if not comparison_results[name]['is_close']: - bars1[i].set_color('red') - bars2[i].set_color('orange') - - # Labels - labels = [PARAM_INFO.get(p, {'name': p})['name'] for p in param_names] - ax.set_xticks(x) - ax.set_xticklabels(labels, rotation=45, ha='right') - ax.set_ylabel('Gradient Value') - ax.set_title('Analytical vs Numerical Gradients') - ax.legend() - ax.grid(True, alpha=0.3, axis='y') - - # Add relative difference text - for i, name in enumerate(param_names): - rel_diff = comparison_results[name]['rel_diff'] - y_pos = max(abs(analytical[i]), abs(numerical[i])) - ax.annotate(f'{rel_diff:.1e}', (x[i], y_pos), - textcoords="offset points", xytext=(0, 5), - ha='center', fontsize=8) - - plt.tight_layout() - - if save_path: - fig.savefig(save_path, dpi=150, bbox_inches='tight') - print(f"Saved: {save_path}") - - return fig - - -def plot_all_loss_landscapes( - loss_landscapes: Dict[str, Tuple[jnp.ndarray, jnp.ndarray]], - gradients: Optional[Dict[str, Dict]] = None, - save_dir: Optional[str] = None -) -> plt.Figure: - """ - Plot all loss landscapes in a grid. - - Parameters - ---------- - loss_landscapes : dict - Dictionary of param_name -> (param_values, loss_values). - gradients : dict, optional - Dictionary of param_name -> {'numerical': ..., 'analytical': ...}. - save_dir : str, optional - Directory to save individual plots. - - Returns - ------- - plt.Figure - Matplotlib figure with grid of subplots. - """ - n_params = len(loss_landscapes) - n_cols = 2 - n_rows = (n_params + n_cols - 1) // n_cols - - fig, axes = plt.subplots(n_rows, n_cols, figsize=(12, 5 * n_rows)) - axes = axes.flatten() if n_params > 1 else [axes] - - for i, (param_name, (param_values, loss_values)) in enumerate(loss_landscapes.items()): - ax = axes[i] - info = PARAM_INFO.get(param_name, {'name': param_name, 'units': ''}) - - ax.plot(param_values, loss_values, 'b-', linewidth=2) - ax.scatter(param_values, loss_values, c='blue', s=20) - - # Mark center - center_idx = len(param_values) // 2 - ax.scatter([param_values[center_idx]], [loss_values[center_idx]], - c='red', s=80, marker='*', zorder=10) - - ax.set_xlabel(f'{info["name"]} ({info["units"]})') - ax.set_ylabel('Loss') - ax.set_title(f'{info["name"]}') - ax.grid(True, alpha=0.3) - - # Add gradient info if available - if gradients and param_name in gradients: - grad_info = gradients[param_name] - text = f"Num: {grad_info.get('numerical', 'N/A'):.2e}" - if 'analytical' in grad_info: - text += f"\nAna: {grad_info['analytical']:.2e}" - ax.text(0.02, 0.98, text, transform=ax.transAxes, - verticalalignment='top', fontsize=9, - bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5)) - - # Hide unused subplots - for j in range(i + 1, len(axes)): - axes[j].set_visible(False) - - plt.suptitle('Loss Landscapes for Physics Parameters', fontsize=14) - plt.tight_layout() - - if save_dir: - os.makedirs(save_dir, exist_ok=True) - fig.savefig(os.path.join(save_dir, 'all_loss_landscapes.png'), - dpi=150, bbox_inches='tight') - - return fig - - -def create_gradient_report( - gradient_results: Dict, - loss_landscapes: Dict, - save_path: str -): - """ - Create a text report of gradient testing results. - - Parameters - ---------- - gradient_results : dict - Results from gradient_check(). - loss_landscapes : dict - Loss landscape data. - save_path : str - Path to save the report. - """ - with open(save_path, 'w') as f: - f.write("=" * 60 + "\n") - f.write("JAXTPC Gradient Testing Report\n") - f.write("=" * 60 + "\n\n") - - # Analytical gradient status - f.write("Analytical Gradient Computation:\n") - f.write("-" * 40 + "\n") - if gradient_results.get('analytical_success', False): - f.write("Status: SUCCESS\n") - else: - f.write("Status: FAILED\n") - if gradient_results.get('analytical_error'): - f.write(f"Error: {gradient_results['analytical_error']}\n") - f.write("\n") - - # Numerical gradients - f.write("Numerical Gradients:\n") - f.write("-" * 40 + "\n") - for name, grad in gradient_results.get('numerical_grads', {}).items(): - info = PARAM_INFO.get(name, {'name': name}) - f.write(f" {info['name']:<25}: {grad:>12.6e}\n") - f.write("\n") - - # Comparison - if gradient_results.get('comparison'): - f.write("Gradient Comparison (Analytical vs Numerical):\n") - f.write("-" * 40 + "\n") - f.write(f"{'Parameter':<20} {'Analytical':>12} {'Numerical':>12} {'Rel Diff':>10} {'Match':>6}\n") - f.write("-" * 60 + "\n") - for name, comp in gradient_results['comparison'].items(): - match = "YES" if comp['is_close'] else "NO" - f.write(f"{name:<20} {comp['analytical']:>12.4e} {comp['numerical']:>12.4e} " - f"{comp['rel_diff']:>10.2e} {match:>6}\n") - f.write("\n") - - # Loss landscape summary - f.write("Loss Landscape Summary:\n") - f.write("-" * 40 + "\n") - for name, (params, losses) in loss_landscapes.items(): - info = PARAM_INFO.get(name, {'name': name}) - f.write(f"\n {info['name']}:\n") - f.write(f" Parameter range: [{float(params[0]):.4e}, {float(params[-1]):.4e}]\n") - f.write(f" Loss range: [{float(min(losses)):.4e}, {float(max(losses)):.4e}]\n") - f.write(f" Loss at default: {float(losses[len(losses)//2]):.4e}\n") - - f.write("\n" + "=" * 60 + "\n") - - print(f"Report saved to: {save_path}") diff --git a/closure/archive/muon_intermediate/benchmark_topk_sw.py b/closure/archive/muon_intermediate/benchmark_topk_sw.py deleted file mode 100644 index 7b4bb0f..0000000 --- a/closure/archive/muon_intermediate/benchmark_topk_sw.py +++ /dev/null @@ -1,239 +0,0 @@ -""" -Benchmark top-k extraction + SW loss computation as a function of K. - -Measures only the pointcloud extraction and SW distance (not the simulation). -Averages over multiple trials, skipping the first (warmup). - -Run from project root: - python3 closure_analysis_muon/benchmark_topk_sw.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments, - build_muon_forward, -) - -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 -N_PROJ = 200 -N_TRIALS = 20 # total calls per K (first is warmup, rest averaged) -PLANES = [0, 1, 2] - -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 2 -TRUTH_ENERGY = 200.0 - -# Perturbed signal for a nonzero SW distance -PERT_THETA = TRUTH_THETA + 0.15 - -K_VALUES = [500, 1000, 2000, 3000, 5000, 7000, 10000, 15000, 20000, 30000] - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -def main(): - print("=" * 60, flush=True) - print("BENCHMARK: top-k + SW vs K", flush=True) - print(f"N_PROJ={N_PROJ}, N_TRIALS={N_TRIALS} (first skipped)", flush=True) - print("=" * 60, flush=True) - - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - # Generate truth and perturbed signals (just once, reuse arrays) - print("Generating signals...", flush=True) - pos_fixed = jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], dtype=jnp.float32) - - truth_pos, truth_de = generate_muon_segments( - jnp.float32(TRUTH_ENERGY), pos_fixed, - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - truth_sigs = forward(truth_pos, truth_de) - - pert_pos, pert_de = generate_muon_segments( - jnp.float32(TRUTH_ENERGY), pos_fixed, - jnp.float32(PERT_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - pert_sigs = forward(pert_pos, pert_de) - - for s in truth_sigs: - jax.block_until_ready(s) - for s in pert_sigs: - jax.block_until_ready(s) - print(" Signals ready.", flush=True) - - ot_key = jax.random.PRNGKey(42) - - # For each K, build a jitted function that does topk + SW for all 3 planes - results = [] - - for K in K_VALUES: - print(f"\nK = {K:,}", flush=True) - - # Pre-extract truth pointclouds for this K (not timed — these are fixed) - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(truth_sigs[p], K) - target_clouds[p] = (pts, w) - - # JIT the topk + SW for the perturbed signal - def topk_sw(pert_sig_0, pert_sig_1, pert_sig_2): - loss = 0.0 - for p, sig in enumerate([pert_sig_0, pert_sig_1, pert_sig_2]): - pts, w = signal_to_pointcloud(sig, K) - loss = loss + sliced_wasserstein_loss_jit( - pts, w, target_clouds[p][0], target_clouds[p][1], - ot_key, n_projections=N_PROJ, - ) - return loss - - topk_sw_jit = jax.jit(topk_sw) - - # Warmup (compile) - t0 = time.time() - loss = topk_sw_jit(pert_sigs[0], pert_sigs[1], pert_sigs[2]) - jax.block_until_ready(loss) - compile_time = time.time() - t0 - print(f" compile: {compile_time:.3f}s, loss={float(loss):.2f}", flush=True) - - # Timed runs - times = [] - for trial in range(N_TRIALS): - t0 = time.time() - loss = topk_sw_jit(pert_sigs[0], pert_sigs[1], pert_sigs[2]) - jax.block_until_ready(loss) - times.append(time.time() - t0) - - times = np.array(times) - mean_ms = times.mean() * 1000 - std_ms = times.std() * 1000 - print(f" runtime: {mean_ms:.1f} ± {std_ms:.1f} ms " - f"(min={times.min()*1000:.1f}, max={times.max()*1000:.1f})", flush=True) - - # Also time topk + SW + backward (value_and_grad) - topk_sw_vg = jax.jit(jax.value_and_grad(topk_sw, argnums=(0, 1, 2))) - - # Warmup backward - t0 = time.time() - loss_g, grads_g = topk_sw_vg(pert_sigs[0], pert_sigs[1], pert_sigs[2]) - jax.block_until_ready(loss_g) - for g in grads_g: - jax.block_until_ready(g) - bwd_compile = time.time() - t0 - print(f" bwd compile: {bwd_compile:.3f}s", flush=True) - - bwd_times = [] - for trial in range(N_TRIALS): - t0 = time.time() - loss_g, grads_g = topk_sw_vg(pert_sigs[0], pert_sigs[1], pert_sigs[2]) - jax.block_until_ready(loss_g) - for g in grads_g: - jax.block_until_ready(g) - bwd_times.append(time.time() - t0) - - bwd_times = np.array(bwd_times) - bwd_mean_ms = bwd_times.mean() * 1000 - bwd_std_ms = bwd_times.std() * 1000 - print(f" fwd+bwd: {bwd_mean_ms:.1f} ± {bwd_std_ms:.1f} ms", flush=True) - - results.append({ - 'K': K, - 'fwd_mean_ms': mean_ms, - 'fwd_std_ms': std_ms, - 'bwd_mean_ms': bwd_mean_ms, - 'bwd_std_ms': bwd_std_ms, - 'compile_s': compile_time, - 'bwd_compile_s': bwd_compile, - 'loss': float(loss), - }) - - # ===================================================================== - # Plot - # ===================================================================== - print("\nGenerating plot...", flush=True) - - Ks = [r['K'] for r in results] - fwd_means = [r['fwd_mean_ms'] for r in results] - fwd_stds = [r['fwd_std_ms'] for r in results] - bwd_means = [r['bwd_mean_ms'] for r in results] - bwd_stds = [r['bwd_std_ms'] for r in results] - compiles = [r['compile_s'] for r in results] - bwd_compiles = [r['bwd_compile_s'] for r in results] - losses = [r['loss'] for r in results] - - fig, axes = plt.subplots(1, 3, figsize=(18, 5)) - - # Runtime vs K - axes[0].errorbar(Ks, fwd_means, yerr=fwd_stds, fmt='bo-', lw=1.5, - capsize=3, label='Forward only') - axes[0].errorbar(Ks, bwd_means, yerr=bwd_stds, fmt='rs-', lw=1.5, - capsize=3, label='Forward + Backward') - axes[0].set_xlabel('K (top-k points)') - axes[0].set_ylabel('Time (ms)') - axes[0].set_title('Runtime: top-k + SW (3 planes)') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - axes[0].set_xscale('log') - - # Compile time vs K - axes[1].plot(Ks, compiles, 'bo-', lw=1.5, label='Forward compile') - axes[1].plot(Ks, bwd_compiles, 'rs-', lw=1.5, label='Fwd+Bwd compile') - axes[1].set_xlabel('K (top-k points)') - axes[1].set_ylabel('Compile time (s)') - axes[1].set_title('JIT Compilation Time') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - axes[1].set_xscale('log') - - # Loss vs K - axes[2].plot(Ks, losses, 'go-', lw=1.5) - axes[2].set_xlabel('K (top-k points)') - axes[2].set_ylabel('SW Loss') - axes[2].set_title('SW Loss Value vs K') - axes[2].grid(True, alpha=0.3) - axes[2].set_xscale('log') - - fig.suptitle( - f'Top-K + Sliced Wasserstein Scaling (N_PROJ={N_PROJ}, 3 east planes, {N_TRIALS} trials)', - fontsize=13, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'benchmark_topk_sw.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}", flush=True) - - # Print summary table - print(f"\n{'K':>8} | {'Fwd (ms)':>10} | {'Fwd+Bwd (ms)':>14} | " - f"{'Compile (s)':>12} | {'Bwd Compile':>12} | {'Loss':>8}", flush=True) - print("-" * 80, flush=True) - for r in results: - print(f"{r['K']:>8,} | {r['fwd_mean_ms']:>8.1f}±{r['fwd_std_ms']:<4.1f}| " - f"{r['bwd_mean_ms']:>10.1f}±{r['bwd_std_ms']:<6.1f}| " - f"{r['compile_s']:>11.2f}s | {r['bwd_compile_s']:>10.2f}s | " - f"{r['loss']:>8.2f}", flush=True) - - print("\nDone!", flush=True) - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/diagnose_loss_peaks.py b/closure/archive/muon_intermediate/diagnose_loss_peaks.py deleted file mode 100644 index a2b1b71..0000000 --- a/closure/archive/muon_intermediate/diagnose_loss_peaks.py +++ /dev/null @@ -1,380 +0,0 @@ -""" -Diagnose anomalous SW loss peaks at specific parameter values. - -Investigates three anomalies: - 1. Energy < 140 MeV: track shortens, fewer nonzero signal pixels vs K=10000 - 2. Phi ~ 1.2 rad: track gains x-component, crosses x=0 to west side - 3. Theta ~ 0.55 rad: track geometry changes projection onto wire planes - -For each anomalous point, generates: - - Signal pixel statistics (nonzero count per plane vs K) - - East vs west segment counts - - Event display comparisons (truth vs anomalous) - - Pointcloud visualizations - -Run from project root: - python3 closure_analysis_muon/diagnose_loss_peaks.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments, - build_muon_forward, -) - -# ============================================================================= -# Configuration -# ============================================================================= - -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 -K = 10000 - -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 2 -TRUTH_ENERGY = 200.0 - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -# Anomalous parameter values to investigate -ANOMALOUS = { - 'energy': [120.0, 130.0, 140.0, 150.0, 160.0], - 'phi': [1.0, 1.1, 1.2, 1.3, 1.4], - 'theta': [0.4, 0.45, 0.5, 0.55, 0.6, 0.65], -} - - -def main(): - print("=" * 60, flush=True) - print("DIAGNOSE SW LOSS PEAKS", flush=True) - print("=" * 60, flush=True) - - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - - - def simulate(x, y, z, theta, phi, energy): - pos = jnp.array([x, y, z], dtype=jnp.float32) - positions, des = generate_muon_segments( - jnp.float32(energy), pos, jnp.float32(theta), jnp.float32(phi), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - signals = forward(positions, des) - return signals, positions, des - - # --- Compile --- - print("Compiling...", flush=True) - t0 = time.time() - sim_jit = jax.jit(simulate) - truth_result = sim_jit(TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY) - for s in truth_result[0]: - jax.block_until_ready(s) - print(f" Compiled ({time.time()-t0:.1f}s)", flush=True) - - truth_signals, truth_pos, truth_de = truth_result - truth_pos_np = np.array(truth_pos) - truth_de_np = np.array(truth_de) - - # --- Analyze truth --- - print("\n" + "=" * 60, flush=True) - print("TRUTH ANALYSIS", flush=True) - print("=" * 60, flush=True) - _analyze_result("Truth", truth_signals, truth_pos_np, truth_de_np, K) - - # --- Analyze each anomalous point --- - all_results = {} - - for param_name, values in ANOMALOUS.items(): - print(f"\n{'=' * 60}", flush=True) - print(f"SWEEPING {param_name.upper()}", flush=True) - print(f"{'=' * 60}", flush=True) - - for val in values: - # Build args with this parameter changed - args = { - 'x': TRUTH_X, 'y': TRUTH_Y, 'z': TRUTH_Z, - 'theta': TRUTH_THETA, 'phi': TRUTH_PHI, 'energy': TRUTH_ENERGY, - } - args[param_name] = val - - signals, pos, des = sim_jit(**args) - for s in signals: - jax.block_until_ready(s) - pos_np = np.array(pos) - de_np = np.array(des) - - label = f"{param_name}={val:.2f}" - _analyze_result(label, signals, pos_np, de_np, K) - - all_results[(param_name, val)] = (signals, pos_np, de_np) - - # --- Generate comparison event displays --- - print(f"\n{'=' * 60}", flush=True) - print("GENERATING COMPARISON PLOTS", flush=True) - print(f"{'=' * 60}", flush=True) - - # 1. Energy comparison - _plot_comparison( - truth_signals, - all_results[('energy', 130.0)][0], - "Truth (E=200 MeV)", "E=130 MeV", - os.path.join(OUT_DIR, "diagnose_energy_130.png"), - ) - _plot_comparison( - truth_signals, - all_results[('energy', 140.0)][0], - "Truth (E=200 MeV)", "E=140 MeV", - os.path.join(OUT_DIR, "diagnose_energy_140.png"), - ) - - # 2. Phi comparison - _plot_comparison( - truth_signals, - all_results[('phi', 1.2)][0], - f"Truth (phi={TRUTH_PHI:.2f})", "phi=1.20", - os.path.join(OUT_DIR, "diagnose_phi_1.2.png"), - ) - - # 3. Theta comparison - _plot_comparison( - truth_signals, - all_results[('theta', 0.55)][0], - f"Truth (theta={TRUTH_THETA:.2f})", "theta=0.55", - os.path.join(OUT_DIR, "diagnose_theta_0.55.png"), - ) - - # --- 3D track comparisons --- - _plot_tracks_3d( - truth_pos_np, truth_de_np, - all_results[('energy', 130.0)][1], all_results[('energy', 130.0)][2], - "Truth (E=200)", "E=130 MeV", - os.path.join(OUT_DIR, "diagnose_track_energy_130.png"), - ) - _plot_tracks_3d( - truth_pos_np, truth_de_np, - all_results[('phi', 1.2)][1], all_results[('phi', 1.2)][2], - f"Truth (phi={TRUTH_PHI:.2f})", "phi=1.20", - os.path.join(OUT_DIR, "diagnose_track_phi_1.2.png"), - ) - _plot_tracks_3d( - truth_pos_np, truth_de_np, - all_results[('theta', 0.55)][1], all_results[('theta', 0.55)][2], - f"Truth (theta={TRUTH_THETA:.2f})", "theta=0.55", - os.path.join(OUT_DIR, "diagnose_track_theta_0.55.png"), - ) - - # --- Pointcloud comparison --- - _plot_pointclouds( - truth_signals, all_results[('energy', 130.0)][0], - "Truth (E=200)", "E=130 MeV", K, - os.path.join(OUT_DIR, "diagnose_pc_energy_130.png"), - ) - _plot_pointclouds( - truth_signals, all_results[('phi', 1.2)][0], - "Truth (phi=1.57)", "phi=1.20", K, - os.path.join(OUT_DIR, "diagnose_pc_phi_1.2.png"), - ) - _plot_pointclouds( - truth_signals, all_results[('theta', 0.55)][0], - "Truth (theta=0.79)", "theta=0.55", K, - os.path.join(OUT_DIR, "diagnose_pc_theta_0.55.png"), - ) - - print("\nDone!", flush=True) - - -def _analyze_result(label, signals, pos_np, de_np, K): - """Print diagnostic statistics for one simulation result.""" - n_active = int(np.sum(de_np > 0)) - n_east = int(np.sum((de_np > 0) & (pos_np[:, 0] < 0))) - n_west = int(np.sum((de_np > 0) & (pos_np[:, 0] >= 0))) - total_de = float(np.sum(de_np)) - - x_range = (float(pos_np[de_np > 0, 0].min()), float(pos_np[de_np > 0, 0].max())) if n_active > 0 else (0, 0) - - print(f"\n --- {label} ---", flush=True) - print(f" Active segments: {n_active}/{len(de_np)}", flush=True) - print(f" East/West split: {n_east} / {n_west}", flush=True) - print(f" Total dE: {total_de:.1f} MeV", flush=True) - print(f" x range: [{x_range[0]:.1f}, {x_range[1]:.1f}] mm", flush=True) - - plane_names = ['East U', 'East V', 'East Y', 'West U', 'West V', 'West Y'] - for pi, pname in enumerate(plane_names): - sig_np = np.array(signals[pi]) - abs_sig = np.abs(sig_np) - n_nonzero = int(np.sum(abs_sig > 1e-6)) - max_val = float(abs_sig.max()) - # Check how many pixels above the K-th largest - flat = abs_sig.ravel() - if len(flat) > K: - kth_val = float(np.partition(flat, -K)[-K]) if n_nonzero >= K else 0.0 - else: - kth_val = 0.0 - below_k = "OK" if n_nonzero >= K else f"BELOW K={K}!" - print(f" {pname}: nonzero={n_nonzero:,}, max={max_val:.1f}, " - f"kth_val={kth_val:.2f}, {below_k}", flush=True) - - -def _plot_comparison(truth_sigs, test_sigs, - label_truth, label_test, fname): - """3-column (U/V/Y) × 3-row (truth/test/diff) event display comparison.""" - plane_names = ['East U (Induction)', 'East V (Induction)', 'East Y (Collection)'] - fig, axes = plt.subplots(3, 3, figsize=(18, 14)) - - for col, pi in enumerate(range(3)): - truth_adc = np.array(truth_sigs[pi]) # already in ADC - test_adc = np.array(test_sigs[pi]) - diff = test_adc - truth_adc - - # Find combined bounding box - all_nz = np.nonzero(np.abs(truth_adc) + np.abs(test_adc) > 0.01) - if len(all_nz[0]) > 0: - wlo = max(0, all_nz[0].min() - 15) - whi = min(truth_adc.shape[0], all_nz[0].max() + 15) - tlo = max(0, all_nz[1].min() - 30) - thi = min(truth_adc.shape[1], all_nz[1].max() + 30) - else: - wlo, whi = 0, truth_adc.shape[0] - tlo, thi = 0, truth_adc.shape[1] - - crops = [ - truth_adc[wlo:whi, tlo:thi], - test_adc[wlo:whi, tlo:thi], - diff[wlo:whi, tlo:thi], - ] - extent = [wlo, whi, tlo, thi] - vmax_sig = max(np.abs(crops[0]).max(), np.abs(crops[1]).max()) - if vmax_sig < 1e-10: - vmax_sig = 1.0 - vmax_diff = np.abs(crops[2]).max() - if vmax_diff < 1e-10: - vmax_diff = 1.0 - - row_labels = [label_truth, label_test, 'Difference'] - vmaxes = [vmax_sig, vmax_sig, vmax_diff] - - for row in range(3): - im = axes[row, col].imshow( - crops[row].T, aspect='auto', origin='lower', extent=extent, - cmap='RdBu_r', vmin=-vmaxes[row], vmax=vmaxes[row], - interpolation='nearest', - ) - if row == 0: - axes[row, col].set_title(plane_names[col], fontsize=12, fontweight='bold') - axes[row, col].set_ylabel(f'{row_labels[row]}\nTime bin') - axes[row, col].set_xlabel('Wire index') - fig.colorbar(im, ax=axes[row, col], label='ADC', shrink=0.8) - - fig.suptitle(f'{label_truth} vs {label_test}', fontsize=14, fontweight='bold') - fig.tight_layout() - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}", flush=True) - - -def _plot_tracks_3d(pos1, de1, pos2, de2, label1, label2, fname): - """Side-by-side 3D track comparison with x=0 plane.""" - fig = plt.figure(figsize=(16, 6)) - - for i, (pos, de, label) in enumerate([(pos1, de1, label1), (pos2, de2, label2)]): - ax = fig.add_subplot(1, 2, i + 1, projection='3d') - active = de > 0 - if np.any(active): - sc = ax.scatter( - pos[active, 0], pos[active, 1], pos[active, 2], - c=de[active], cmap='hot', s=3, alpha=0.8, - ) - fig.colorbar(sc, ax=ax, label='dE (MeV)', shrink=0.6) - - # Draw x=0 plane indicator - y_range = [pos[active, 1].min(), pos[active, 1].max()] - z_range = [pos[active, 2].min(), pos[active, 2].max()] - yy, zz = np.meshgrid( - np.linspace(y_range[0] - 20, y_range[1] + 20, 2), - np.linspace(z_range[0] - 20, z_range[1] + 20, 2), - ) - ax.plot_surface(np.zeros_like(yy), yy, zz, alpha=0.15, color='blue') - ax.text(0, y_range[0], z_range[1] + 30, 'x=0\n(anode)', color='blue', fontsize=8) - - ax.set_xlabel('x (mm)') - ax.set_ylabel('y (mm)') - ax.set_zlabel('z (mm)') - ax.set_title(label) - - fig.suptitle('3D Track Comparison', fontsize=14, fontweight='bold') - fig.tight_layout() - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}", flush=True) - - -def _plot_pointclouds(truth_sigs, test_sigs, label1, label2, K, fname): - """Compare pointclouds extracted from truth and test signals.""" - plane_names = ['East U', 'East V', 'East Y'] - fig, axes = plt.subplots(2, 3, figsize=(18, 10)) - - for col, pi in enumerate(range(3)): - pts_t, w_t = signal_to_pointcloud(truth_sigs[pi], K) - pts_p, w_p = signal_to_pointcloud(test_sigs[pi], K) - - pts_t_np = np.array(pts_t) - w_t_np = np.array(w_t) - pts_p_np = np.array(pts_p) - w_p_np = np.array(w_p) - - # Count how many weights are effectively zero - n_zero_truth = int(np.sum(w_t_np < 1e-6)) - n_zero_test = int(np.sum(w_p_np < 1e-6)) - - for row, (pts, w, label, n_zero) in enumerate([ - (pts_t_np, w_t_np, label1, n_zero_truth), - (pts_p_np, w_p_np, label2, n_zero_test), - ]): - nonzero = w > 1e-6 - if np.any(nonzero): - sc = axes[row, col].scatter( - pts[nonzero, 0], pts[nonzero, 1], - c=w[nonzero], cmap='hot', s=1, alpha=0.5, - ) - fig.colorbar(sc, ax=axes[row, col], label='weight', shrink=0.8) - if n_zero > 0: - # Show zero-weight points in grey - axes[row, col].scatter( - pts[~nonzero, 0], pts[~nonzero, 1], - c='grey', s=1, alpha=0.2, label=f'{n_zero} zero-weight', - ) - axes[row, col].legend(fontsize=8) - - axes[row, col].set_xlabel('wire (norm)') - axes[row, col].set_ylabel('time (norm)') - title_extra = f" ({n_zero} zeros)" if n_zero > 0 else "" - if row == 0: - axes[row, col].set_title(f'{plane_names[col]}\n{label}{title_extra}', fontsize=10) - else: - axes[row, col].set_title(f'{label}{title_extra}', fontsize=10) - - fig.suptitle(f'Pointcloud Comparison (K={K})', fontsize=14, fontweight='bold') - fig.tight_layout() - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}", flush=True) - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/diagnose_sw_detail.py b/closure/archive/muon_intermediate/diagnose_sw_detail.py deleted file mode 100644 index 274737a..0000000 --- a/closure/archive/muon_intermediate/diagnose_sw_detail.py +++ /dev/null @@ -1,323 +0,0 @@ -""" -Detailed diagnosis of SW loss anomalies at low energy and theta~0.5. - -1. Energy: shows how V-plane nonzero pixel count vs K causes top_k to grab zeros -2. Theta: shows the track is parallel to V wires at theta=atan(0.5/0.866)=0.524 - -Run from project root: - python3 closure_analysis_muon/diagnose_sw_detail.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments, - build_muon_forward, -) - -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 -K = 10000 -N_PROJ = 200 - -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 2 -TRUTH_ENERGY = 200.0 - -PLANES = [0, 1, 2] -PLANE_NAMES = ['East U (+60°)', 'East V (-60°)', 'East Y (0°)'] -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -def main(): - print("=" * 60, flush=True) - print("DETAILED SW LOSS DIAGNOSIS", flush=True) - print("=" * 60, flush=True) - - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - ot_key = jax.random.PRNGKey(42) - - def sim_forward(x, y, z, theta, phi, energy): - pos, de = generate_muon_segments( - energy, jnp.array([x, y, z]), theta, phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - return forward(pos, de) - - print("Compiling...", flush=True) - t0 = time.time() - sim_jit = jax.jit(sim_forward) - truth_sigs = sim_jit(TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY) - for s in truth_sigs: - jax.block_until_ready(s) - print(f" sim compiled ({time.time()-t0:.1f}s)", flush=True) - - # Truth pointclouds - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(truth_sigs[p], K) - target_clouds[p] = (pts, w) - - def per_plane_sw(sigs): - """Return per-plane SW losses and pixel stats.""" - losses = [] - stats = [] - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = sliced_wasserstein_loss_jit( - pts, w, target_clouds[p][0], target_clouds[p][1], - ot_key, n_projections=N_PROJ, - ) - losses.append(float(loss)) - # Stats - sig_np = np.array(sigs[p]) - n_nz = int(np.sum(np.abs(sig_np) > 1e-6)) - w_np = np.array(w) - n_zero_w = int(np.sum(w_np < 1e-6)) - stats.append({'nonzero_pixels': n_nz, 'zero_weight_in_topk': n_zero_w}) - return losses, stats - - # ========================================================================= - # 1. V-wire angle analysis - # ========================================================================= - print("\n" + "=" * 60, flush=True) - print("V-WIRE ANGLE ANALYSIS", flush=True) - print("=" * 60, flush=True) - - # V wires at -60 deg: wire coord = -sin(60)*y + cos(60)*z = -0.866*y + 0.5*z - # Track direction at phi=pi/2: [0, sin(theta), cos(theta)] - # dr/ds = -0.866*sin(theta) + 0.5*cos(theta) - # Zero crossing: tan(theta) = 0.5/0.866 => theta = 0.5236 rad (30 deg) - critical_theta = np.arctan(0.5 / 0.866) - print(f" V-wire angle: -60 deg", flush=True) - print(f" Wire coord: r = -0.866*y + 0.5*z", flush=True) - print(f" Track direction (phi=pi/2): [0, sin(theta), cos(theta)]", flush=True) - print(f" dr/ds = -0.866*sin(theta) + 0.5*cos(theta)", flush=True) - print(f" dr/ds = 0 at theta = arctan(0.5/0.866) = {critical_theta:.4f} rad " - f"({np.degrees(critical_theta):.1f} deg)", flush=True) - print(f" => Track is PARALLEL to V wires at theta ~ 0.524 rad!", flush=True) - - # Show dr/ds for a range of theta - thetas = np.linspace(0.3, 1.2, 50) - drds = -0.866 * np.sin(thetas) + 0.5 * np.cos(thetas) - - print(f"\n theta (rad) | dr/ds (V wire projection rate)", flush=True) - print(f" {'-'*45}", flush=True) - for th in [0.3, 0.4, 0.5, critical_theta, 0.55, 0.6, 0.7, 0.785, 0.9, 1.0, 1.2]: - d = -0.866 * np.sin(th) + 0.5 * np.cos(th) - marker = " <-- PARALLEL" if abs(th - critical_theta) < 0.02 else "" - print(f" {th:10.3f} | {d:+.4f}{marker}", flush=True) - - # ========================================================================= - # 2. Per-plane SW loss vs theta - # ========================================================================= - print("\n" + "=" * 60, flush=True) - print("PER-PLANE SW LOSS vs THETA", flush=True) - print("=" * 60, flush=True) - - theta_vals = np.linspace(0.3, 1.2, 30) - plane_losses_theta = {p: [] for p in PLANES} - total_losses_theta = [] - v_nonzero_theta = [] - v_zero_weight_theta = [] - - t0 = time.time() - for th in theta_vals: - sigs = sim_jit(TRUTH_X, TRUTH_Y, TRUTH_Z, float(th), TRUTH_PHI, TRUTH_ENERGY) - losses, stats = per_plane_sw(sigs) - for p in PLANES: - plane_losses_theta[p].append(losses[p]) - total_losses_theta.append(sum(losses)) - v_nonzero_theta.append(stats[1]['nonzero_pixels']) - v_zero_weight_theta.append(stats[1]['zero_weight_in_topk']) - print(f" Theta sweep done ({time.time()-t0:.1f}s)", flush=True) - - # Plot - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - - # Top-left: per-plane losses - for p in PLANES: - axes[0, 0].plot(theta_vals, plane_losses_theta[p], lw=1.5, label=PLANE_NAMES[p]) - axes[0, 0].axvline(critical_theta, color='red', ls=':', lw=2, - label=f'V-parallel (θ={critical_theta:.3f})') - axes[0, 0].axvline(TRUTH_THETA, color='green', ls='--', lw=2, label='Truth') - axes[0, 0].set_xlabel('theta (rad)') - axes[0, 0].set_ylabel('SW Loss (per plane)') - axes[0, 0].set_title('Per-Plane SW Loss vs Theta') - axes[0, 0].legend() - axes[0, 0].grid(True, alpha=0.3) - - # Top-right: total loss - axes[0, 1].plot(theta_vals, total_losses_theta, 'b-', lw=2) - axes[0, 1].axvline(critical_theta, color='red', ls=':', lw=2, label=f'V-parallel') - axes[0, 1].axvline(TRUTH_THETA, color='green', ls='--', lw=2, label='Truth') - axes[0, 1].set_xlabel('theta (rad)') - axes[0, 1].set_ylabel('Total SW Loss (U+V+Y)') - axes[0, 1].set_title('Total SW Loss vs Theta') - axes[0, 1].legend() - axes[0, 1].grid(True, alpha=0.3) - - # Bottom-left: V plane nonzero pixels - axes[1, 0].plot(theta_vals, v_nonzero_theta, 'b-', lw=2) - axes[1, 0].axhline(K, color='red', ls='--', lw=2, label=f'K={K}') - axes[1, 0].axvline(critical_theta, color='red', ls=':', lw=2, label='V-parallel') - axes[1, 0].axvline(TRUTH_THETA, color='green', ls='--', lw=2, label='Truth') - axes[1, 0].set_xlabel('theta (rad)') - axes[1, 0].set_ylabel('East V nonzero pixels') - axes[1, 0].set_title('V-Plane Signal Occupancy vs Theta') - axes[1, 0].legend() - axes[1, 0].grid(True, alpha=0.3) - - # Bottom-right: zero-weight points in top-K - axes[1, 1].plot(theta_vals, v_zero_weight_theta, 'r-', lw=2) - axes[1, 1].axvline(critical_theta, color='red', ls=':', lw=2, label='V-parallel') - axes[1, 1].axvline(TRUTH_THETA, color='green', ls='--', lw=2, label='Truth') - axes[1, 1].set_xlabel('theta (rad)') - axes[1, 1].set_ylabel('Zero-weight points in top-K') - axes[1, 1].set_title('V-Plane Top-K Zero Contamination') - axes[1, 1].legend() - axes[1, 1].grid(True, alpha=0.3) - - fig.suptitle( - f'Theta Anomaly: Track parallel to V wires at θ={critical_theta:.3f} rad ({np.degrees(critical_theta):.1f}°)\n' - f'V wire coord: r = -0.866·y + 0.5·z, dr/ds = 0 when tan(θ) = 0.577', - fontsize=13, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'diagnose_theta_v_wire.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}", flush=True) - - # ========================================================================= - # 3. Per-plane SW loss vs energy - # ========================================================================= - print("\n" + "=" * 60, flush=True) - print("PER-PLANE SW LOSS vs ENERGY", flush=True) - print("=" * 60, flush=True) - - energy_vals = np.linspace(100, 280, 30) - plane_losses_e = {p: [] for p in PLANES} - total_losses_e = [] - nonzero_per_plane_e = {p: [] for p in PLANES} - zero_weight_per_plane_e = {p: [] for p in PLANES} - - t0 = time.time() - for en in energy_vals: - sigs = sim_jit(TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, float(en)) - losses, stats = per_plane_sw(sigs) - for p in PLANES: - plane_losses_e[p].append(losses[p]) - nonzero_per_plane_e[p].append(stats[p]['nonzero_pixels']) - zero_weight_per_plane_e[p].append(stats[p]['zero_weight_in_topk']) - total_losses_e.append(sum(losses)) - print(f" Energy sweep done ({time.time()-t0:.1f}s)", flush=True) - - # Plot - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - - # Top-left: per-plane losses - for p in PLANES: - axes[0, 0].plot(energy_vals, plane_losses_e[p], lw=1.5, label=PLANE_NAMES[p]) - axes[0, 0].axvline(TRUTH_ENERGY, color='green', ls='--', lw=2, label='Truth') - axes[0, 0].set_xlabel('Energy (MeV)') - axes[0, 0].set_ylabel('SW Loss (per plane)') - axes[0, 0].set_title('Per-Plane SW Loss vs Energy') - axes[0, 0].legend() - axes[0, 0].grid(True, alpha=0.3) - - # Top-right: total loss - axes[0, 1].plot(energy_vals, total_losses_e, 'b-', lw=2) - axes[0, 1].axvline(TRUTH_ENERGY, color='green', ls='--', lw=2, label='Truth') - axes[0, 1].set_xlabel('Energy (MeV)') - axes[0, 1].set_ylabel('Total SW Loss (U+V+Y)') - axes[0, 1].set_title('Total SW Loss vs Energy') - axes[0, 1].legend() - axes[0, 1].grid(True, alpha=0.3) - - # Bottom-left: nonzero pixels per plane - for p in PLANES: - axes[1, 0].plot(energy_vals, nonzero_per_plane_e[p], lw=1.5, label=PLANE_NAMES[p]) - axes[1, 0].axhline(K, color='red', ls='--', lw=2, label=f'K={K}') - axes[1, 0].axvline(TRUTH_ENERGY, color='green', ls='--', lw=2, label='Truth') - axes[1, 0].set_xlabel('Energy (MeV)') - axes[1, 0].set_ylabel('Nonzero pixels') - axes[1, 0].set_title('Signal Occupancy vs Energy') - axes[1, 0].legend() - axes[1, 0].grid(True, alpha=0.3) - - # Bottom-right: zero-weight in top-K - for p in PLANES: - axes[1, 1].plot(energy_vals, zero_weight_per_plane_e[p], lw=1.5, label=PLANE_NAMES[p]) - axes[1, 1].axvline(TRUTH_ENERGY, color='green', ls='--', lw=2, label='Truth') - axes[1, 1].set_xlabel('Energy (MeV)') - axes[1, 1].set_ylabel('Zero-weight points in top-K') - axes[1, 1].set_title('Top-K Zero Contamination vs Energy') - axes[1, 1].legend() - axes[1, 1].grid(True, alpha=0.3) - - fig.suptitle( - f'Energy Anomaly: V-plane drops below K={K} nonzero pixels at low energy\n' - f'top_k grabs zero-valued pixels → corrupts SW distance', - fontsize=13, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'diagnose_energy_v_plane.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}", flush=True) - - # ========================================================================= - # 4. Wire projection rate dr/ds vs theta plot - # ========================================================================= - fig, ax = plt.subplots(figsize=(10, 5)) - thetas_fine = np.linspace(0.3, 1.2, 200) - - u_drds = 0.866 * np.sin(thetas_fine) + 0.5 * np.cos(thetas_fine) # U at +60 - v_drds = -0.866 * np.sin(thetas_fine) + 0.5 * np.cos(thetas_fine) # V at -60 - y_drds = np.sin(thetas_fine) # Y at 0 (wires along y, measuring z... actually wires vertical, measuring y) - - # Y wires at 0 deg: r = sin(0)*y + cos(0)*z = z - # dr/ds = cos(theta) for the z-component - y_drds = np.cos(thetas_fine) - - ax.plot(thetas_fine, np.abs(u_drds), 'b-', lw=2, label='|dr/ds| U (+60°)') - ax.plot(thetas_fine, np.abs(v_drds), 'r-', lw=2, label='|dr/ds| V (-60°)') - ax.plot(thetas_fine, np.abs(y_drds), 'g-', lw=2, label='|dr/ds| Y (0°)') - ax.axvline(critical_theta, color='red', ls=':', lw=2, alpha=0.7, - label=f'V parallel (θ={critical_theta:.3f})') - ax.axvline(TRUTH_THETA, color='green', ls='--', lw=2, alpha=0.7, label='Truth') - ax.axhline(0, color='k', lw=0.5) - ax.set_xlabel('theta (rad)') - ax.set_ylabel('|dr/ds| (wire crossing rate)') - ax.set_title('Wire Crossing Rate vs Track Angle (phi=π/2)\n' - 'When |dr/ds|→0, track is parallel to wires → signal concentrates on few wires') - ax.legend() - ax.grid(True, alpha=0.3) - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'diagnose_wire_crossing_rate.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f" Saved {fname}", flush=True) - - print("\nDone!", flush=True) - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/diff_muon_generator.py b/closure/archive/muon_intermediate/diff_muon_generator.py deleted file mode 100644 index 151bbe1..0000000 --- a/closure/archive/muon_intermediate/diff_muon_generator.py +++ /dev/null @@ -1,567 +0,0 @@ -""" -Differentiable muon track generator using JAX and PDG dE/dx tables. - -Generates straight-line muon tracks with energy-dependent stopping power. -All operations use JAX primitives so the full pipeline -position/direction/energy -> segments -> wire signals is end-to-end -differentiable. - -Design choices --------------- -- Energy evolution: CSDA range table for fully-parallel O(1) computation. - The range function R(E) = integral(1/dE/dx) is pre-integrated from the - PDG table, enabling E(s) = R^{-1}(R(E_0) - s) for each segment - independently. ~400x faster than the old jax.lax.scan approach. -- dE/dx lookup: log-energy interpolation of PDG table via jnp.interp - (differentiable w.r.t. energy through the interpolation weights). -- Direction: spherical angles (theta, phi) -> unit vector, or trig - components (sin_theta, cos_theta, sin_phi, cos_phi) for optimization. -- The old scan-based versions are available as ``generate_muon_segments_scan`` - and ``generate_muon_segments_trig_scan`` for testing/comparison. -""" - -import jax -import jax.numpy as jnp -import numpy as np -import os - -# Liquid argon density (g/cm^3) -LAR_DENSITY = 1.396 - -# Path to PDG dE/dx data -_DATA_DIR = os.path.join( - os.path.dirname(os.path.dirname(os.path.abspath(__file__))), - "tools", "data", -) -_DEDX_FILE = os.path.join(_DATA_DIR, "muon_dedx_lar.csv") - -# Module-level caches -_DEDX_TABLE_JAX = None -_CSDA_TABLE_JAX = None -_CONSISTENT_CSDA = None - - -# --------------------------------------------------------------------------- -# PDG table loading -# --------------------------------------------------------------------------- - -def load_dedx_table_jax(): - """Load PDG muon dE/dx table as JAX arrays (cached after first call). - - Returns - ------- - log_T_table : jnp.ndarray - Natural log of kinetic energies (MeV). - dedx_table : jnp.ndarray - Stopping power in MeV/cm (already multiplied by LAr density). - """ - global _DEDX_TABLE_JAX - if _DEDX_TABLE_JAX is None: - data = np.loadtxt(_DEDX_FILE, delimiter=",", comments="#") - T_MeV = data[:, 0] - dedx_MeVcm = data[:, 2] * LAR_DENSITY - _DEDX_TABLE_JAX = ( - jnp.array(np.log(T_MeV)), - jnp.array(dedx_MeVcm), - ) - return _DEDX_TABLE_JAX - - -def build_consistent_csda_table(log_T_table, dedx_table, n_points=2000): - """Build CSDA range table by integrating 1/dE/dx from the same table - the scan uses, ensuring perfect consistency between the two methods. - - Parameters - ---------- - log_T_table : jnp.ndarray - Log of kinetic energies from ``load_dedx_table_jax()``. - dedx_table : jnp.ndarray - dE/dx values in MeV/cm from ``load_dedx_table_jax()``. - n_points : int - Number of points in the dense integration grid. - - Returns - ------- - R_cm_table : jnp.ndarray - CSDA range in cm (n_points,). - T_MeV_table : jnp.ndarray - Kinetic energies in MeV (n_points,). - """ - log_T_np = np.asarray(log_T_table) - dedx_np = np.asarray(dedx_table) - - # Dense grid in log-E space (matches jnp.interp's linear interpolation) - log_T_dense = np.linspace(log_T_np[0], log_T_np[-1], n_points) - dedx_dense = np.interp(log_T_dense, log_T_np, dedx_np) - T_dense = np.exp(log_T_dense) - - # Trapezoidal integration of 1/(dE/dx) over dT - inv_dedx = 1.0 / dedx_dense - dT = np.diff(T_dense) - avg_inv = 0.5 * (inv_dedx[:-1] + inv_dedx[1:]) - R_dense = np.concatenate([[0.0], np.cumsum(dT * avg_inv)]) - - return np.asarray(R_dense, dtype=np.float32), np.asarray(T_dense, dtype=np.float32) - - -def load_csda_range_table_jax(n_dense=0): - """Load CSDA range table as JAX arrays (cached after first call). - - The range is read directly from the PDG table (column 4: g/cm^2) - and converted to cm by dividing by LAr density. - - Parameters - ---------- - n_dense : int - If > 0, densify the table to this many points uniformly spaced - in log-energy for improved interpolation accuracy. 0 uses the - raw 82-point PDG table. - - Returns - ------- - R_cm_table : jnp.ndarray - CSDA range in cm (monotonically increasing with energy). - T_MeV_table : jnp.ndarray - Corresponding kinetic energies in MeV. - """ - global _CSDA_TABLE_JAX - if _CSDA_TABLE_JAX is None: - data = np.loadtxt(_DEDX_FILE, delimiter=",", comments="#") - T_MeV = data[:, 0] - R_gcm2 = data[:, 3] - R_cm = R_gcm2 / LAR_DENSITY - - if n_dense > 0: - log_T_raw = np.log(T_MeV) - log_T_dense = np.linspace(log_T_raw[0], log_T_raw[-1], n_dense) - R_cm = np.interp(log_T_dense, log_T_raw, R_cm) - T_MeV = np.exp(log_T_dense) - - _CSDA_TABLE_JAX = (jnp.array(R_cm), jnp.array(T_MeV)) - return _CSDA_TABLE_JAX - - -# --------------------------------------------------------------------------- -# Differentiable dE/dx -# --------------------------------------------------------------------------- - -def diff_dedx(kinetic_energy_mev, log_T_table, dedx_table): - """Differentiable dE/dx lookup via log-energy interpolation. - - Caller must ensure kinetic_energy_mev > 0 (use safe_energy clamp). - - Parameters - ---------- - kinetic_energy_mev : scalar - Muon kinetic energy in MeV. - log_T_table : jnp.ndarray - Log of table energies. - dedx_table : jnp.ndarray - dE/dx values in MeV/cm. - - Returns - ------- - scalar - dE/dx in MeV/cm. - """ - return jnp.interp(jnp.log(kinetic_energy_mev), log_T_table, dedx_table) - - -# --------------------------------------------------------------------------- -# Differentiable muon segment generation -# --------------------------------------------------------------------------- - -def _softplus(x, beta): - """Softplus with temperature: log(1 + exp(beta*x)) / beta. - - Uses logaddexp for numerical stability (no overflow for large beta*x). - """ - return jnp.logaddexp(beta * x, 0.0) / beta - - -def _make_scan_fn(step_vector, step_size_cm, log_T_table, dedx_table, - min_energy_mev, smooth_temperature): - """Build the scan body for energy evolution. - - Factored out so both generate_muon_segments and - generate_muon_segments_trig share the same implementation. - """ - if smooth_temperature > 0: - beta = 1.0 / smooth_temperature - - def scan_fn(carry, _): - pos, energy = carry - safe_energy = _softplus(energy - min_energy_mev, beta) + min_energy_mev - dedx = diff_dedx(safe_energy, log_T_table, dedx_table) - de_raw = dedx * step_size_cm - remaining = _softplus(energy - min_energy_mev, beta) - de = de_raw - _softplus(de_raw - remaining, beta) - gate = jax.nn.sigmoid((energy - min_energy_mev) / smooth_temperature) - de = de * gate - return (pos + step_vector, energy - de), (pos, de) - else: - def scan_fn(carry, _): - pos, energy = carry - safe_energy = jnp.maximum(energy, min_energy_mev) - dedx = diff_dedx(safe_energy, log_T_table, dedx_table) - de_raw = dedx * step_size_cm - remaining = jnp.maximum(energy - min_energy_mev, 0.0) - de = jnp.minimum(de_raw, remaining) - de = jnp.where(energy > min_energy_mev, de, 0.0) - return (pos + step_vector, energy - de), (pos, de) - - return scan_fn - - -def generate_muon_segments_scan( - kinetic_energy_mev, - start_position_mm, - theta, - phi, - step_size_mm, - n_segments, - log_T_table, - dedx_table, - min_energy_mev=10.0, - smooth_temperature=0.0, -): - """Generate muon segments using sequential ``jax.lax.scan`` (slow). - - Kept for testing/comparison. Production code should use - ``generate_muon_segments`` which calls the parallel CSDA path. - """ - sin_theta = jnp.sin(theta) - dir_vec = jnp.array([ - sin_theta * jnp.cos(phi), - sin_theta * jnp.sin(phi), - jnp.cos(theta), - ]) - step_vector = dir_vec * step_size_mm - - scan_fn = _make_scan_fn(step_vector, step_size_mm / 10.0, - log_T_table, dedx_table, - min_energy_mev, smooth_temperature) - - _, (positions, des) = jax.lax.scan( - scan_fn, (start_position_mm, kinetic_energy_mev), - None, length=n_segments, - ) - return positions, des - - -def generate_muon_segments_trig_scan( - kinetic_energy_mev, - start_position_mm, - sin_theta, cos_theta, sin_phi, cos_phi, - step_size_mm, - n_segments, - log_T_table, - dedx_table, - min_energy_mev=10.0, - smooth_temperature=0.0, -): - """Generate muon segments using sequential scan with trig params (slow). - - Kept for testing/comparison. Production code should use - ``generate_muon_segments_trig`` which calls the parallel CSDA path. - """ - dir_unnorm = jnp.array([ - sin_theta * cos_phi, - sin_theta * sin_phi, - cos_theta, - ]) - dir_vec = dir_unnorm / jnp.linalg.norm(dir_unnorm) - step_vector = dir_vec * step_size_mm - - scan_fn = _make_scan_fn(step_vector, step_size_mm / 10.0, - log_T_table, dedx_table, - min_energy_mev, smooth_temperature) - - _, (positions, des) = jax.lax.scan( - scan_fn, (start_position_mm, kinetic_energy_mev), - None, length=n_segments, - ) - return positions, des - - -# --------------------------------------------------------------------------- -# Volume masking -# --------------------------------------------------------------------------- - -def mask_outside_volume(positions, de, half_extents_mm=(2160.0, 2160.0, 2160.0)): - """Zero out dE for segments whose positions fall outside the detector volume. - - Parameters - ---------- - positions : (N, 3) array — segment positions in mm. - de : (N,) array — energy deposits per segment. - half_extents_mm : tuple of 3 floats - Half-extent of the detector volume per axis in mm. - Default 2160.0 = 432 cm / 2 * 10 mm/cm. - - Returns - ------- - de_masked : (N,) array — dE with out-of-volume segments zeroed. - """ - hx, hy, hz = half_extents_mm - in_volume = ( - (jnp.abs(positions[:, 0]) < hx) & - (jnp.abs(positions[:, 1]) < hy) & - (jnp.abs(positions[:, 2]) < hz) - ) - return jnp.where(in_volume, de, 0.0) - - -# --------------------------------------------------------------------------- -# Forward function with correct dx -# --------------------------------------------------------------------------- - -def build_muon_forward(simulator, n_segments, step_size_mm): - """Build a forward function for muon tracks with correct step size. - - Delegates to ``simulator.build_forward(dx_mm=step_size_mm)`` and - wraps it to accept ``(positions_mm, de)`` instead of SegmentData. - - Parameters - ---------- - simulator : DetectorSimulator - Must have been created with ``differentiable=True, n_segments=n_segments``. - n_segments : int - Segment count (must match ``simulator.n_segments``). - step_size_mm : float - Muon step size in mm. - - Returns - ------- - forward : callable - ``forward(positions_mm, de) -> tuple`` of 6 response arrays - (east_U, east_V, east_Y, west_U, west_V, west_Y). - """ - from tools.config import SegmentData - inner = simulator.build_forward(dx_mm=step_size_mm) - - def forward(positions_mm, de): - return inner(SegmentData(positions_mm=positions_mm, de=de)) - - return forward - - -# --------------------------------------------------------------------------- -# CSDA range-based parallel segment generation -# --------------------------------------------------------------------------- - -def _csda_energy_deposits(kinetic_energy_mev, step_size_cm, n_segments, - R_cm_table, T_MeV_table, relax_steps=2.0): - """Compute energy deposits in parallel using CSDA range table. - - The CSDA range R(E) = integral of 1/(dE/dx) maps energy to total - remaining path length. The inverse R^{-1} gives energy at any - distance along the track, turning the sequential recurrence into - independent lookups: E(s) = R^{-1}(R(E_0) - s). - - A soft clamp (softplus) replaces ``jnp.maximum(R, R_floor)`` at the - stopping boundary. This shifts the last few segments' dE by - O(relax * ln2) — negligible for physics — but makes the gradient - smooth at the Bragg peak. JAX auto-diff handles the backward pass; - no custom_jvp is needed because softplus + jnp.interp compose into - a smooth enough gradient for the full simulation pipeline. - """ - indices = jnp.arange(n_segments) - log_T_csda = jnp.log(T_MeV_table) - - # Forward lookup: E_0 -> R(E_0) - R_initial = jnp.interp(jnp.log(kinetic_energy_mev), log_T_csda, R_cm_table) - - # Remaining range at start and end of each segment - R_at_start = R_initial - indices * step_size_cm - R_at_end = R_initial - (indices + 1) * step_size_cm - - # Soft clamp: smoothed version of max(R, R_floor). - # softplus(x/relax)*relax ≈ max(x, 0) but with smooth derivative (sigmoid). - # relax controls the transition width at the stopping boundary. - R_floor = R_cm_table[0] - relax = step_size_cm * relax_steps - R_start_soft = R_floor + jax.nn.softplus((R_at_start - R_floor) / relax) * relax - R_end_soft = R_floor + jax.nn.softplus((R_at_end - R_floor) / relax) * relax - - E_start = jnp.interp(R_start_soft, R_cm_table, T_MeV_table) - E_end = jnp.interp(R_end_soft, R_cm_table, T_MeV_table) - - return jnp.maximum(E_start - E_end, 0.0) - - -def generate_muon_segments_csda( - kinetic_energy_mev, - start_position_mm, - theta, - phi, - step_size_mm, - n_segments, - log_T_table, - dedx_table, - R_cm_table, - T_MeV_table, - relax_steps=2.0, -): - """Generate muon segments using CSDA range table (fully parallel). - - Same physics as ``generate_muon_segments`` but replaces the O(N) - sequential ``jax.lax.scan`` with O(1) parallel table lookups. - """ - sin_theta = jnp.sin(theta) - dir_vec = jnp.array([ - sin_theta * jnp.cos(phi), - sin_theta * jnp.sin(phi), - jnp.cos(theta), - ]) - step_vector = dir_vec * step_size_mm - - indices = jnp.arange(n_segments) - positions = start_position_mm[None, :] + indices[:, None] * step_vector[None, :] - - de = _csda_energy_deposits( - kinetic_energy_mev, step_size_mm / 10.0, n_segments, - R_cm_table, T_MeV_table, relax_steps, - ) - return positions, de - - -def generate_muon_segments_trig_csda( - kinetic_energy_mev, - start_position_mm, - sin_theta, cos_theta, sin_phi, cos_phi, - step_size_mm, - n_segments, - log_T_table, - dedx_table, - R_cm_table, - T_MeV_table, - relax_steps=2.0, -): - """Generate muon segments using CSDA range with trig parameterization.""" - dir_unnorm = jnp.array([ - sin_theta * cos_phi, - sin_theta * sin_phi, - cos_theta, - ]) - dir_vec = dir_unnorm / jnp.linalg.norm(dir_unnorm) - step_vector = dir_vec * step_size_mm - - indices = jnp.arange(n_segments) - positions = start_position_mm[None, :] + indices[:, None] * step_vector[None, :] - - de = _csda_energy_deposits( - kinetic_energy_mev, step_size_mm / 10.0, n_segments, - R_cm_table, T_MeV_table, relax_steps, - ) - return positions, de - - -# --------------------------------------------------------------------------- -# Public API — CSDA-backed wrappers (drop-in replacements for scan versions) -# --------------------------------------------------------------------------- - -def _get_consistent_csda(log_T_table, dedx_table): - """Lazily build and cache the consistent CSDA table.""" - global _CONSISTENT_CSDA - if _CONSISTENT_CSDA is None: - _CONSISTENT_CSDA = build_consistent_csda_table(log_T_table, dedx_table) - return _CONSISTENT_CSDA - - -def generate_muon_segments( - kinetic_energy_mev, - start_position_mm, - theta, - phi, - step_size_mm, - n_segments, - log_T_table, - dedx_table, - relax_steps=2.0, -): - """Generate a straight-line muon track as differentiable JAX arrays. - - Uses the CSDA range table for fully-parallel O(1) computation. - - Parameters - ---------- - kinetic_energy_mev : scalar - Initial muon kinetic energy in MeV. - start_position_mm : (3,) array - Starting (x, y, z) in mm. - theta : scalar - Polar angle from z-axis (radians). - phi : scalar - Azimuthal angle in xy-plane (radians). - step_size_mm : float - Segment length in mm (static, not traced by JAX). - n_segments : int - Maximum number of segments (static for JIT). - log_T_table, dedx_table : jnp.ndarray - PDG stopping-power table arrays from ``load_dedx_table_jax()``. - relax_steps : float - Softplus relaxation width in units of step size (default 2.0). - - Returns - ------- - positions_mm : (n_segments, 3) - Segment centre positions in mm. - de : (n_segments,) - Energy deposit per segment in MeV (0 for exhausted segments). - """ - R_cm, T_MeV = _get_consistent_csda(log_T_table, dedx_table) - return generate_muon_segments_csda( - kinetic_energy_mev, start_position_mm, theta, phi, - step_size_mm, n_segments, log_T_table, dedx_table, - R_cm, T_MeV, relax_steps, - ) - - -def generate_muon_segments_trig( - kinetic_energy_mev, - start_position_mm, - sin_theta, cos_theta, sin_phi, cos_phi, - step_size_mm, - n_segments, - log_T_table, - dedx_table, - relax_steps=2.0, -): - """Generate muon segments using trig parameterization (sin/cos). - - Uses the CSDA range table for fully-parallel O(1) computation. - - Parameters - ---------- - kinetic_energy_mev : scalar - Initial muon kinetic energy in MeV. - start_position_mm : (3,) array - Starting (x, y, z) in mm. - sin_theta, cos_theta : scalar - Polar angle trig components. - sin_phi, cos_phi : scalar - Azimuthal angle trig components. - step_size_mm : float - Segment length in mm (static, not traced by JAX). - n_segments : int - Maximum number of segments (static for JIT). - log_T_table, dedx_table : jnp.ndarray - PDG stopping-power table arrays from ``load_dedx_table_jax()``. - relax_steps : float - Softplus relaxation width in units of step size (default 2.0). - - Returns - ------- - positions_mm : (n_segments, 3) - Segment centre positions in mm. - de : (n_segments,) - Energy deposit per segment in MeV (0 for exhausted segments). - """ - R_cm, T_MeV = _get_consistent_csda(log_T_table, dedx_table) - return generate_muon_segments_trig_csda( - kinetic_energy_mev, start_position_mm, - sin_theta, cos_theta, sin_phi, cos_phi, - step_size_mm, n_segments, log_T_table, dedx_table, - R_cm, T_MeV, relax_steps, - ) diff --git a/closure/archive/muon_intermediate/energy_segment_study.py b/closure/archive/muon_intermediate/energy_segment_study.py deleted file mode 100644 index c45f716..0000000 --- a/closure/archive/muon_intermediate/energy_segment_study.py +++ /dev/null @@ -1,216 +0,0 @@ -""" -Energy gradient surface vs segment size. - -Tests whether the seesaw in energy autodiff gradients is caused by -coarse segment discretization in the lax.scan dE/dx chain. - -Run from project root: - python3 closure_analysis_muon/energy_segment_study.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import blur_mse_loss, make_spectral_weight, DEFAULT_BLUR_SIGMAS - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments, - build_muon_forward, -) - -# ── Config ── -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 2 -TRUTH_ENERGY = 200.0 -PLANES = [0, 1, 2] -N_SWEEP = 40 -ENERGY_RANGE = (100.0, 280.0) -FD_EPS = 0.5 - -# Segment configs: (step_size_mm, n_segments) -# 200 MeV muon range ~950mm, so need enough segments to cover it -SEGMENT_CONFIGS = [ - (1.0, 1400), # coarse - (0.5, 2800), # current default - (0.25, 5600), # fine - (0.1, 14000), # very fine -] - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -def run_energy_sweep(step_size, n_seg, log_T, dedx): - """Run energy sweep for one segment configuration.""" - print(f"\n{'='*50}") - print(f"Step size: {step_size}mm, N segments: {n_seg}") - print(f"{'='*50}") - - # Build simulator - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg) - forward = build_muon_forward(sim, n_seg, step_size) - - def sim_forward(x, y, z, theta, phi, energy): - pos, de = generate_muon_segments( - energy, jnp.array([x, y, z]), theta, phi, - step_size, n_seg, log_T, dedx, - ) - return forward(pos, de) - - truth_args = ( - jnp.float32(TRUTH_X), jnp.float32(TRUTH_Y), jnp.float32(TRUTH_Z), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), jnp.float32(TRUTH_ENERGY), - ) - - # Compile sim - print("Compiling sim...", flush=True) - t0 = time.time() - sim_jit = jax.jit(sim_forward) - truth_signals = sim_jit(*truth_args) - for s in truth_signals: - jax.block_until_ready(s) - print(f" sim compiled ({time.time()-t0:.1f}s)", flush=True) - - # Precompute spectral weights - planes_tuple = tuple(PLANES) - sw_tuple = tuple( - make_spectral_weight(*truth_signals[i].shape, DEFAULT_BLUR_SIGMAS) - if i in PLANES else jnp.zeros((1, 1)) - for i in range(6) - ) - - def blur_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - return blur_mse_loss(sigs, truth_signals, sw_tuple, planes=planes_tuple) - - # Compile loss + grad - print("Compiling loss+grad...", flush=True) - ALL = (0, 1, 2, 3, 4, 5) - blur_jit = jax.jit(blur_loss) - blur_vg = jax.jit(jax.value_and_grad(blur_loss, argnums=ALL)) - - t0 = time.time() - _ = blur_jit(*truth_args) - print(f" fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - _ = blur_vg(*truth_args) - print(f" fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - # Energy sweep - e_vals = np.linspace(*ENERGY_RANGE, N_SWEEP) - losses = np.empty(N_SWEEP) - ad_grads = np.empty(N_SWEEP) - - print("Sweeping energy...", flush=True) - t0 = time.time() - for i, e in enumerate(e_vals): - a = list(truth_args) - a[5] = jnp.float32(e) - a = tuple(a) - loss, grads = blur_vg(*a) - losses[i] = float(loss) - ad_grads[i] = float(grads[5]) # energy is index 5 - - fd_grads = np.array([ - (float(blur_jit(*_args(truth_args, e + FD_EPS))) - - float(blur_jit(*_args(truth_args, e - FD_EPS)))) / (2 * FD_EPS) - for e in e_vals - ]) - print(f" done ({time.time()-t0:.1f}s)", flush=True) - - return e_vals, losses, ad_grads, fd_grads - - -def _args(truth_args, energy): - a = list(truth_args) - a[5] = jnp.float32(energy) - return tuple(a) - - -def main(): - log_T, dedx = load_dedx_table_jax() - - results = {} - for step_size, n_seg in SEGMENT_CONFIGS: - label = f"{step_size}mm ({n_seg} seg)" - e_vals, losses, ad_grads, fd_grads = run_energy_sweep( - step_size, n_seg, log_T, dedx, - ) - results[label] = (e_vals, losses, ad_grads, fd_grads) - - # ── Plot ── - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - colors = ['C0', 'C1', 'C2', 'C3'] - - # Loss landscapes - ax = axes[0, 0] - for (label, (e, l, _, _)), c in zip(results.items(), colors): - ax.plot(e, l, color=c, lw=1.5, label=label) - ax.axvline(TRUTH_ENERGY, color='green', ls='--', lw=2) - ax.set_xlabel('energy (MeV)') - ax.set_ylabel('Blur Loss') - ax.set_title('Loss Landscape') - ax.legend() - ax.grid(True, alpha=0.3) - - # Autodiff gradients - ax = axes[0, 1] - for (label, (e, _, ag, _)), c in zip(results.items(), colors): - ax.plot(e, ag, color=c, lw=1.5, label=label) - ax.axhline(0, color='k', ls='-', lw=0.5) - ax.axvline(TRUTH_ENERGY, color='green', ls='--', lw=2) - ax.set_xlabel('energy (MeV)') - ax.set_ylabel('dBlur/denergy (autodiff)') - ax.set_title('Autodiff Gradient') - ax.legend() - ax.grid(True, alpha=0.3) - - # FD gradients - ax = axes[1, 0] - for (label, (e, _, _, fg)), c in zip(results.items(), colors): - ax.plot(e, fg, color=c, lw=1.5, label=label) - ax.axhline(0, color='k', ls='-', lw=0.5) - ax.axvline(TRUTH_ENERGY, color='green', ls='--', lw=2) - ax.set_xlabel('energy (MeV)') - ax.set_ylabel('dBlur/denergy (FD)') - ax.set_title('Finite-Difference Gradient') - ax.legend() - ax.grid(True, alpha=0.3) - - # Autodiff vs FD overlay for finest - ax = axes[1, 1] - finest_label = list(results.keys())[-1] - e, _, ag, fg = results[finest_label] - ax.plot(e, ag, 'r-', lw=1.5, label='Autodiff') - ax.plot(e, fg, 'b--', lw=1.5, alpha=0.7, label='FD') - ax.axhline(0, color='k', ls='-', lw=0.5) - ax.axvline(TRUTH_ENERGY, color='green', ls='--', lw=2) - ax.set_xlabel('energy (MeV)') - ax.set_ylabel('dBlur/denergy') - ax.set_title(f'Autodiff vs FD — {finest_label}') - ax.legend() - ax.grid(True, alpha=0.3) - - fig.suptitle( - 'Energy Gradient vs Segment Size (muon, summed U+V+Y)', - fontsize=14, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'energy_segment_study.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"\nSaved {fname}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/muon_angle_optimization.py b/closure/archive/muon_intermediate/muon_angle_optimization.py deleted file mode 100644 index 8db9437..0000000 --- a/closure/archive/muon_intermediate/muon_angle_optimization.py +++ /dev/null @@ -1,342 +0,0 @@ -""" -Compare angle optimization: direct (theta, phi) vs trig (sin/cos) parameterization. - -Both optimize only the two angles (theta, phi) to match a truth muon signal, -with all other parameters (x, y, z, energy) fixed at truth. - -1. Direct: optimize theta, phi with Adam -2. Trig: optimize (sin_theta, cos_theta, sin_phi, cos_phi) with Adam, - reconstruct angles via atan2 for the simulation - -Both use SW loss on east-side planes. - -Run from project root: - python3 closure_analysis_muon/muon_angle_optimization.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import optax -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments, - generate_muon_segments_trig, - build_muon_forward, -) - -# ============================================================================= -# Configuration -# ============================================================================= - -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 - -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA = np.pi / 4 # 0.785 rad -TRUTH_PHI = np.pi / 2 # 1.571 rad -TRUTH_ENERGY = 200.0 - -# Starting guess: offset from truth -INIT_THETA = TRUTH_THETA + 0.3 # ~62 deg vs 45 deg -INIT_PHI = TRUTH_PHI - 0.4 # ~67 deg vs 90 deg - -PLANES = [0, 1, 2] -K = 10000 -N_PROJ = 200 -N_STEPS = 200 -LR = 1e-2 - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -def main(): - print("=" * 60, flush=True) - print("ANGLE OPTIMIZATION: DIRECT vs TRIG", flush=True) - print("=" * 60, flush=True) - print(f"Truth: theta={TRUTH_THETA:.4f}, phi={TRUTH_PHI:.4f}", flush=True) - print(f"Init: theta={INIT_THETA:.4f}, phi={INIT_PHI:.4f}", flush=True) - print(f"Steps: {N_STEPS}, LR: {LR}", flush=True) - - # --- Setup --- - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - ot_key = jax.random.PRNGKey(42) - - # Fixed params - pos_fixed = jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], dtype=jnp.float32) - energy_fixed = jnp.float32(TRUTH_ENERGY) - - # --- Generate truth --- - print("\nGenerating truth signal...", flush=True) - truth_pos, truth_de = generate_muon_segments( - energy_fixed, pos_fixed, jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - truth_sigs = forward(truth_pos, truth_de) - for s in truth_sigs: - jax.block_until_ready(s) - - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(truth_sigs[p], K) - target_clouds[p] = (pts, w) - - # ================================================================= - # Method 1: Direct angle parameterization - # ================================================================= - print("\n--- Compiling DIRECT loss ---", flush=True) - - def direct_loss(params): - theta, phi = params['theta'], params['phi'] - pos, de = generate_muon_segments( - energy_fixed, pos_fixed, theta, phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - sigs = forward(pos, de) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + sliced_wasserstein_loss_jit( - pts, w, target_clouds[p][0], target_clouds[p][1], - ot_key, n_projections=N_PROJ, - ) - return loss - - direct_vg = jax.jit(jax.value_and_grad(direct_loss)) - - # Warmup compile - t0 = time.time() - init_direct = {'theta': jnp.float32(INIT_THETA), 'phi': jnp.float32(INIT_PHI)} - _l, _g = direct_vg(init_direct) - jax.block_until_ready(_l) - print(f" Compiled ({time.time()-t0:.1f}s)", flush=True) - print(f" Init loss: {float(_l):.2f}", flush=True) - - # Run optimization - print(" Running Adam...", flush=True) - optimizer = optax.adam(LR) - params = init_direct - opt_state = optimizer.init(params) - - direct_history = {'loss': [], 'theta': [], 'phi': []} - t0 = time.time() - for step in range(N_STEPS): - loss, grads = direct_vg(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - params = optax.apply_updates(params, updates) - - direct_history['loss'].append(float(loss)) - direct_history['theta'].append(float(params['theta'])) - direct_history['phi'].append(float(params['phi'])) - - if step % 50 == 0 or step == N_STEPS - 1: - print(f" step {step:3d}: loss={float(loss):.2f}, " - f"theta={float(params['theta']):.4f}, phi={float(params['phi']):.4f}", - flush=True) - - direct_time = time.time() - t0 - print(f" Done ({direct_time:.1f}s)", flush=True) - - # ================================================================= - # Method 2: Trig parameterization - # ================================================================= - print("\n--- Compiling TRIG loss ---", flush=True) - - def trig_loss(params): - sin_theta = params['sin_theta'] - cos_theta = params['cos_theta'] - sin_phi = params['sin_phi'] - cos_phi = params['cos_phi'] - pos, de = generate_muon_segments_trig( - energy_fixed, pos_fixed, - sin_theta, cos_theta, sin_phi, cos_phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - sigs = forward(pos, de) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + sliced_wasserstein_loss_jit( - pts, w, target_clouds[p][0], target_clouds[p][1], - ot_key, n_projections=N_PROJ, - ) - return loss - - trig_vg = jax.jit(jax.value_and_grad(trig_loss)) - - # Init from same angles - init_trig = { - 'sin_theta': jnp.float32(jnp.sin(INIT_THETA)), - 'cos_theta': jnp.float32(jnp.cos(INIT_THETA)), - 'sin_phi': jnp.float32(jnp.sin(INIT_PHI)), - 'cos_phi': jnp.float32(jnp.cos(INIT_PHI)), - } - - t0 = time.time() - _l, _g = trig_vg(init_trig) - jax.block_until_ready(_l) - print(f" Compiled ({time.time()-t0:.1f}s)", flush=True) - print(f" Init loss: {float(_l):.2f}", flush=True) - - # Run optimization - print(" Running Adam...", flush=True) - optimizer_trig = optax.adam(LR) - params_trig = init_trig - opt_state_trig = optimizer_trig.init(params_trig) - - trig_history = {'loss': [], 'theta': [], 'phi': [], - 'sin_theta': [], 'cos_theta': [], 'sin_phi': [], 'cos_phi': []} - t0 = time.time() - for step in range(N_STEPS): - loss, grads = trig_vg(params_trig) - updates, opt_state_trig = optimizer_trig.update(grads, opt_state_trig, params_trig) - params_trig = optax.apply_updates(params_trig, updates) - - # Project back onto unit circle after each step - norm_t = jnp.sqrt(params_trig['sin_theta']**2 + params_trig['cos_theta']**2) - norm_p = jnp.sqrt(params_trig['sin_phi']**2 + params_trig['cos_phi']**2) - params_trig = { - 'sin_theta': params_trig['sin_theta'] / norm_t, - 'cos_theta': params_trig['cos_theta'] / norm_t, - 'sin_phi': params_trig['sin_phi'] / norm_p, - 'cos_phi': params_trig['cos_phi'] / norm_p, - } - - # Recover effective angles - eff_theta = float(jnp.arctan2(params_trig['sin_theta'], params_trig['cos_theta'])) - eff_phi = float(jnp.arctan2(params_trig['sin_phi'], params_trig['cos_phi'])) - - trig_history['loss'].append(float(loss)) - trig_history['theta'].append(eff_theta) - trig_history['phi'].append(eff_phi) - trig_history['sin_theta'].append(float(params_trig['sin_theta'])) - trig_history['cos_theta'].append(float(params_trig['cos_theta'])) - trig_history['sin_phi'].append(float(params_trig['sin_phi'])) - trig_history['cos_phi'].append(float(params_trig['cos_phi'])) - - if step % 50 == 0 or step == N_STEPS - 1: - norm_t = float(jnp.sqrt(params_trig['sin_theta']**2 + params_trig['cos_theta']**2)) - norm_p = float(jnp.sqrt(params_trig['sin_phi']**2 + params_trig['cos_phi']**2)) - print(f" step {step:3d}: loss={float(loss):.2f}, " - f"theta_eff={eff_theta:.4f}, phi_eff={eff_phi:.4f}, " - f"|t|={norm_t:.3f}, |p|={norm_p:.3f}", - flush=True) - - trig_time = time.time() - t0 - print(f" Done ({trig_time:.1f}s)", flush=True) - - # ================================================================= - # Plot comparison - # ================================================================= - print("\nGenerating plots...", flush=True) - - fig, axes = plt.subplots(2, 3, figsize=(18, 10)) - - steps = np.arange(N_STEPS) - - # Row 0: Loss convergence - axes[0, 0].plot(steps, direct_history['loss'], 'b-', lw=1.5, label='Direct (θ, φ)') - axes[0, 0].plot(steps, trig_history['loss'], 'r-', lw=1.5, label='Trig (sin/cos)') - axes[0, 0].set_xlabel('Step') - axes[0, 0].set_ylabel('SW Loss') - axes[0, 0].set_title('Loss Convergence') - axes[0, 0].legend() - axes[0, 0].grid(True, alpha=0.3) - axes[0, 0].set_yscale('log') - - # Row 0: Theta convergence - axes[0, 1].plot(steps, direct_history['theta'], 'b-', lw=1.5, label='Direct θ') - axes[0, 1].plot(steps, trig_history['theta'], 'r-', lw=1.5, label='Trig θ_eff') - axes[0, 1].axhline(TRUTH_THETA, color='green', ls='--', lw=2, label=f'Truth θ={TRUTH_THETA:.3f}') - axes[0, 1].set_xlabel('Step') - axes[0, 1].set_ylabel('Theta (rad)') - axes[0, 1].set_title('Theta Convergence') - axes[0, 1].legend() - axes[0, 1].grid(True, alpha=0.3) - - # Row 0: Phi convergence - axes[0, 2].plot(steps, direct_history['phi'], 'b-', lw=1.5, label='Direct φ') - axes[0, 2].plot(steps, trig_history['phi'], 'r-', lw=1.5, label='Trig φ_eff') - axes[0, 2].axhline(TRUTH_PHI, color='green', ls='--', lw=2, label=f'Truth φ={TRUTH_PHI:.3f}') - axes[0, 2].set_xlabel('Step') - axes[0, 2].set_ylabel('Phi (rad)') - axes[0, 2].set_title('Phi Convergence') - axes[0, 2].legend() - axes[0, 2].grid(True, alpha=0.3) - - # Row 1: Trig components - axes[1, 0].plot(steps, trig_history['sin_theta'], '-', lw=1.5, label='sin_θ') - axes[1, 0].plot(steps, trig_history['cos_theta'], '-', lw=1.5, label='cos_θ') - axes[1, 0].axhline(np.sin(TRUTH_THETA), color='C0', ls='--', alpha=0.5) - axes[1, 0].axhline(np.cos(TRUTH_THETA), color='C1', ls='--', alpha=0.5) - axes[1, 0].set_xlabel('Step') - axes[1, 0].set_ylabel('Value') - axes[1, 0].set_title('Trig: θ components') - axes[1, 0].legend() - axes[1, 0].grid(True, alpha=0.3) - - axes[1, 1].plot(steps, trig_history['sin_phi'], '-', lw=1.5, label='sin_φ') - axes[1, 1].plot(steps, trig_history['cos_phi'], '-', lw=1.5, label='cos_φ') - axes[1, 1].axhline(np.sin(TRUTH_PHI), color='C0', ls='--', alpha=0.5) - axes[1, 1].axhline(np.cos(TRUTH_PHI), color='C1', ls='--', alpha=0.5) - axes[1, 1].set_xlabel('Step') - axes[1, 1].set_ylabel('Value') - axes[1, 1].set_title('Trig: φ components') - axes[1, 1].legend() - axes[1, 1].grid(True, alpha=0.3) - - # Row 1: Trajectory in theta-phi space - axes[1, 2].plot(direct_history['theta'], direct_history['phi'], 'b.-', - ms=2, lw=0.5, alpha=0.7, label='Direct') - axes[1, 2].plot(trig_history['theta'], trig_history['phi'], 'r.-', - ms=2, lw=0.5, alpha=0.7, label='Trig') - axes[1, 2].plot(TRUTH_THETA, TRUTH_PHI, 'g*', ms=15, label='Truth') - axes[1, 2].plot(INIT_THETA, INIT_PHI, 'kx', ms=10, mew=2, label='Init') - axes[1, 2].set_xlabel('Theta (rad)') - axes[1, 2].set_ylabel('Phi (rad)') - axes[1, 2].set_title('Trajectory in (θ, φ) space') - axes[1, 2].legend() - axes[1, 2].grid(True, alpha=0.3) - - fig.suptitle( - f'Angle Optimization: Direct vs Trig Parameterization\n' - f'Init: θ={INIT_THETA:.3f}, φ={INIT_PHI:.3f} → ' - f'Truth: θ={TRUTH_THETA:.3f}, φ={TRUTH_PHI:.3f} | ' - f'Adam LR={LR}, {N_STEPS} steps', - fontsize=13, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'optimization_angle_comparison.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}", flush=True) - - # Print final summary - print(f"\n{'='*60}", flush=True) - print("SUMMARY", flush=True) - print(f"{'='*60}", flush=True) - print(f" Direct: final loss={direct_history['loss'][-1]:.2f}, " - f"theta={direct_history['theta'][-1]:.4f}, phi={direct_history['phi'][-1]:.4f} " - f"({direct_time:.1f}s)", flush=True) - print(f" Trig: final loss={trig_history['loss'][-1]:.2f}, " - f"theta={trig_history['theta'][-1]:.4f}, phi={trig_history['phi'][-1]:.4f} " - f"({trig_time:.1f}s)", flush=True) - print(f" Truth: theta={TRUTH_THETA:.4f}, phi={TRUTH_PHI:.4f}", flush=True) - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/muon_event_display.py b/closure/archive/muon_intermediate/muon_event_display.py deleted file mode 100644 index 2457a15..0000000 --- a/closure/archive/muon_intermediate/muon_event_display.py +++ /dev/null @@ -1,349 +0,0 @@ -""" -Muon event display and parameter variation visualization. - -Generates: - 1. muon_event_display.png - 6-panel wire signal display (all planes) - 2. muon_variation_{param}.png - truth vs perturbed signal for each parameter - 3. muon_track_3d.png - 3D scatter of the generated muon segments - -Run from project root: - python3 closure_analysis_muon/muon_event_display.py - -Design choices --------------- -- n_segments = 500, step_size = 3 mm (0.3 cm) -- Default muon: 200 MeV, start (-500, 0, 100) mm, - theta = pi/4, phi = pi/2 (diagonal in y-z plane, deep in east side) -- Response path only: no noise, no electronics, no E-field distortions -- Visualization uses the tools.visualization module for consistent style -- Parameter perturbations chosen to give visible but small signal changes -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.visualization import visualize_wire_signals - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments, - build_muon_forward, -) - -# ============================================================================= -# Configuration -# ============================================================================= - -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 # 0.05 cm per step - -# Truth muon parameters -TRUTH_X = -500.0 # mm (deep in east side, track stays east for all angle sweeps) -TRUTH_Y = 0.0 # mm -TRUTH_Z = 100.0 # mm -TRUTH_THETA = np.pi / 4 # 45 deg from z-axis -TRUTH_PHI = np.pi / 2 # in y-z plane (no x component) -TRUTH_ENERGY = 200.0 # MeV - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -# Perturbation sizes for parameter variation plots -PERTURBATIONS = { - 'x': 10.0, # mm - 'y': 10.0, # mm - 'z': 10.0, # mm - 'theta': 0.1, # rad (~5.7 deg) - 'phi': 0.1, # rad - 'energy': 20.0, # MeV -} - - -# ============================================================================= -# Helpers -# ============================================================================= - -def make_muon_params(x=TRUTH_X, y=TRUTH_Y, z=TRUTH_Z, - theta=TRUTH_THETA, phi=TRUTH_PHI, energy=TRUTH_ENERGY): - """Pack muon parameters as JAX scalars/arrays.""" - return ( - jnp.float32(energy), - jnp.array([x, y, z], dtype=jnp.float32), - jnp.float32(theta), - jnp.float32(phi), - ) - - -def simulate_muon(energy, pos, theta, phi, forward, log_T, dedx): - """Generate segments and run detector simulation.""" - positions, des = generate_muon_segments( - energy, pos, theta, phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - signals = forward(positions, des) - return signals, positions, des - - -def signals_to_dict(signals): - """Convert 6-tuple to (side, plane) dict for visualization.""" - d = {} - for side in range(2): - for plane in range(3): - d[(side, plane)] = signals[side * 3 + plane] - return d - - -# ============================================================================= -# Main -# ============================================================================= - -def main(): - print("=" * 60) - print("MUON EVENT DISPLAY AND PARAMETER VARIATIONS") - print("=" * 60) - print(f"n_segments={N_SEGMENTS}, step_size={STEP_SIZE_MM} mm") - print(f"Truth: E={TRUTH_ENERGY} MeV, pos=({TRUTH_X},{TRUTH_Y},{TRUTH_Z}) mm") - print(f" theta={TRUTH_THETA:.4f} rad, phi={TRUTH_PHI:.4f} rad") - - # --- Load PDG table and detector --- - print("\nLoading PDG dE/dx table...") - log_T, dedx = load_dedx_table_jax() - - print("Loading detector config...") - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - - print("Creating differentiable simulator...") - sim = DetectorSimulator( - detector_config, - differentiable=True, - n_segments=N_SEGMENTS, - ) - - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - # --- Generate truth muon --- - print("Generating truth muon track...") - energy, pos, theta, phi = make_muon_params() - t0 = time.time() - truth_signals, truth_pos, truth_de = simulate_muon( - energy, pos, theta, phi, forward, log_T, dedx, - ) - # Block until ready - for s in truth_signals: - jax.block_until_ready(s) - t1 = time.time() - - n_active = int(jnp.sum(truth_de > 0)) - total_de = float(jnp.sum(truth_de)) - track_len_cm = n_active * STEP_SIZE_MM / 10.0 - print(f" Active segments: {n_active}/{N_SEGMENTS}") - print(f" Total dE: {total_de:.1f} MeV") - print(f" Track length: {track_len_cm:.1f} cm") - print(f" First forward pass: {t1 - t0:.2f}s (includes JIT)") - - # ========================================================================= - # 1. Event display (6 planes) - # ========================================================================= - print("\nGenerating event display...") - wire_dict = signals_to_dict(truth_signals) - fig = visualize_wire_signals( - wire_dict, detector_config, - sparse_data=False, threshold_enc=0, gamma=0.3, - ) - fig.suptitle( - f'Muon Event Display — {TRUTH_ENERGY:.0f} MeV, ' - f'{n_active} segments, track {track_len_cm:.0f} cm', - fontsize=14, fontweight='bold', y=1.02, - ) - fname = os.path.join(OUT_DIR, 'muon_event_display.png') - fig.savefig(fname, dpi=150, bbox_inches='tight', facecolor='white') - plt.close(fig) - print(f" Saved {fname}") - - # ========================================================================= - # 1b. Zoomed event display (east-side only, cropped to signal region) - # ========================================================================= - print("Generating zoomed event display...") - plane_names = ['1st Induction (U)', '2nd Induction (V)', 'Collection (Y)'] - fig_zoom, axes_zoom = plt.subplots(1, 3, figsize=(18, 5)) - for pi in range(3): - sig_np = np.array(truth_signals[pi]) # already in ADC (kernel includes conversion) - nz = np.nonzero(np.abs(sig_np) > 0.01) - if len(nz[0]) > 0: - wlo = max(0, nz[0].min() - 20) - whi = min(sig_np.shape[0], nz[0].max() + 20) - tlo = max(0, nz[1].min() - 40) - thi = min(sig_np.shape[1], nz[1].max() + 40) - else: - wlo, whi = 0, sig_np.shape[0] - tlo, thi = 0, sig_np.shape[1] - crop = sig_np[wlo:whi, tlo:thi] - vabs = np.abs(crop).max() - if vabs < 1e-10: - vabs = 1.0 - im = axes_zoom[pi].imshow( - crop.T, aspect='auto', origin='lower', - extent=[wlo, whi, tlo, thi], - cmap='RdBu_r', vmin=-vabs, vmax=vabs, - interpolation='nearest', - ) - axes_zoom[pi].set_title(f'East {plane_names[pi]}') - axes_zoom[pi].set_xlabel('Wire index') - axes_zoom[pi].set_ylabel('Time bin') - fig_zoom.colorbar(im, ax=axes_zoom[pi], label='ADC', shrink=0.8) - - fig_zoom.suptitle( - f'Muon Event Display (Zoomed) — {TRUTH_ENERGY:.0f} MeV, ' - f'{n_active} segments, track {track_len_cm:.0f} cm', - fontsize=14, fontweight='bold', - ) - fig_zoom.tight_layout() - fname = os.path.join(OUT_DIR, 'muon_event_display_zoomed.png') - fig_zoom.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig_zoom) - print(f" Saved {fname}") - - # ========================================================================= - # 2. 3D track visualization - # ========================================================================= - print("Generating 3D track plot...") - pos_np = np.array(truth_pos) - de_np = np.array(truth_de) - active = de_np > 0 - - fig = plt.figure(figsize=(10, 8)) - ax = fig.add_subplot(111, projection='3d') - sc = ax.scatter( - pos_np[active, 0], pos_np[active, 1], pos_np[active, 2], - c=de_np[active], cmap='hot', s=2, alpha=0.8, - ) - fig.colorbar(sc, ax=ax, label='dE (MeV)', shrink=0.6) - ax.set_xlabel('x (mm)') - ax.set_ylabel('y (mm)') - ax.set_zlabel('z (mm)') - ax.set_title(f'Muon Track — {TRUTH_ENERGY:.0f} MeV') - fname = os.path.join(OUT_DIR, 'muon_track_3d.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}") - - # ========================================================================= - # 3. Parameter variation figures (zoomed to signal region) - # ========================================================================= - print("\nGenerating parameter variation figures...") - - # Use east-side Y plane (index 2) for variation visualization - truth_Y = np.array(truth_signals[2]) # east Y plane - truth_Y_adc = truth_Y # already in ADC (kernel includes conversion) - - # Find bounding box of the signal region (with generous padding) - nonzero = np.nonzero(np.abs(truth_Y_adc) > 0.01) - if len(nonzero[0]) > 0: - w_lo = max(0, nonzero[0].min() - 30) - w_hi = min(truth_Y_adc.shape[0], nonzero[0].max() + 30) - t_lo = max(0, nonzero[1].min() - 50) - t_hi = min(truth_Y_adc.shape[1], nonzero[1].max() + 50) - else: - w_lo, w_hi = 0, truth_Y_adc.shape[0] - t_lo, t_hi = 0, truth_Y_adc.shape[1] - - print(f" Signal region: wire [{w_lo}, {w_hi}], time [{t_lo}, {t_hi}]") - - param_configs = [ - ('x', lambda d: make_muon_params(x=TRUTH_X + d)), - ('y', lambda d: make_muon_params(y=TRUTH_Y + d)), - ('z', lambda d: make_muon_params(z=TRUTH_Z + d)), - ('theta', lambda d: make_muon_params(theta=TRUTH_THETA + d)), - ('phi', lambda d: make_muon_params(phi=TRUTH_PHI + d)), - ('energy', lambda d: make_muon_params(energy=TRUTH_ENERGY + d)), - ] - - for pname, make_fn in param_configs: - delta = PERTURBATIONS[pname] - unit = 'mm' if pname in ('x', 'y', 'z') else ('rad' if pname in ('theta', 'phi') else 'MeV') - - # Perturbed signal - e_p, pos_p, th_p, ph_p = make_fn(+delta) - sig_plus, _, _ = simulate_muon(e_p, pos_p, th_p, ph_p, forward, log_T, dedx) - jax.block_until_ready(sig_plus[2]) - perturbed_Y_adc = np.array(sig_plus[2]) # already in ADC - - diff_Y = perturbed_Y_adc - truth_Y_adc - - # Crop to signal region (with extra margin for perturbed signal) - p_nz = np.nonzero(np.abs(perturbed_Y_adc) > 0.01) - if len(p_nz[0]) > 0: - crop_w_lo = max(0, min(w_lo, p_nz[0].min() - 30)) - crop_w_hi = min(truth_Y_adc.shape[0], max(w_hi, p_nz[0].max() + 30)) - crop_t_lo = max(0, min(t_lo, p_nz[1].min() - 50)) - crop_t_hi = min(truth_Y_adc.shape[1], max(t_hi, p_nz[1].max() + 50)) - else: - crop_w_lo, crop_w_hi, crop_t_lo, crop_t_hi = w_lo, w_hi, t_lo, t_hi - - truth_crop = truth_Y_adc[crop_w_lo:crop_w_hi, crop_t_lo:crop_t_hi] - pert_crop = perturbed_Y_adc[crop_w_lo:crop_w_hi, crop_t_lo:crop_t_hi] - diff_crop = diff_Y[crop_w_lo:crop_w_hi, crop_t_lo:crop_t_hi] - - # Plot: truth | perturbed | difference - fig, axes = plt.subplots(1, 3, figsize=(18, 5)) - - extent = [crop_w_lo, crop_w_hi, crop_t_lo, crop_t_hi] - vmax_sig = max(np.abs(truth_crop).max(), np.abs(pert_crop).max()) - if vmax_sig < 1e-10: - vmax_sig = 1.0 - vmax_diff = np.abs(diff_crop).max() - if vmax_diff < 1e-10: - vmax_diff = 1.0 - - im0 = axes[0].imshow( - truth_crop.T, aspect='auto', origin='lower', extent=extent, - cmap='RdBu_r', vmin=-vmax_sig, vmax=vmax_sig, - interpolation='nearest', - ) - axes[0].set_title('Truth (East Y)') - axes[0].set_xlabel('Wire index') - axes[0].set_ylabel('Time bin') - fig.colorbar(im0, ax=axes[0], label='ADC', shrink=0.8) - - im1 = axes[1].imshow( - pert_crop.T, aspect='auto', origin='lower', extent=extent, - cmap='RdBu_r', vmin=-vmax_sig, vmax=vmax_sig, - interpolation='nearest', - ) - axes[1].set_title(f'Perturbed ({pname} + {delta} {unit})') - axes[1].set_xlabel('Wire index') - axes[1].set_ylabel('Time bin') - fig.colorbar(im1, ax=axes[1], label='ADC', shrink=0.8) - - im2 = axes[2].imshow( - diff_crop.T, aspect='auto', origin='lower', extent=extent, - cmap='RdBu_r', vmin=-vmax_diff, vmax=vmax_diff, - interpolation='nearest', - ) - axes[2].set_title(f'Difference (perturbed - truth)') - axes[2].set_xlabel('Wire index') - axes[2].set_ylabel('Time bin') - fig.colorbar(im2, ax=axes[2], label='ADC', shrink=0.8) - - fig.suptitle( - f'Parameter Variation: {pname} (delta = {delta} {unit})', - fontsize=14, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'muon_variation_{pname}.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}") - - print("\nDone!") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/muon_full_optimization.py b/closure/archive/muon_intermediate/muon_full_optimization.py deleted file mode 100644 index 628e322..0000000 --- a/closure/archive/muon_intermediate/muon_full_optimization.py +++ /dev/null @@ -1,383 +0,0 @@ -"""Full muon parameter optimization using both TPC sides. - -Optimizes all 8 free variables (x, y, z, sin_theta, cos_theta, sin_phi, -cos_phi, energy) using Sobolev H^-1 geomean loss over all 6 planes -(east U/V/Y + west U/V/Y). - -Parameters are normalized so all live in O(1) space for balanced gradients: - normalized = physical / SCALES -The optimizer works in normalized space; the loss denormalizes before -calling the simulation. - -Trig parameterization with unit circle projection after each Adam step. - -Run from project root: - python3 closure_analysis_muon/muon_full_optimization.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import optax -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean, make_sobolev_weight - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments_trig, - mask_outside_volume, - build_muon_forward, -) - - -# ============================================================================= -# Configuration -# ============================================================================= - -N_SEGMENTS = 4000 -STEP_SIZE_MM = 0.5 - -# Truth parameters — track starts in east side, crosses to west. -# phi=pi/6 gives positive x-component: sin(pi/4)*cos(pi/6) = 0.61 -# so the track travels from x=-200 toward positive x, crossing x=0. -TRUTH_X = -200.0 # mm, east side near center -TRUTH_Y = 0.0 # mm -TRUTH_Z = 100.0 # mm -TRUTH_THETA = np.pi / 4 # 45 deg polar -TRUTH_PHI = np.pi / 6 # 30 deg azimuthal -TRUTH_ENERGY = 500.0 # MeV - -# Trig truth values -TRUTH_SIN_THETA = np.sin(TRUTH_THETA) -TRUTH_COS_THETA = np.cos(TRUTH_THETA) -TRUTH_SIN_PHI = np.sin(TRUTH_PHI) -TRUTH_COS_PHI = np.cos(TRUTH_PHI) - -# Physical-space truth: [x, y, z, sin_th, cos_th, sin_ph, cos_ph, energy] -TRUTH_PHYS = np.array([ - TRUTH_X, TRUTH_Y, TRUTH_Z, - TRUTH_SIN_THETA, TRUTH_COS_THETA, - TRUTH_SIN_PHI, TRUTH_COS_PHI, - TRUTH_ENERGY, -]) - -# Normalization scales — makes all params O(1) in optimizer space. -SCALES = np.array([200.0, 200.0, 200.0, 1.0, 1.0, 1.0, 1.0, 500.0]) - -# Initial guess: perturb all parameters from truth -THETA_PERTURB = 0.5 # rad (~29 deg) -PHI_PERTURB = 0.5 # rad (~29 deg) -INIT_THETA = TRUTH_THETA + THETA_PERTURB -INIT_PHI = TRUTH_PHI + PHI_PERTURB - -INIT_PHYS = np.array([ - TRUTH_X + 100.0, - TRUTH_Y + 100.0, - TRUTH_Z - 100.0, - np.sin(INIT_THETA), - np.cos(INIT_THETA), - np.sin(INIT_PHI), - np.cos(INIT_PHI), - TRUTH_ENERGY + 100.0, -]) - -TRUTH_NORM = TRUTH_PHYS / SCALES -INIT_NORM = INIT_PHYS / SCALES - -# Optimization -N_STEPS = 300 -LR = 0.015 - -PARAM_NAMES = ['x', 'y', 'z', 'sin_th', 'cos_th', 'sin_ph', 'cos_ph', 'energy'] -PLANE_NAMES = ['east_U', 'east_V', 'east_Y', 'west_U', 'west_V', 'west_Y'] -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -# ============================================================================= -# Helpers -# ============================================================================= - -SCALES_JAX = jnp.array(SCALES, dtype=jnp.float32) - - -def to_physical(norm_params): - """Normalized -> physical space.""" - return norm_params * SCALES_JAX - - -def project_unit_circle(norm_params): - """Project sin/cos pairs onto unit circle.""" - st, ct = norm_params[3], norm_params[4] - norm_t = jnp.maximum(jnp.sqrt(st**2 + ct**2), 1e-8) - - sp, cp = norm_params[5], norm_params[6] - norm_p = jnp.maximum(jnp.sqrt(sp**2 + cp**2), 1e-8) - - return norm_params.at[3].set(st / norm_t).at[4].set(ct / norm_t) \ - .at[5].set(sp / norm_p).at[6].set(cp / norm_p) - - -def _make_sim_forward(forward, log_T, dedx): - """Build sim forward closure.""" - def sim_forward(phys): - pos, de = generate_muon_segments_trig( - phys[7], jnp.array([phys[0], phys[1], phys[2]]), - phys[3], phys[4], phys[5], phys[6], - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - de = mask_outside_volume(pos, de) - return forward(pos, de) - return sim_forward - - -# ============================================================================= -# Main -# ============================================================================= - -def main(): - print("=" * 70) - print("FULL MUON PARAMETER OPTIMIZATION (BOTH SIDES, SOBOLEV GEOMEAN)") - print("=" * 70) - print(f"Truth: x={TRUTH_X}, y={TRUTH_Y}, z={TRUTH_Z}") - print(f" theta={np.degrees(TRUTH_THETA):.1f} deg, " - f"phi={np.degrees(TRUTH_PHI):.1f} deg, E={TRUTH_ENERGY} MeV") - print(f"Init: x={INIT_PHYS[0]:.0f}, y={INIT_PHYS[1]:.0f}, " - f"z={INIT_PHYS[2]:.0f}") - print(f" theta={np.degrees(INIT_THETA):.1f} deg, " - f"phi={np.degrees(INIT_PHI):.1f} deg, E={INIT_PHYS[7]:.0f} MeV") - print(f"Scales: {SCALES}") - print(f"N_SEGMENTS={N_SEGMENTS}, N_STEPS={N_STEPS}, LR={LR}") - print(f"Loss: Sobolev H^-1 Geomean s=1.5") - print() - - # --- Load resources --- - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, - n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - sim_forward = _make_sim_forward(forward, log_T, dedx) - - # --- Generate truth signals --- - print("Compiling forward...", flush=True) - t0 = time.time() - truth_signals = jax.jit(sim_forward)( - jnp.array(TRUTH_PHYS, dtype=jnp.float32)) - for s in truth_signals: - jax.block_until_ready(s) - print(f" Compiled ({time.time()-t0:.1f}s)", flush=True) - - for i, name in enumerate(PLANE_NAMES): - sig = truth_signals[i] - print(f" {name}: shape={sig.shape}, " - f"max={float(jnp.max(jnp.abs(sig))):.4f}, " - f"sum_abs={float(jnp.sum(jnp.abs(sig))):.2f}") - - # --- Precompute Sobolev spectral weights (s=1.5) --- - print("\nPrecomputing Sobolev spectral weights (s=1.5)...", flush=True) - spec_weights_tuple = tuple( - make_sobolev_weight(*truth_signals[p].shape, s=1.5) for p in range(6) - ) - - # --- Loss function (takes NORMALIZED params) --- - def loss_fn(norm_params): - sigs = sim_forward(to_physical(norm_params)) - return sobolev_loss_geomean(sigs, truth_signals, spec_weights_tuple) - - # --- Compile loss + grad --- - print("Compiling loss + gradient...", flush=True) - t0 = time.time() - loss_and_grad = jax.jit(jax.value_and_grad(loss_fn)) - init_n = jnp.array(INIT_NORM, dtype=jnp.float32) - init_loss, init_grad = loss_and_grad(init_n) - jax.block_until_ready(init_grad) - print(f" Compiled ({time.time()-t0:.1f}s)", flush=True) - print(f" Initial loss: {float(init_loss):.6f}") - grad_strs = [f"{PARAM_NAMES[i]}={float(init_grad[i]):.4f}" - for i in range(8)] - print(f" Normalized grads: {', '.join(grad_strs)}") - - # --- Optimizer --- - optimizer = optax.adam(learning_rate=LR) - opt_state = optimizer.init(init_n) - - # --- Optimization loop --- - print(f"\nRunning {N_STEPS} optimization steps (LR={LR})...", flush=True) - params_n = init_n - - # History (store normalized, convert to physical at end) - loss_history = np.empty(N_STEPS) - norm_history = np.empty((N_STEPS, 8)) - norm_theta_history = np.empty(N_STEPS) - norm_phi_history = np.empty(N_STEPS) - - t_start = time.time() - for step in range(N_STEPS): - loss, grad = loss_and_grad(params_n) - - loss_history[step] = float(loss) - norm_history[step] = np.array(params_n) - - updates, opt_state = optimizer.update(grad, opt_state, params_n) - params_n = optax.apply_updates(params_n, updates) - - norm_theta_history[step] = float( - jnp.sqrt(params_n[3]**2 + params_n[4]**2)) - norm_phi_history[step] = float( - jnp.sqrt(params_n[5]**2 + params_n[6]**2)) - - params_n = project_unit_circle(params_n) - - if step % 20 == 0 or step == N_STEPS - 1: - p = np.array(to_physical(params_n)) - eff_theta = float(jnp.arctan2(params_n[3], params_n[4])) - eff_phi = float(jnp.arctan2(params_n[5], params_n[6])) - elapsed = time.time() - t_start - print(f" Step {step:3d}: loss={float(loss):.6f}, " - f"x={p[0]:7.1f}, y={p[1]:7.1f}, z={p[2]:7.1f}, " - f"th={np.degrees(eff_theta):5.1f} deg, " - f"ph={np.degrees(eff_phi):5.1f} deg, " - f"E={p[7]:6.1f} MeV " - f"({elapsed:.1f}s)", flush=True) - - total_time = time.time() - t_start - print(f"\nOptimization complete in {total_time:.1f}s " - f"({total_time/N_STEPS:.2f}s/step)") - - # --- Final results --- - param_history = norm_history * SCALES[np.newaxis, :] - final_phys = param_history[-1] - eff_theta_final = np.arctan2(final_phys[3], final_phys[4]) - eff_phi_final = np.arctan2(final_phys[5], final_phys[6]) - - print(f"\n{'Parameter':<12} {'Truth':>10} {'Initial':>10} " - f"{'Final':>10} {'Delta':>10}") - print("-" * 55) - print(f"{'x (mm)':<12} {TRUTH_X:>10.1f} {INIT_PHYS[0]:>10.1f} " - f"{final_phys[0]:>10.1f} {final_phys[0]-TRUTH_X:>10.2f}") - print(f"{'y (mm)':<12} {TRUTH_Y:>10.1f} {INIT_PHYS[1]:>10.1f} " - f"{final_phys[1]:>10.1f} {final_phys[1]-TRUTH_Y:>10.2f}") - print(f"{'z (mm)':<12} {TRUTH_Z:>10.1f} {INIT_PHYS[2]:>10.1f} " - f"{final_phys[2]:>10.1f} {final_phys[2]-TRUTH_Z:>10.2f}") - print(f"{'theta (deg)':<12} {np.degrees(TRUTH_THETA):>10.1f} " - f"{np.degrees(INIT_THETA):>10.1f} " - f"{np.degrees(eff_theta_final):>10.1f} " - f"{np.degrees(eff_theta_final-TRUTH_THETA):>10.2f}") - print(f"{'phi (deg)':<12} {np.degrees(TRUTH_PHI):>10.1f} " - f"{np.degrees(INIT_PHI):>10.1f} " - f"{np.degrees(eff_phi_final):>10.1f} " - f"{np.degrees(eff_phi_final-TRUTH_PHI):>10.2f}") - print(f"{'E (MeV)':<12} {TRUTH_ENERGY:>10.1f} {INIT_PHYS[7]:>10.1f} " - f"{final_phys[7]:>10.1f} " - f"{final_phys[7]-TRUTH_ENERGY:>10.2f}") - - # --- Plot --- - _plot_results(loss_history, param_history, - norm_theta_history, norm_phi_history) - print("\nDone!") - - -# ============================================================================= -# Plotting -# ============================================================================= - -def _plot_convergence(ax, steps, values, truth, init, ylabel, title): - """Plot a single parameter convergence subplot.""" - ax.plot(steps, values, 'b-', lw=1.5, label='optimized') - ax.axhline(truth, color='green', ls='--', lw=2, label=f'truth={truth:.4g}') - ax.axhline(init, color='red', ls=':', lw=1.5, label=f'init={init:.4g}') - ax.set_xlabel('Step') - ax.set_ylabel(ylabel) - ax.set_title(title) - ax.legend(fontsize=8) - ax.grid(True, alpha=0.3) - - -def _plot_results(loss_history, param_history, - norm_theta_history, norm_phi_history): - """Generate 3x3 summary plot.""" - steps = np.arange(len(loss_history)) - eff_theta = np.arctan2(param_history[:, 3], param_history[:, 4]) - eff_phi = np.arctan2(param_history[:, 5], param_history[:, 6]) - - fig, axes = plt.subplots(3, 3, figsize=(16, 14)) - - # Loss convergence - ax = axes[0, 0] - ax.semilogy(steps, loss_history, 'b-', lw=1.5) - ax.set_xlabel('Step') - ax.set_ylabel('Sobolev Geomean Loss (log)') - ax.set_title('Loss Convergence') - ax.grid(True, alpha=0.3) - - # Parameter convergences - specs = [ - (axes[0, 1], param_history[:, 0], TRUTH_X, INIT_PHYS[0], - 'x (mm)', 'x Convergence'), - (axes[0, 2], param_history[:, 1], TRUTH_Y, INIT_PHYS[1], - 'y (mm)', 'y Convergence'), - (axes[1, 0], param_history[:, 2], TRUTH_Z, INIT_PHYS[2], - 'z (mm)', 'z Convergence'), - (axes[1, 1], np.degrees(eff_theta), np.degrees(TRUTH_THETA), - np.degrees(INIT_THETA), 'theta (deg)', 'theta Convergence'), - (axes[1, 2], np.degrees(eff_phi), np.degrees(TRUTH_PHI), - np.degrees(INIT_PHI), 'phi (deg)', 'phi Convergence'), - (axes[2, 0], param_history[:, 7], TRUTH_ENERGY, INIT_PHYS[7], - 'Energy (MeV)', 'Energy Convergence'), - ] - for ax, values, truth, init, ylabel, title in specs: - _plot_convergence(ax, steps, values, truth, init, ylabel, title) - - # theta-phi trajectory - ax = axes[2, 1] - ax.plot(np.degrees(eff_phi), np.degrees(eff_theta), 'b-', lw=1, alpha=0.7) - ax.plot(np.degrees(eff_phi[0]), np.degrees(eff_theta[0]), - 'ro', ms=10, label='start') - ax.plot(np.degrees(eff_phi[-1]), np.degrees(eff_theta[-1]), - 'bs', ms=10, label='final') - ax.plot(np.degrees(TRUTH_PHI), np.degrees(TRUTH_THETA), - 'g*', ms=15, label='truth') - ax.set_xlabel('phi (deg)') - ax.set_ylabel('theta (deg)') - ax.set_title('theta-phi Trajectory') - ax.legend(fontsize=8) - ax.grid(True, alpha=0.3) - - # sin/cos norms - ax = axes[2, 2] - ax.plot(steps, norm_theta_history, 'b-', lw=1.5, - label='||(sin_th, cos_th)||') - ax.plot(steps, norm_phi_history, 'r-', lw=1.5, - label='||(sin_ph, cos_ph)||') - ax.axhline(1.0, color='green', ls='--', lw=2, label='target=1.0') - ax.set_xlabel('Step') - ax.set_ylabel('Norm (pre-projection)') - ax.set_title('sin/cos Pair Norms') - ax.legend(fontsize=8) - ax.grid(True, alpha=0.3) - - fig.suptitle( - f'Full Muon Optimization: 6 planes, Sobolev Geomean s=1.5, ' - f'{N_STEPS} steps, Adam LR={LR}\n' - f'Truth: x={TRUTH_X}, y={TRUTH_Y}, z={TRUTH_Z}, ' - f'theta={np.degrees(TRUTH_THETA):.1f} deg, ' - f'phi={np.degrees(TRUTH_PHI):.1f} deg, E={TRUTH_ENERGY} MeV', - fontsize=12, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'optimization_full_muon.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/muon_gradient_surfaces.py b/closure/archive/muon_intermediate/muon_gradient_surfaces.py deleted file mode 100644 index 82da36d..0000000 --- a/closure/archive/muon_intermediate/muon_gradient_surfaces.py +++ /dev/null @@ -1,387 +0,0 @@ -""" -Loss and gradient surface plots for differentiable muon simulation. - -For each of 6 muon parameters (x, y, z, theta, phi, energy), sweeps the -parameter while holding the others fixed at truth and plots: - - Loss landscape - - Gradient comparison (autodiff vs finite-difference) - -Supports three loss types: MSE, SW (Sliced Wasserstein), and Blur MSE. - -Run from project root: - python3 closure_analysis_muon/muon_gradient_surfaces.py --loss mse - python3 closure_analysis_muon/muon_gradient_surfaces.py --loss sw - python3 closure_analysis_muon/muon_gradient_surfaces.py --loss blur - python3 closure_analysis_muon/muon_gradient_surfaces.py --loss all -""" - -import sys, os, argparse -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit -from tools.losses import ( - blur_mse_loss, make_spectral_weight, DEFAULT_BLUR_SIGMAS, - sobolev_loss, sobolev_loss_geomean, sobolev_loss_geomean_log1p, - make_sobolev_weight, -) - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments, - build_muon_forward, -) - -# ============================================================================= -# Configuration -# ============================================================================= - -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 - -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 2 -TRUTH_ENERGY = 200.0 - -PLANES = [0, 1, 2] -K = 10000 -N_PROJ = 200 -N_SWEEP = 120 - -FD_EPS_POS = 0.5 -FD_EPS_ANGLE = 0.01 -FD_EPS_ENERGY = 0.5 - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -PARAM_ORDER = ['x', 'y', 'z', 'theta', 'phi', 'energy'] -PARAM_IDX = {n: i for i, n in enumerate(PARAM_ORDER)} - -SWEEP_CONFIGS = { - 'energy': {'range': (100.0, 280.0), 'truth': TRUTH_ENERGY, 'unit': 'MeV', 'eps': FD_EPS_ENERGY}, - 'x': {'range': (-700, -300), 'truth': TRUTH_X, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'y': {'range': (-400, 400), 'truth': TRUTH_Y, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'z': {'range': (-200, 400), 'truth': TRUTH_Z, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'theta': {'range': (0.3, 1.2), 'truth': TRUTH_THETA, 'unit': 'rad', 'eps': FD_EPS_ANGLE}, - 'phi': {'range': (0.8, 2.4), 'truth': TRUTH_PHI, 'unit': 'rad', 'eps': FD_EPS_ANGLE}, -} - - -# ============================================================================= -# Main -# ============================================================================= - -def main(loss_types=None): - if loss_types is None: - loss_types = ['mse', 'sw', 'blur'] - - print("=" * 60, flush=True) - print("MUON GRADIENT SURFACE ANALYSIS", flush=True) - print(f"Loss types: {', '.join(loss_types)}", flush=True) - print("=" * 60, flush=True) - - # --- Setup --- - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - # --- Truth signals --- - truth_args = ( - jnp.float32(TRUTH_X), jnp.float32(TRUTH_Y), jnp.float32(TRUTH_Z), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), jnp.float32(TRUTH_ENERGY), - ) - - def sim_forward(x, y, z, theta, phi, energy): - pos, de = generate_muon_segments( - energy, jnp.array([x, y, z]), theta, phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - return forward(pos, de) - - print("Compiling sim_forward...", flush=True) - t0 = time.time() - sim_jit = jax.jit(sim_forward) - truth_signals = sim_jit(*truth_args) - for s in truth_signals: - jax.block_until_ready(s) - print(f" compiled ({time.time()-t0:.1f}s)", flush=True) - - ot_key = jax.random.PRNGKey(42) - target_sigs = {p: truth_signals[p] for p in PLANES} - - ALL = (0, 1, 2, 3, 4, 5) - - # --- MSE --- - if 'mse' in loss_types: - def mse_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - loss = 0.0 - for p in PLANES: - loss = loss + jnp.mean((sigs[p] - target_sigs[p]) ** 2) - return loss - - print("\nCompiling MSE loss...", flush=True) - t0 = time.time() - mse_jit = jax.jit(mse_loss) - _ = mse_jit(*truth_args) - print(f" MSE fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - mse_vg = jax.jit(jax.value_and_grad(mse_loss, argnums=ALL)) - _ = mse_vg(*truth_args) - print(f" MSE fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('MSE', mse_jit, mse_vg, truth_args) - - # --- SW --- - if 'sw' in loss_types: - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(truth_signals[p], K) - target_clouds[p] = (pts, w) - - def sw_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + sliced_wasserstein_loss_jit( - pts, w, target_clouds[p][0], target_clouds[p][1], - ot_key, n_projections=N_PROJ, - ) - return loss - - print("\nCompiling SW loss...", flush=True) - t0 = time.time() - sw_jit = jax.jit(sw_loss) - _ = sw_jit(*truth_args) - print(f" SW fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - sw_vg = jax.jit(jax.value_and_grad(sw_loss, argnums=ALL)) - _ = sw_vg(*truth_args) - print(f" SW fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('SW', sw_jit, sw_vg, truth_args) - - # --- Blur MSE (spectral) --- - if 'blur' in loss_types: - planes_tuple = tuple(PLANES) - - # Precompute spectral weights for each plane shape - print("\nPrecomputing spectral weights...", flush=True) - spec_weights = {} - for p in PLANES: - H, W = truth_signals[p].shape - spec_weights[p] = make_spectral_weight(H, W, DEFAULT_BLUR_SIGMAS) - # Build full 6-element tuple (only PLANES entries used) - sw_tuple = tuple( - spec_weights[i] if i in spec_weights - else jnp.zeros((1, 1)) - for i in range(6) - ) - - def blur_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - return blur_mse_loss(sigs, truth_signals, sw_tuple, planes=planes_tuple) - - print("Compiling Blur MSE loss...", flush=True) - t0 = time.time() - blur_jit = jax.jit(blur_loss) - _ = blur_jit(*truth_args) - print(f" Blur fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - blur_vg = jax.jit(jax.value_and_grad(blur_loss, argnums=ALL)) - _ = blur_vg(*truth_args) - print(f" Blur fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('Blur', blur_jit, blur_vg, truth_args) - - # --- Sobolev: shared spectral weights for sum and geomean (s=2.0) --- - if 'sobolev_sum' in loss_types or 'sobolev_geomean' in loss_types: - planes_tuple = tuple(PLANES) - - print("\nPrecomputing Sobolev spectral weights (s=2.0)...", flush=True) - sob_weights = {} - for p in PLANES: - H, W = truth_signals[p].shape - sob_weights[p] = make_sobolev_weight(H, W, s=2.0) - sob_tuple = tuple( - sob_weights[i] if i in sob_weights - else jnp.zeros((1, 1)) - for i in range(6) - ) - - # --- Sobolev Sum --- - if 'sobolev_sum' in loss_types: - def sob_sum_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - return sobolev_loss(sigs, truth_signals, sob_tuple, planes=planes_tuple) - - print("\nCompiling Sobolev Sum loss...", flush=True) - t0 = time.time() - sob_sum_jit = jax.jit(sob_sum_loss) - _ = sob_sum_jit(*truth_args) - print(f" Sobolev Sum fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - sob_sum_vg = jax.jit(jax.value_and_grad(sob_sum_loss, argnums=ALL)) - _ = sob_sum_vg(*truth_args) - print(f" Sobolev Sum fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('Sobolev_Sum', sob_sum_jit, sob_sum_vg, truth_args) - - # --- Sobolev Geomean --- - if 'sobolev_geomean' in loss_types: - def sob_geo_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - return sobolev_loss_geomean(sigs, truth_signals, sob_tuple, planes=planes_tuple) - - print("\nCompiling Sobolev Geomean loss...", flush=True) - t0 = time.time() - sob_geo_jit = jax.jit(sob_geo_loss) - _ = sob_geo_jit(*truth_args) - print(f" Sobolev Geomean fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - sob_geo_vg = jax.jit(jax.value_and_grad(sob_geo_loss, argnums=ALL)) - _ = sob_geo_vg(*truth_args) - print(f" Sobolev Geomean fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('Sobolev_Geomean', sob_geo_jit, sob_geo_vg, truth_args) - - # --- Sobolev Geomean Log1p (s=1.5, matching optimization settings) --- - if 'sobolev_geomean_log1p' in loss_types: - planes_tuple = tuple(PLANES) - - print("\nPrecomputing Sobolev spectral weights (s=1.5)...", flush=True) - sob15_weights = {} - for p in PLANES: - H, W = truth_signals[p].shape - sob15_weights[p] = make_sobolev_weight(H, W, s=1.5) - sob15_tuple = tuple( - sob15_weights[i] if i in sob15_weights - else jnp.zeros((1, 1)) - for i in range(6) - ) - - def sob_log1p_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - return sobolev_loss_geomean_log1p(sigs, truth_signals, sob15_tuple, - planes=planes_tuple) - - print("Compiling Sobolev Geomean Log1p loss...", flush=True) - t0 = time.time() - sob_log1p_jit = jax.jit(sob_log1p_loss) - _ = sob_log1p_jit(*truth_args) - print(f" Sobolev Geomean Log1p fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - sob_log1p_vg = jax.jit(jax.value_and_grad(sob_log1p_loss, argnums=ALL)) - _ = sob_log1p_vg(*truth_args) - print(f" Sobolev Geomean Log1p fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('Sobolev_Geomean_Log1p', sob_log1p_jit, sob_log1p_vg, truth_args) - - print("\nDone!", flush=True) - - -def _run_sweeps(loss_name, loss_jit, loss_vg, truth_args): - """Run parameter sweeps and save plots for one loss type.""" - - prefix = { - 'MSE': 'mse', 'SW': 'sw', 'Blur': 'blur', - 'Sobolev_Sum': 'sobolev_sum_s2.0_smooth0.2', - 'Sobolev_Geomean': 'sobolev_geomean_s2.0_smooth0.2', - 'Sobolev_Geomean_Log1p': 'sobolev_geomean_log1p_s1.5_smooth0.2', - }[loss_name] - - for pname, cfg in SWEEP_CONFIGS.items(): - lo, hi = cfg['range'] - truth_val = cfg['truth'] - unit = cfg['unit'] - eps = cfg['eps'] - pidx = PARAM_IDX[pname] - - x_vals = np.linspace(lo, hi, N_SWEEP) - print(f"\n {loss_name} — {pname} [{lo}, {hi}] {unit}", flush=True) - - def _args(val): - a = list(truth_args) - a[pidx] = jnp.float32(val) - return tuple(a) - - # Loss + autodiff gradient - t0 = time.time() - losses = np.empty(N_SWEEP) - ad_grads = np.empty(N_SWEEP) - for i, v in enumerate(x_vals): - loss, grads = loss_vg(*_args(v)) - losses[i] = float(loss) - ad_grads[i] = float(grads[pidx]) - - # Finite-diff gradient - fd_grads = np.array([ - (float(loss_jit(*_args(v + eps))) - - float(loss_jit(*_args(v - eps)))) / (2 * eps) - for v in x_vals - ]) - print(f" done ({time.time()-t0:.1f}s)", flush=True) - - # --- Plot --- - truth_label = f'Truth {pname}={truth_val:.2f}' - fig, axes = plt.subplots(1, 2, figsize=(12, 5)) - - axes[0].plot(x_vals, losses, 'b-', lw=1.5) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, label=truth_label) - axes[0].set_xlabel(f'{pname} ({unit})') - axes[0].set_ylabel(f'{loss_name} Loss') - axes[0].set_title('Loss Landscape') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - - axes[1].plot(x_vals, ad_grads, 'r-', lw=1.5, label='Autodiff') - axes[1].plot(x_vals, fd_grads, 'b--', lw=1.5, alpha=0.7, label=f'FD (eps={eps})') - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, label=truth_label) - axes[1].set_xlabel(f'{pname} ({unit})') - axes[1].set_ylabel(f'd{loss_name}/d{pname}') - axes[1].set_title('Gradient (Autodiff vs FD)') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - - fig.suptitle( - f'{loss_name} — varying {pname} (muon, {N_SEGMENTS} seg, summed U+V+Y)', - fontsize=14, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'{prefix}_surface_{pname}.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f" Saved {fname}", flush=True) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='Muon gradient surface analysis') - parser.add_argument( - '--loss', type=str, default='all', - choices=['mse', 'sw', 'blur', 'sobolev_sum', 'sobolev_geomean', - 'sobolev_geomean_log1p', 'all'], - help='Which loss to run (default: all)', - ) - args = parser.parse_args() - if args.loss == 'all': - main(['mse', 'sw', 'blur', 'sobolev_sum', 'sobolev_geomean', - 'sobolev_geomean_log1p']) - else: - main([args.loss]) diff --git a/closure/archive/muon_intermediate/muon_gradient_surfaces_perplane.py b/closure/archive/muon_intermediate/muon_gradient_surfaces_perplane.py deleted file mode 100644 index c7ce1e2..0000000 --- a/closure/archive/muon_intermediate/muon_gradient_surfaces_perplane.py +++ /dev/null @@ -1,220 +0,0 @@ -"""Per-plane Sobolev gradient surfaces. - -Shows loss and gradient for each plane (U, V, Y) individually plus the sum. -Sim is compiled once; per-plane losses are thin wrappers. - -Run from project root: - python3 closure_analysis_muon/muon_gradient_surfaces_perplane.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss, make_sobolev_weight - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments, - build_muon_forward, -) - -# ============================================================================= -# Configuration -# ============================================================================= - -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 - -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 2 -TRUTH_ENERGY = 200.0 - -PLANES = [0, 1, 2] -PLANE_NAMES = {0: 'U', 1: 'V', 2: 'Y'} -PLANE_COLORS = {0: 'C0', 1: 'C1', 2: 'C2'} -N_SWEEP = 40 -FD_EPS_POS = 0.5 -FD_EPS_ANGLE = 0.01 -FD_EPS_ENERGY = 0.5 - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -PARAM_ORDER = ['x', 'y', 'z', 'theta', 'phi', 'energy'] -PARAM_IDX = {n: i for i, n in enumerate(PARAM_ORDER)} - -SWEEP_CONFIGS = { - 'x': {'range': (-700, -300), 'truth': TRUTH_X, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'y': {'range': (-400, 400), 'truth': TRUTH_Y, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'z': {'range': (-200, 400), 'truth': TRUTH_Z, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'theta': {'range': (0.3, 1.2), 'truth': TRUTH_THETA, 'unit': 'rad', 'eps': FD_EPS_ANGLE}, - 'phi': {'range': (0.8, 2.4), 'truth': TRUTH_PHI, 'unit': 'rad', 'eps': FD_EPS_ANGLE}, - 'energy': {'range': (100.0, 280.0), 'truth': TRUTH_ENERGY, 'unit': 'MeV', 'eps': FD_EPS_ENERGY}, -} - -ALL = (0, 1, 2, 3, 4, 5) - - -def main(): - print("=" * 60, flush=True) - print("PER-PLANE SOBOLEV GRADIENT SURFACES", flush=True) - print("=" * 60, flush=True) - - # --- Setup --- - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - # --- Truth signals --- - truth_args = ( - jnp.float32(TRUTH_X), jnp.float32(TRUTH_Y), jnp.float32(TRUTH_Z), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), jnp.float32(TRUTH_ENERGY), - ) - - def sim_forward(x, y, z, theta, phi, energy): - pos, de = generate_muon_segments( - energy, jnp.array([x, y, z]), theta, phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - return forward(pos, de) - - print("Compiling sim_forward...", flush=True) - t0 = time.time() - sim_jit = jax.jit(sim_forward) - truth_signals = sim_jit(*truth_args) - for s in truth_signals: - jax.block_until_ready(s) - print(f" sim compiled ({time.time()-t0:.1f}s)", flush=True) - - # --- Sobolev weights --- - print("\nPrecomputing Sobolev weights...", flush=True) - sob_weights = {} - for p in PLANES: - H, W = truth_signals[p].shape - sob_weights[p] = make_sobolev_weight(H, W) - sob_tuple = tuple( - sob_weights[i] if i in sob_weights else jnp.zeros((1, 1)) - for i in range(6) - ) - - # --- Per-plane loss functions (thin wrappers over same sim) --- - def make_loss(plane_tuple): - def loss_fn(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - return sobolev_loss(sigs, truth_signals, sob_tuple, planes=plane_tuple) - return loss_fn - - # Compile per-plane and sum - print("Compiling per-plane losses...", flush=True) - loss_fns = {} # name -> (jit_loss, jit_vg) - for p in PLANES: - name = PLANE_NAMES[p] - fn = make_loss((p,)) - t0 = time.time() - fn_jit = jax.jit(fn) - vg_jit = jax.jit(jax.value_and_grad(fn, argnums=ALL)) - _ = fn_jit(*truth_args) - _ = vg_jit(*truth_args) - loss_fns[name] = (fn_jit, vg_jit) - print(f" {name} compiled ({time.time()-t0:.1f}s)", flush=True) - - # Sum - fn_sum = make_loss(tuple(PLANES)) - t0 = time.time() - fn_sum_jit = jax.jit(fn_sum) - vg_sum_jit = jax.jit(jax.value_and_grad(fn_sum, argnums=ALL)) - _ = fn_sum_jit(*truth_args) - _ = vg_sum_jit(*truth_args) - loss_fns['Sum'] = (fn_sum_jit, vg_sum_jit) - print(f" Sum compiled ({time.time()-t0:.1f}s)", flush=True) - - # --- Sweeps --- - ordered = ['U', 'V', 'Y', 'Sum'] - colors = {'U': 'C0', 'V': 'C1', 'Y': 'C2', 'Sum': 'k'} - lws = {'U': 1.5, 'V': 1.5, 'Y': 1.5, 'Sum': 2.5} - - for pname, cfg in SWEEP_CONFIGS.items(): - lo, hi = cfg['range'] - truth_val = cfg['truth'] - unit = cfg['unit'] - eps = cfg['eps'] - pidx = PARAM_IDX[pname] - - x_vals = np.linspace(lo, hi, N_SWEEP) - print(f"\n {pname} [{lo}, {hi}] {unit}", flush=True) - - def _args(val): - a = list(truth_args) - a[pidx] = jnp.float32(val) - return tuple(a) - - # Collect per-plane data - t0 = time.time() - data = {} - for name in ordered: - fn_jit, vg_jit = loss_fns[name] - losses = np.empty(N_SWEEP) - ad_grads = np.empty(N_SWEEP) - for i, v in enumerate(x_vals): - loss, grads = vg_jit(*_args(v)) - losses[i] = float(loss) - ad_grads[i] = float(grads[pidx]) - data[name] = (losses, ad_grads) - print(f" done ({time.time()-t0:.1f}s)", flush=True) - - # --- Plot: 2 panels --- - fig, axes = plt.subplots(1, 2, figsize=(14, 5.5)) - - # Left: loss per plane - for name in ordered: - losses, _ = data[name] - axes[0].plot(x_vals, losses, color=colors[name], lw=lws[name], - ls='-' if name != 'Sum' else '-', - alpha=0.8 if name != 'Sum' else 1.0, - label=name) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth={truth_val:.2f}') - axes[0].set_xlabel(f'{pname} ({unit})') - axes[0].set_ylabel('Sobolev Loss') - axes[0].set_title('Loss per Plane') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - - # Right: gradient per plane - for name in ordered: - _, ad_grads = data[name] - axes[1].plot(x_vals, ad_grads, color=colors[name], lw=lws[name], - alpha=0.8 if name != 'Sum' else 1.0, - label=name) - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth={truth_val:.2f}') - axes[1].set_xlabel(f'{pname} ({unit})') - axes[1].set_ylabel(f'dLoss/d{pname}') - axes[1].set_title('Gradient per Plane') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - - fig.suptitle( - f'Sobolev per-plane — varying {pname} (U, V, Y + Sum)', - fontsize=14, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'sobolev_perplane_{pname}.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f" Saved {fname}", flush=True) - - print("\nDone!", flush=True) - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/muon_gradient_surfaces_trig.py b/closure/archive/muon_intermediate/muon_gradient_surfaces_trig.py deleted file mode 100644 index 288ba82..0000000 --- a/closure/archive/muon_intermediate/muon_gradient_surfaces_trig.py +++ /dev/null @@ -1,409 +0,0 @@ -""" -Loss and gradient surfaces using trig parameterization (sin/cos). - -Instead of optimizing (theta, phi), use (sin_theta, cos_theta, sin_phi, cos_phi) -as free variables. The direction vector is built from these directly and -normalized to unit length: - - dir_unnorm = [sin_theta * cos_phi, sin_theta * sin_phi, cos_theta] - dir = dir_unnorm / |dir_unnorm| - -This avoids the angle parameterization and may smooth out features -like the V-wire parallel singularity at theta=0.524. - -Each trig component is swept independently while the others stay at truth. - -Supports three loss types: MSE, SW (Sliced Wasserstein), and Pyramid Blur. - -Run from project root: - python3 closure_analysis_muon/muon_gradient_surfaces_trig.py --loss mse - python3 closure_analysis_muon/muon_gradient_surfaces_trig.py --loss sw - python3 closure_analysis_muon/muon_gradient_surfaces_trig.py --loss pyramid - python3 closure_analysis_muon/muon_gradient_surfaces_trig.py --loss all -""" - -import sys, os, argparse -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.pointcloud import signal_to_pointcloud -from ott_test.ot_losses import sliced_wasserstein_loss_jit -from tools.losses import pyramid_blur_loss, DEFAULT_PYRAMID_SPEC -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments_trig, - mask_outside_volume, - build_muon_forward, -) - -# ============================================================================= -# Configuration -# ============================================================================= - -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 - -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 2 -TRUTH_ENERGY = 200.0 - -# Trig truth values -TRUTH_SIN_THETA = np.sin(TRUTH_THETA) # 0.7071 -TRUTH_COS_THETA = np.cos(TRUTH_THETA) # 0.7071 -TRUTH_SIN_PHI = np.sin(TRUTH_PHI) # 1.0 -TRUTH_COS_PHI = np.cos(TRUTH_PHI) # 0.0 - -PLANES = [0, 1, 2] -K = 10000 -N_PROJ = 200 -N_SWEEP = 40 - -FD_EPS_TRIG = 0.01 -FD_EPS_POS = 0.5 -FD_EPS_ENERGY = 0.5 - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -# 8-parameter order: x, y, z, sin_theta, cos_theta, sin_phi, cos_phi, energy -PARAM_ORDER = ['x', 'y', 'z', 'sin_theta', 'cos_theta', 'sin_phi', 'cos_phi', 'energy'] -PARAM_IDX = {n: i for i, n in enumerate(PARAM_ORDER)} - -SWEEP_CONFIGS = { - 'sin_theta': {'range': (0.2, 1.0), 'truth': TRUTH_SIN_THETA, 'unit': '', 'eps': FD_EPS_TRIG}, - 'cos_theta': {'range': (0.2, 1.0), 'truth': TRUTH_COS_THETA, 'unit': '', 'eps': FD_EPS_TRIG}, - 'sin_phi': {'range': (0.3, 1.0), 'truth': TRUTH_SIN_PHI, 'unit': '', 'eps': FD_EPS_TRIG}, - 'cos_phi': {'range': (-0.7, 0.7), 'truth': TRUTH_COS_PHI, 'unit': '', 'eps': FD_EPS_TRIG}, -} - - -# ============================================================================= -# Main -# ============================================================================= - -def main(loss_types=None): - if loss_types is None: - loss_types = ['mse', 'sw', 'pyramid'] - - print("=" * 60, flush=True) - print("TRIG PARAMETERIZATION GRADIENT SURFACES", flush=True) - print(f"Loss types: {', '.join(loss_types)}", flush=True) - print("=" * 60, flush=True) - print(f"Truth trig: sin_θ={TRUTH_SIN_THETA:.4f}, cos_θ={TRUTH_COS_THETA:.4f}, " - f"sin_φ={TRUTH_SIN_PHI:.4f}, cos_φ={TRUTH_COS_PHI:.4f}", flush=True) - - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - # Truth args: (x, y, z, sin_theta, cos_theta, sin_phi, cos_phi, energy) - truth_args = ( - jnp.float32(TRUTH_X), jnp.float32(TRUTH_Y), jnp.float32(TRUTH_Z), - jnp.float32(TRUTH_SIN_THETA), jnp.float32(TRUTH_COS_THETA), - jnp.float32(TRUTH_SIN_PHI), jnp.float32(TRUTH_COS_PHI), - jnp.float32(TRUTH_ENERGY), - ) - - def sim_forward(x, y, z, sin_theta, cos_theta, sin_phi, cos_phi, energy): - pos, de = generate_muon_segments_trig( - energy, jnp.array([x, y, z]), - sin_theta, cos_theta, sin_phi, cos_phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - de = mask_outside_volume(pos, de) - return forward(pos, de) - - # Compile sim - print("Compiling sim_forward...", flush=True) - t0 = time.time() - sim_jit = jax.jit(sim_forward) - truth_signals = sim_jit(*truth_args) - for s in truth_signals: - jax.block_until_ready(s) - print(f" sim compiled ({time.time()-t0:.1f}s)", flush=True) - - ot_key = jax.random.PRNGKey(42) - target_sigs = {p: truth_signals[p] for p in PLANES} - - ALL = tuple(range(8)) - - # Track compiled losses for comparison plots - compiled = {} - - # --- MSE --- - if 'mse' in loss_types: - def mse_loss(x, y, z, sin_theta, cos_theta, sin_phi, cos_phi, energy): - sigs = sim_forward(x, y, z, sin_theta, cos_theta, sin_phi, cos_phi, energy) - loss = 0.0 - for p in PLANES: - loss = loss + jnp.mean((sigs[p] - target_sigs[p]) ** 2) - return loss - - print("\nCompiling MSE loss...", flush=True) - t0 = time.time() - mse_jit = jax.jit(mse_loss) - _ = mse_jit(*truth_args) - print(f" MSE fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - mse_vg = jax.jit(jax.value_and_grad(mse_loss, argnums=ALL)) - _ = mse_vg(*truth_args) - print(f" MSE fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('MSE', mse_jit, mse_vg, truth_args) - compiled['mse'] = (mse_jit, mse_vg) - - # --- SW --- - if 'sw' in loss_types: - target_clouds = {} - for p in PLANES: - pts, w = signal_to_pointcloud(truth_signals[p], K) - target_clouds[p] = (pts, w) - - def sw_loss(x, y, z, sin_theta, cos_theta, sin_phi, cos_phi, energy): - sigs = sim_forward(x, y, z, sin_theta, cos_theta, sin_phi, cos_phi, energy) - loss = 0.0 - for p in PLANES: - pts, w = signal_to_pointcloud(sigs[p], K) - loss = loss + sliced_wasserstein_loss_jit( - pts, w, target_clouds[p][0], target_clouds[p][1], - ot_key, n_projections=N_PROJ, - ) - return loss - - print("\nCompiling SW loss...", flush=True) - t0 = time.time() - sw_jit = jax.jit(sw_loss) - _ = sw_jit(*truth_args) - print(f" SW fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - sw_vg = jax.jit(jax.value_and_grad(sw_loss, argnums=ALL)) - _ = sw_vg(*truth_args) - print(f" SW fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('SW', sw_jit, sw_vg, truth_args) - compiled['sw'] = (sw_jit, sw_vg) - - # --- Pyramid Blur --- - if 'pyramid' in loss_types: - planes_tuple = tuple(PLANES) - - def pyramid_loss(x, y, z, sin_theta, cos_theta, sin_phi, cos_phi, energy): - sigs = sim_forward(x, y, z, sin_theta, cos_theta, sin_phi, cos_phi, energy) - return pyramid_blur_loss( - sigs, truth_signals, DEFAULT_PYRAMID_SPEC, - planes=planes_tuple, - ) - - print("\nCompiling Pyramid Blur loss...", flush=True) - t0 = time.time() - pyr_jit = jax.jit(pyramid_loss) - _ = pyr_jit(*truth_args) - print(f" Pyramid fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - pyr_vg = jax.jit(jax.value_and_grad(pyramid_loss, argnums=ALL)) - _ = pyr_vg(*truth_args) - print(f" Pyramid fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('Pyramid', pyr_jit, pyr_vg, truth_args) - - # --- Side-by-side comparison (needs both sw and mse) --- - if 'sw' in compiled and 'mse' in compiled: - print("\nGenerating comparison plots...", flush=True) - sw_jit, sw_vg = compiled['sw'] - mse_jit, mse_vg = compiled['mse'] - _comparison_plots(sw_jit, sw_vg, truth_args, mse_jit, mse_vg) - - print("\nDone!", flush=True) - - -def _run_sweeps(loss_name, loss_jit, loss_vg, truth_args): - """Run trig parameter sweeps.""" - prefix = {'MSE': 'mse', 'SW': 'sw', 'Pyramid': 'pyramid'}[loss_name] - - for pname, cfg in SWEEP_CONFIGS.items(): - lo, hi = cfg['range'] - truth_val = cfg['truth'] - unit = cfg['unit'] - eps = cfg['eps'] - pidx = PARAM_IDX[pname] - - x_vals = np.linspace(lo, hi, N_SWEEP) - print(f"\n {loss_name} — {pname} [{lo}, {hi}]", flush=True) - - def _args(val): - a = list(truth_args) - a[pidx] = jnp.float32(val) - return tuple(a) - - t0 = time.time() - losses = np.empty(N_SWEEP) - ad_grads = np.empty(N_SWEEP) - for i, v in enumerate(x_vals): - loss, grads = loss_vg(*_args(v)) - losses[i] = float(loss) - ad_grads[i] = float(grads[pidx]) - - fd_grads = np.array([ - (float(loss_jit(*_args(v + eps))) - - float(loss_jit(*_args(v - eps)))) / (2 * eps) - for v in x_vals - ]) - print(f" done ({time.time()-t0:.1f}s)", flush=True) - - # Plot - truth_label = f'Truth={truth_val:.4f}' - fig, axes = plt.subplots(1, 2, figsize=(12, 5)) - - axes[0].plot(x_vals, losses, 'b-', lw=1.5) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, label=truth_label) - axes[0].set_xlabel(pname) - axes[0].set_ylabel(f'{loss_name} Loss') - axes[0].set_title('Loss Landscape') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - - axes[1].plot(x_vals, ad_grads, 'r-', lw=1.5, label='Autodiff') - axes[1].plot(x_vals, fd_grads, 'b--', lw=1.5, alpha=0.7, label=f'FD (eps={eps})') - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, label=truth_label) - axes[1].set_xlabel(pname) - axes[1].set_ylabel(f'd{loss_name}/d{pname}') - axes[1].set_title('Gradient (Autodiff vs FD)') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - - fig.suptitle( - f'{loss_name} — varying {pname} (trig param, normalized direction)', - fontsize=14, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'{prefix}_trig_surface_{pname}.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f" Saved {fname}", flush=True) - - -def _comparison_plots(sw_jit, sw_vg, truth_args, mse_jit, mse_vg): - """Side-by-side: angle param vs trig param for theta direction.""" - - # --- Sweep sin_theta while cos_theta fixed (off-circle) --- - sin_vals = np.linspace(0.2, 1.0, N_SWEEP) - - sw_losses_sin = np.empty(N_SWEEP) - mse_losses_sin = np.empty(N_SWEEP) - # Effective theta for each sin_theta value (with cos_theta fixed at truth) - effective_theta_sin = np.arctan2(sin_vals, TRUTH_COS_THETA) - - for i, s in enumerate(sin_vals): - a = list(truth_args) - a[PARAM_IDX['sin_theta']] = jnp.float32(s) - sw_losses_sin[i] = float(sw_jit(*tuple(a))) - mse_losses_sin[i] = float(mse_jit(*tuple(a))) - - # --- Sweep cos_theta while sin_theta fixed (off-circle) --- - cos_vals = np.linspace(0.2, 1.0, N_SWEEP) - - sw_losses_cos = np.empty(N_SWEEP) - mse_losses_cos = np.empty(N_SWEEP) - effective_theta_cos = np.arctan2(TRUTH_SIN_THETA, cos_vals) - - for i, c in enumerate(cos_vals): - a = list(truth_args) - a[PARAM_IDX['cos_theta']] = jnp.float32(c) - sw_losses_cos[i] = float(sw_jit(*tuple(a))) - mse_losses_cos[i] = float(mse_jit(*tuple(a))) - - # V-parallel condition: -0.866*sin_theta + 0.5*cos_theta = 0 - # For sin_theta sweep: sin_theta_parallel = 0.5*cos_theta_truth/0.866 - sin_parallel = 0.5 * TRUTH_COS_THETA / 0.866 - # For cos_theta sweep: cos_theta_parallel = 0.866*sin_theta_truth/0.5 - cos_parallel = 0.866 * TRUTH_SIN_THETA / 0.5 - - # --- Plot comparison --- - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - - # Top-left: SW vs sin_theta - axes[0, 0].plot(sin_vals, sw_losses_sin, 'b-', lw=2) - axes[0, 0].axvline(TRUTH_SIN_THETA, color='green', ls='--', lw=2, - label=f'Truth sin_θ={TRUTH_SIN_THETA:.4f}') - if 0.2 <= sin_parallel <= 1.0: - axes[0, 0].axvline(sin_parallel, color='red', ls=':', lw=2, - label=f'V-parallel sin_θ={sin_parallel:.4f}') - axes[0, 0].set_xlabel('sin_theta') - axes[0, 0].set_ylabel('SW Loss') - axes[0, 0].set_title('SW vs sin_theta (cos_theta fixed)') - axes[0, 0].legend() - axes[0, 0].grid(True, alpha=0.3) - - # Top-right: SW vs cos_theta - axes[0, 1].plot(cos_vals, sw_losses_cos, 'b-', lw=2) - axes[0, 1].axvline(TRUTH_COS_THETA, color='green', ls='--', lw=2, - label=f'Truth cos_θ={TRUTH_COS_THETA:.4f}') - if 0.2 <= cos_parallel <= 1.0: - axes[0, 1].axvline(cos_parallel, color='red', ls=':', lw=2, - label=f'V-parallel cos_θ={cos_parallel:.4f}') - axes[0, 1].set_xlabel('cos_theta') - axes[0, 1].set_ylabel('SW Loss') - axes[0, 1].set_title('SW vs cos_theta (sin_theta fixed)') - axes[0, 1].legend() - axes[0, 1].grid(True, alpha=0.3) - - # Bottom-left: Effective theta for sin_theta sweep - ax2 = axes[1, 0] - ax2.plot(sin_vals, np.degrees(effective_theta_sin), 'k-', lw=1.5) - ax2.axhline(np.degrees(0.524), color='red', ls=':', lw=1.5, label='V-parallel (30°)') - ax2.axhline(np.degrees(TRUTH_THETA), color='green', ls='--', lw=1.5, label='Truth (45°)') - ax2.set_xlabel('sin_theta') - ax2.set_ylabel('Effective theta (deg)') - ax2.set_title('Effective angle vs sin_theta') - ax2.legend() - ax2.grid(True, alpha=0.3) - - # Bottom-right: Effective theta for cos_theta sweep - ax3 = axes[1, 1] - ax3.plot(cos_vals, np.degrees(effective_theta_cos), 'k-', lw=1.5) - ax3.axhline(np.degrees(0.524), color='red', ls=':', lw=1.5, label='V-parallel (30°)') - ax3.axhline(np.degrees(TRUTH_THETA), color='green', ls='--', lw=1.5, label='Truth (45°)') - ax3.set_xlabel('cos_theta') - ax3.set_ylabel('Effective theta (deg)') - ax3.set_title('Effective angle vs cos_theta') - ax3.legend() - ax3.grid(True, alpha=0.3) - - fig.suptitle( - 'Trig Parameterization: V-parallel at -0.866·sin_θ + 0.5·cos_θ = 0\n' - f'sin sweep: V-parallel at sin_θ={sin_parallel:.3f} | ' - f'cos sweep: V-parallel at cos_θ={cos_parallel:.3f} (off-range)', - fontsize=12, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'sw_trig_vs_angle_comparison.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}", flush=True) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='Trig parameterization gradient surfaces') - parser.add_argument( - '--loss', type=str, default='all', - choices=['mse', 'sw', 'pyramid', 'all'], - help='Which loss to run (default: all)', - ) - args = parser.parse_args() - if args.loss == 'all': - main(['mse', 'sw', 'pyramid']) - else: - main([args.loss]) diff --git a/closure/archive/muon_intermediate/plot_relax_comparison.py b/closure/archive/muon_intermediate/plot_relax_comparison.py deleted file mode 100644 index 8a79d5b..0000000 --- a/closure/archive/muon_intermediate/plot_relax_comparison.py +++ /dev/null @@ -1,225 +0,0 @@ -""" -Compare softplus relaxation values against the hard-clamp (true) baseline. - -For each relax value, produces a separate figure with: - - Left panel: loss landscape (softplus vs hard clamp) - - Right panel: gradient (softplus AD + softplus FD vs hard-clamp FD) - -Run from project root: - python3 closure_analysis_muon/plot_relax_comparison.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, _get_consistent_csda, build_muon_forward, -) - -# ============================================================================= -# Config -# ============================================================================= - -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 -STEP_SIZE_CM = STEP_SIZE_MM / 10.0 - -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 2 -TRUTH_ENERGY = 200.0 - -PLANES = [0, 1, 2] -N_SWEEP = 120 -ENERGY_RANGE = (100.0, 280.0) -FD_EPS = 0.5 - -RELAX_FACTORS = [1, 2, 5, 10] - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -# ============================================================================= -# CSDA builders -# ============================================================================= - -def make_csda_hard(R_cm, T_MeV): - def csda(kinetic_energy_mev): - indices = jnp.arange(N_SEGMENTS) - R_initial = jnp.interp(jnp.log(kinetic_energy_mev), jnp.log(T_MeV), R_cm) - R_at_start = R_initial - indices * STEP_SIZE_CM - R_at_end = R_initial - (indices + 1) * STEP_SIZE_CM - R_floor = R_cm[0] - E_start = jnp.interp(jnp.maximum(R_at_start, R_floor), R_cm, T_MeV) - E_end = jnp.interp(jnp.maximum(R_at_end, R_floor), R_cm, T_MeV) - return jnp.maximum(E_start - E_end, 0.0) - return csda - - -def make_csda_soft(R_cm, T_MeV, relax_cm): - def csda(kinetic_energy_mev): - indices = jnp.arange(N_SEGMENTS) - R_initial = jnp.interp(jnp.log(kinetic_energy_mev), jnp.log(T_MeV), R_cm) - R_at_start = R_initial - indices * STEP_SIZE_CM - R_at_end = R_initial - (indices + 1) * STEP_SIZE_CM - R_floor = R_cm[0] - R_s = R_floor + jax.nn.softplus((R_at_start - R_floor) / relax_cm) * relax_cm - R_e = R_floor + jax.nn.softplus((R_at_end - R_floor) / relax_cm) * relax_cm - E_start = jnp.interp(R_s, R_cm, T_MeV) - E_end = jnp.interp(R_e, R_cm, T_MeV) - return jnp.maximum(E_start - E_end, 0.0) - return csda - - -def make_sim_fn(csda_fn, forward_fn): - def sim_forward(x, y, z, theta, phi, energy): - sin_t = jnp.sin(theta); cos_t = jnp.cos(theta) - sin_p = jnp.sin(phi); cos_p = jnp.cos(phi) - dir_vec = jnp.array([sin_t * cos_p, sin_t * sin_p, cos_t]) - step_vec = dir_vec * STEP_SIZE_MM - indices = jnp.arange(N_SEGMENTS) - positions = jnp.array([x, y, z])[None, :] + indices[:, None] * step_vec[None, :] - de = csda_fn(energy) - return forward_fn(positions, de) - return sim_forward - - -# ============================================================================= -# Main -# ============================================================================= - -def main(): - print("=" * 70) - print("RELAX COMPARISON: per-relax figures, energy sweep") - print("=" * 70) - - log_T, dedx = load_dedx_table_jax() - R_cm, T_MeV = _get_consistent_csda(log_T, dedx) - - det = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - truth_args = tuple(jnp.float32(v) for v in - [TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY]) - - # --- Hard-clamp truth signals (the ground truth target) --- - print("\nBuilding hard-clamp truth signals...", flush=True) - csda_hard = make_csda_hard(R_cm, T_MeV) - sim_hard = make_sim_fn(csda_hard, forward) - truth_sigs = jax.jit(sim_hard)(*truth_args) - for s in truth_sigs: - jax.block_until_ready(s) - target_sigs = {p: truth_sigs[p] for p in PLANES} - - def make_mse(sim_fn): - def mse_loss(x, y, z, theta, phi, energy): - sigs = sim_fn(x, y, z, theta, phi, energy) - return sum(jnp.mean((sigs[p] - target_sigs[p]) ** 2) for p in PLANES) - return mse_loss - - # --- Compile hard-clamp loss (FD only) --- - print(" Compiling hard clamp (FD only)...", flush=True) - t0 = time.time() - mse_hard = make_mse(sim_hard) - loss_hard_jit = jax.jit(mse_hard) - _ = loss_hard_jit(*truth_args) - print(f" done ({time.time()-t0:.1f}s)", flush=True) - - # --- Energy sweep points --- - e_vals = np.linspace(*ENERGY_RANGE, N_SWEEP) - - def _args(E): - a = list(truth_args) - a[5] = jnp.float32(E) - return tuple(a) - - # --- Hard-clamp: loss only (no FD needed) --- - print(f"\nSweeping hard clamp loss ({N_SWEEP} pts)...", flush=True) - t0 = time.time() - hard_losses = np.empty(N_SWEEP) - for i, E in enumerate(e_vals): - hard_losses[i] = float(loss_hard_jit(*_args(E))) - print(f" done ({time.time()-t0:.1f}s)", flush=True) - - # --- Per-relax: compile, sweep, plot --- - for rf in RELAX_FACTORS: - relax_cm = STEP_SIZE_CM * rf - label = f'{rf}x step ({relax_cm*10:.1f} mm)' - - print(f"\n--- relax = {rf}x step ---", flush=True) - print(f" Compiling...", flush=True) - t0 = time.time() - csda_soft = make_csda_soft(R_cm, T_MeV, relax_cm) - sim_soft = make_sim_fn(csda_soft, forward) - mse_soft = make_mse(sim_soft) - loss_soft_jit = jax.jit(mse_soft) - loss_soft_vg = jax.jit(jax.value_and_grad(mse_soft, argnums=tuple(range(6)))) - _ = loss_soft_jit(*truth_args) - _ = loss_soft_vg(*truth_args) - print(f" done ({time.time()-t0:.1f}s)", flush=True) - - print(f" Sweeping ({N_SWEEP} pts)...", flush=True) - t0 = time.time() - soft_losses = np.empty(N_SWEEP) - soft_ad = np.empty(N_SWEEP) - soft_fd = np.empty(N_SWEEP) - for i, E in enumerate(e_vals): - loss, grads = loss_soft_vg(*_args(E)) - soft_losses[i] = float(loss) - soft_ad[i] = float(grads[5]) - soft_fd[i] = (float(loss_soft_jit(*_args(E + FD_EPS))) - - float(loss_soft_jit(*_args(E - FD_EPS)))) / (2 * FD_EPS) - print(f" done ({time.time()-t0:.1f}s)", flush=True) - - # --- Figure: loss (left) + gradient (right) --- - fig, (ax_loss, ax_grad) = plt.subplots(1, 2, figsize=(16, 6)) - - # Loss panel - ax_loss.plot(e_vals, hard_losses, 'k-', lw=2, label='Hard clamp (true)') - ax_loss.plot(e_vals, soft_losses, 'r-', lw=1.5, alpha=0.9, - label=f'Softplus {label}') - ax_loss.axvline(TRUTH_ENERGY, color='green', ls='--', lw=1.5, alpha=0.7) - ax_loss.set_xlabel('Energy (MeV)', fontsize=13) - ax_loss.set_ylabel('MSE Loss', fontsize=13) - ax_loss.set_title('Loss Landscape', fontsize=14) - ax_loss.legend(fontsize=11) - ax_loss.grid(True, alpha=0.3) - - # Gradient panel - ax_grad.plot(e_vals, soft_ad, 'r-', lw=1.5, alpha=0.9, - label=f'Softplus AD') - ax_grad.plot(e_vals, soft_fd, 'b:', lw=1.5, alpha=0.7, - label=f'Softplus FD') - ax_grad.axhline(0, color='k', ls='-', lw=0.5) - ax_grad.axvline(TRUTH_ENERGY, color='green', ls='--', lw=1.5, alpha=0.7) - ax_grad.set_xlabel('Energy (MeV)', fontsize=13) - ax_grad.set_ylabel('dLoss/dEnergy', fontsize=13) - ax_grad.set_title('Gradient', fontsize=14) - ax_grad.legend(fontsize=11) - ax_grad.grid(True, alpha=0.3) - - fig.suptitle( - f'Softplus relax = {label}\n' - f'target = hard-clamp truth, MSE loss, {N_SEGMENTS} seg, step={STEP_SIZE_MM}mm', - fontsize=14, fontweight='bold', - ) - fig.tight_layout(rect=[0, 0, 1, 0.91]) - fname = os.path.join(OUT_DIR, f'relax_energy_{rf}x.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved {fname}", flush=True) - - print("\nDone!") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/render_multi_3d_gif.py b/closure/archive/muon_intermediate/render_multi_3d_gif.py deleted file mode 100644 index 60510d2..0000000 --- a/closure/archive/muon_intermediate/render_multi_3d_gif.py +++ /dev/null @@ -1,232 +0,0 @@ -""" -Render 3D GIF showing optimization tracks converging to truth. - -Loads precomputed endpoints from individual optimization_X.npz files. - -Usage: - python3 closure_analysis_muon/render_multi_3d_gif.py A B D - python3 closure_analysis_muon/render_multi_3d_gif.py A B C D -""" - -import sys, os, argparse -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import numpy as np -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt -import time -from PIL import Image - -# ============================================================================= -# Settings -# ============================================================================= - -FRAME_EVERY = 2 -GIF_FPS = 50 -FINAL_PAUSE_MS = 500 - -COLORS = {'A': '#1f77b4', 'B': '#ff7f0e', 'C': '#2ca02c', 'D': '#d62728'} - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -# ============================================================================= -# Helpers -# ============================================================================= - -def fig_to_image(fig): - fig.canvas.draw() - w, h = fig.canvas.get_width_height() - buf = fig.canvas.buffer_rgba() - return Image.frombuffer('RGBA', (w, h), buf, 'raw', 'RGBA', 0, 1).convert('RGB').copy() - - -# ============================================================================= -# Renderer -# ============================================================================= - -class MultiTrack3DRenderer: - def __init__(self, truth_start, truth_end, truth_phys, view_lims, labels): - self.labels = labels - self.fig = plt.figure(figsize=(10, 9)) - self.ax = self.fig.add_subplot(111, projection='3d') - - # Arrow length as fraction of track length - self._arrow_frac = 0.15 - - # Truth track (static) with direction arrow - truth_dir = truth_end - truth_start - truth_len = np.linalg.norm(truth_dir) - truth_arrow_len = truth_len * self._arrow_frac - truth_unit = truth_dir / max(truth_len, 1e-6) - arrow_base = truth_end - truth_unit * truth_arrow_len - - self.ax.plot([truth_start[0], arrow_base[0]], - [truth_start[1], arrow_base[1]], - [truth_start[2], arrow_base[2]], - color='black', ls='--', lw=2.5, alpha=0.8, label='Truth') - self.ax.quiver(arrow_base[0], arrow_base[1], arrow_base[2], - truth_unit[0], truth_unit[1], truth_unit[2], - length=truth_arrow_len, color='black', alpha=0.8, - arrow_length_ratio=0.4, linewidth=2.5) - self.ax.scatter(*truth_start, c='white', s=140, marker='o', - edgecolors='black', linewidths=2.0, zorder=5) - - # Reco tracks (updated each frame) - self._lines = [] - self._starts = [] - self._arrows = [] - for i, label in enumerate(labels): - color = COLORS[label] - line, = self.ax.plot([], [], [], color=color, ls='-', - lw=2.0, alpha=0.85, label=f'Init {i+1}') - start = self.ax.scatter([0], [0], [0], c='white', s=120, - marker='o', edgecolors=color, linewidths=2.0, zorder=5) - self._lines.append(line) - self._starts.append(start) - - self.ax.set_xlim(view_lims['x']) - self.ax.set_ylim(view_lims['y']) - self.ax.set_zlim(view_lims['z']) - self.ax.set_xlabel('x (mm)', fontsize=15) - self.ax.set_ylabel('y (mm)', fontsize=15) - self.ax.set_zlabel('z (mm)', fontsize=15) - self.ax.tick_params(labelsize=12) - self.ax.view_init(elev=20, azim=-55) - self.ax.legend(loc='upper left', fontsize=12) - - truth_theta = np.degrees(np.arctan2(truth_phys[3], truth_phys[4])) - truth_phi = np.degrees(np.arctan2(truth_phys[5], truth_phys[6])) - self._truth_sub = ( - f'Truth: x={truth_phys[0]:.0f}, y={truth_phys[1]:.0f}, ' - f'z={truth_phys[2]:.0f}, ' - f'\u03b8={truth_theta:.1f}\u00b0, \u03c6={truth_phi:.1f}\u00b0, ' - f'E={truth_phys[7]:.0f} MeV') - - self._title = self.fig.suptitle('', fontsize=15, y=0.98) - self.fig.subplots_adjust(left=-0.05, right=1.05, bottom=-0.05, top=0.88) - - def render(self, all_starts, all_ends, step, n_steps, losses): - # Remove previous arrows - for arrow in self._arrows: - arrow.remove() - self._arrows.clear() - - for i in range(len(self.labels)): - s, e = all_starts[i], all_ends[i] - d = e - s - length = np.linalg.norm(d) - unit = d / max(length, 1e-6) - arrow_len = length * self._arrow_frac - arrow_base = e - unit * arrow_len - - self._lines[i].set_data_3d( - [s[0], arrow_base[0]], [s[1], arrow_base[1]], [s[2], arrow_base[2]]) - self._starts[i]._offsets3d = ([s[0]], [s[1]], [s[2]]) - - color = COLORS[self.labels[i]] - q = self.ax.quiver(arrow_base[0], arrow_base[1], arrow_base[2], - unit[0], unit[1], unit[2], - length=arrow_len, color=color, alpha=0.85, - arrow_length_ratio=0.4, linewidth=2.0) - self._arrows.append(q) - - loss_str = ' '.join( - f'Init {i+1}:{losses[i]:.2f}' for i in range(len(self.labels))) - self._title.set_text( - f'Step {step:3d}/{n_steps} | Loss: {loss_str}\n{self._truth_sub}') - return fig_to_image(self.fig) - - -# ============================================================================= -# Main -# ============================================================================= - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('labels', nargs='+', help='Run labels to include (e.g. A B D)') - args = parser.parse_args() - - labels = args.labels - print(f"Rendering 3D GIF for runs: {labels}") - - # Load individual NPZ files - runs = {} - for label in labels: - path = os.path.join(OUT_DIR, f'optimization_{label}.npz') - if not os.path.exists(path): - print(f"Error: {path} not found. Run optimization first.") - sys.exit(1) - runs[label] = np.load(path, allow_pickle=True) - - # Use truth from first run (all should be the same) - first = runs[labels[0]] - truth_phys = first['truth_phys'] - truth_start = first['truth_start'] - truth_end = first['truth_end'] - n_steps = int(first['n_steps']) - - # Check all runs have same n_steps (use min if different) - for label in labels: - ns = int(runs[label]['n_steps']) - if ns < n_steps: - n_steps = ns - print(f" Using {n_steps} steps") - - loss_histories = [runs[l]['loss_history'] for l in labels] - ep_starts = [runs[l]['endpoints_starts'] for l in labels] - ep_ends = [runs[l]['endpoints_ends'] for l in labels] - - # Frame steps - frame_steps = list(range(0, n_steps + 1, FRAME_EVERY)) - if frame_steps[-1] != n_steps: - frame_steps.append(n_steps) - n_frames = len(frame_steps) - print(f" {n_frames} frames (every {FRAME_EVERY} steps)") - - # Compute view limits from all endpoints - all_pts = [truth_start[None, :], truth_end[None, :]] - for ri in range(len(labels)): - all_pts.append(ep_starts[ri]) - all_pts.append(ep_ends[ri]) - all_pts = np.concatenate(all_pts) - pad_3d = 200.0 - view_lims = { - 'x': (float(all_pts[:, 0].min() - pad_3d), float(all_pts[:, 0].max() + pad_3d)), - 'y': (float(all_pts[:, 1].min() - pad_3d), float(all_pts[:, 1].max() + pad_3d)), - 'z': (float(all_pts[:, 2].min() - pad_3d), float(all_pts[:, 2].max() + pad_3d)), - } - print(f" View limits: x={view_lims['x']}, y={view_lims['y']}, z={view_lims['z']}") - - # Render frames - print(f"\nRendering {n_frames} frames...", flush=True) - renderer = MultiTrack3DRenderer(truth_start, truth_end, truth_phys, view_lims, labels) - frames = [] - - t0 = time.time() - for fi, step in enumerate(frame_steps): - starts = [ep_starts[ri][step] for ri in range(len(labels))] - ends = [ep_ends[ri][step] for ri in range(len(labels))] - losses = [loss_histories[ri][step] for ri in range(len(labels))] - frames.append(renderer.render(starts, ends, step, n_steps, losses)) - - if (fi + 1) % 20 == 0 or fi == 0 or fi == n_frames - 1: - print(f" Frame {fi+1}/{n_frames} ({time.time()-t0:.1f}s)", flush=True) - - # Save GIF - duration_ms = int(1000 / GIF_FPS) - durations = [duration_ms] * n_frames - durations[-1] = FINAL_PAUSE_MS - - gif_path = os.path.join(OUT_DIR, 'multi_track_3d_optimization.gif') - print(f"Saving {gif_path}...", flush=True) - frames[0].save( - gif_path, save_all=True, append_images=frames[1:], - duration=durations, loop=0, optimize=False, - ) - print(f" Done ({os.path.getsize(gif_path) / 1e6:.1f} MB)") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/render_optimization_gifs.py b/closure/archive/muon_intermediate/render_optimization_gifs.py deleted file mode 100644 index b2ecf76..0000000 --- a/closure/archive/muon_intermediate/render_optimization_gifs.py +++ /dev/null @@ -1,265 +0,0 @@ -""" -Render 3D track convergence GIF from saved optimization history. - -Loads optimization_history.npz, re-runs forward passes to get track -positions, and renders track_3d_optimization.gif showing truth vs reco -track converging over optimization steps. - -Run from project root: - python3 closure_analysis_muon/render_optimization_gifs.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt -import time -from PIL import Image - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments_trig, - mask_outside_volume, - build_muon_forward, -) - -# ============================================================================= -# GIF settings -# ============================================================================= - -FRAME_EVERY = 5 # every 5th step → 61 frames -GIF_FPS = 10 # playback speed (same total duration) -FINAL_PAUSE_MS = 500 # hold on last frame - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -HISTORY_FILE = os.path.join(OUT_DIR, 'optimization_history.npz') - - -# ============================================================================= -# Helpers -# ============================================================================= - -def fig_to_image(fig): - """Convert matplotlib figure to PIL Image via canvas buffer (no PNG encode).""" - fig.canvas.draw() - w, h = fig.canvas.get_width_height() - buf = fig.canvas.buffer_rgba() - return Image.frombuffer('RGBA', (w, h), buf, 'raw', 'RGBA', 0, 1).convert('RGB').copy() - - -def _info_text(step, n_steps, loss, params_phys): - """Format title string.""" - eff_theta = np.degrees(np.arctan2(params_phys[3], params_phys[4])) - eff_phi = np.degrees(np.arctan2(params_phys[5], params_phys[6])) - return ( - f'Step {step:3d}/{n_steps} | Loss: {loss:.6f}\n' - f'x={params_phys[0]:.1f}, y={params_phys[1]:.1f}, ' - f'z={params_phys[2]:.1f} mm | ' - f'\u03b8={eff_theta:.1f}\u00b0, \u03c6={eff_phi:.1f}\u00b0 | ' - f'E={params_phys[7]:.1f} MeV' - ) - - -# ============================================================================= -# 3D Track Renderer -# ============================================================================= - -class Track3DRenderer: - """Reusable 3D figure — truth line fixed, update reco line per frame.""" - - def __init__(self, truth_start, truth_end, truth_phys, view_lims): - self.fig = plt.figure(figsize=(10, 9)) - self.ax = self.fig.add_subplot(111, projection='3d') - - # Truth: start-to-end dashed line (static) - self.ax.plot([truth_start[0], truth_end[0]], - [truth_start[1], truth_end[1]], - [truth_start[2], truth_end[2]], - color='green', ls='--', lw=2.5, alpha=0.8, label='Truth') - self.ax.scatter(*truth_start, c='green', s=120, marker='o', - edgecolors='black', linewidths=1.0, zorder=5, - label='Truth start') - self.ax.scatter(*truth_end, c='green', s=80, marker='s', - edgecolors='black', linewidths=1.0, zorder=5) - - # Reco: placeholder line (updated each frame) - self._reco_line, = self.ax.plot([], [], [], color='red', ls='-', - lw=2.5, alpha=0.8, label='Reco') - self._reco_start = self.ax.scatter([0], [0], [0], c='red', s=120, - marker='o', edgecolors='black', linewidths=1.0, - zorder=5, label='Reco start') - self._reco_end = self.ax.scatter([0], [0], [0], c='red', s=80, - marker='s', edgecolors='black', linewidths=1.0, zorder=5) - - self.ax.set_xlim(view_lims['x']) - self.ax.set_ylim(view_lims['y']) - self.ax.set_zlim(view_lims['z']) - self.ax.set_xlabel('x (mm)', fontsize=15) - self.ax.set_ylabel('y (mm)', fontsize=15) - self.ax.set_zlabel('z (mm)', fontsize=15) - self.ax.tick_params(labelsize=12) - self.ax.view_init(elev=20, azim=-55) - self.ax.legend(loc='upper left', fontsize=14) - - truth_theta = np.degrees(np.arctan2(truth_phys[3], truth_phys[4])) - truth_phi = np.degrees(np.arctan2(truth_phys[5], truth_phys[6])) - self._truth_subtitle = ( - f'Truth: x={truth_phys[0]:.0f}, y={truth_phys[1]:.0f}, ' - f'z={truth_phys[2]:.0f}, ' - f'\u03b8={truth_theta:.1f}\u00b0, \u03c6={truth_phi:.1f}\u00b0, ' - f'E={truth_phys[7]:.0f} MeV') - - self._title = self.fig.suptitle('', fontsize=15, y=0.98) - self.fig.subplots_adjust(left=-0.05, right=1.05, bottom=-0.05, top=0.88) - - def render(self, reco_start, reco_end, step, n_steps, loss, params_phys): - self._reco_line.set_data_3d([reco_start[0], reco_end[0]], - [reco_start[1], reco_end[1]], - [reco_start[2], reco_end[2]]) - self._reco_start._offsets3d = ([reco_start[0]], [reco_start[1]], [reco_start[2]]) - self._reco_end._offsets3d = ([reco_end[0]], [reco_end[1]], [reco_end[2]]) - - self._title.set_text( - _info_text(step, n_steps, loss, params_phys) + '\n' + - self._truth_subtitle) - return fig_to_image(self.fig) - - -# ============================================================================= -# Main -# ============================================================================= - -def main(): - print("=" * 70) - print("RENDER 3D TRACK GIF") - print("=" * 70) - - # --- Load history --- - print(f"Loading {HISTORY_FILE}...") - data = np.load(HISTORY_FILE) - param_history = data['param_history_phys'] # (N+1, 8) - loss_history = data['loss_history'] # (N+1,) - truth_phys = data['truth_phys'] # (8,) - n_segments = int(data['n_segments']) - step_size_mm = float(data['step_size_mm']) - n_steps = int(data['n_steps']) - - print(f" {n_steps} optimization steps, {len(param_history)} param snapshots") - - # Select frame steps - frame_steps = list(range(0, n_steps + 1, FRAME_EVERY)) - if frame_steps[-1] != n_steps: - frame_steps.append(n_steps) - n_frames = len(frame_steps) - print(f" Rendering {n_frames} frames") - - # --- Set up simulator (same approach as previous working version) --- - print("\nSetting up simulator...", flush=True) - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=n_segments) - forward = build_muon_forward(sim, n_segments, step_size_mm) - - @jax.jit - def run_forward(phys_np): - phys = jnp.array(phys_np, dtype=jnp.float32) - pos, de = generate_muon_segments_trig( - phys[7], jnp.array([phys[0], phys[1], phys[2]]), - phys[3], phys[4], phys[5], phys[6], - step_size_mm, n_segments, log_T, dedx, - ) - de = mask_outside_volume(pos, de) - sigs = forward(pos, de) - return sigs, pos, de - - print("Compiling forward (single JIT)...", flush=True) - t0 = time.time() - truth_sigs, truth_pos, truth_de = run_forward(truth_phys) - for s in truth_sigs: - jax.block_until_ready(s) - print(f" Done ({time.time()-t0:.1f}s)") - - # Extract truth endpoints - truth_pos_np = np.array(truth_pos) - truth_de_np = np.array(truth_de) - truth_active = truth_de_np > 0 - tp = truth_pos_np[truth_active] - truth_start = tp[0] - truth_end = tp[-1] - - # --- Collect all track endpoints via forward passes --- - print(f"\nCollecting track endpoints ({n_frames} forward passes)...", flush=True) - track_data = [] # (start, end, step, loss, phys) - - for i, step in enumerate(frame_steps): - phys = param_history[step] - _, reco_pos, reco_de = run_forward(phys) - jax.block_until_ready(reco_de) - reco_pos_np = np.array(reco_pos) - reco_de_np = np.array(reco_de) - reco_active = reco_de_np > 0 - - if np.any(reco_active): - rp = reco_pos_np[reco_active] - rp_start, rp_end = rp[0].copy(), rp[-1].copy() - else: - rp_start = reco_pos_np[0].copy() - rp_end = reco_pos_np[1].copy() - - track_data.append((rp_start, rp_end, step, loss_history[step], phys.copy())) - - if (i + 1) % 50 == 0 or i == 0 or i == n_frames - 1: - print(f" {i+1}/{n_frames} (step {step})", flush=True) - - # --- Compute view limits from ALL endpoints --- - all_pts = [truth_start[None, :], truth_end[None, :]] - for rp_start, rp_end, _, _, _ in track_data: - all_pts.append(rp_start[None, :]) - all_pts.append(rp_end[None, :]) - all_pts = np.concatenate(all_pts) - pad_3d = 200.0 - view_lims = { - 'x': (float(all_pts[:, 0].min() - pad_3d), float(all_pts[:, 0].max() + pad_3d)), - 'y': (float(all_pts[:, 1].min() - pad_3d), float(all_pts[:, 1].max() + pad_3d)), - 'z': (float(all_pts[:, 2].min() - pad_3d), float(all_pts[:, 2].max() + pad_3d)), - } - print(f" View limits: x={view_lims['x']}, y={view_lims['y']}, z={view_lims['z']}") - - # --- Render frames --- - print(f"\nRendering {n_frames} 3D track frames...", flush=True) - renderer = Track3DRenderer(truth_start, truth_end, truth_phys, view_lims) - frames = [] - - for i, (rp_start, rp_end, step, loss, phys) in enumerate(track_data): - t0 = time.time() - frames.append(renderer.render(rp_start, rp_end, step, n_steps, loss, phys)) - elapsed = time.time() - t0 - if (i + 1) % 50 == 0 or i == 0 or i == n_frames - 1: - print(f" Frame {i+1}/{n_frames}: {elapsed:.2f}s", flush=True) - - # --- Save GIF --- - duration_ms = int(1000 / GIF_FPS) - durations = [duration_ms] * n_frames - durations[-1] = FINAL_PAUSE_MS - - track_gif = os.path.join(OUT_DIR, 'track_3d_optimization.gif') - print(f"Saving {track_gif}...", flush=True) - frames[0].save( - track_gif, save_all=True, append_images=frames[1:], - duration=durations, loop=0, optimize=False, - ) - print(f" Done ({os.path.getsize(track_gif) / 1e6:.1f} MB)") - - print("\nAll done!") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/run_multi_optimization.py b/closure/archive/muon_intermediate/run_multi_optimization.py deleted file mode 100644 index 05f7a93..0000000 --- a/closure/archive/muon_intermediate/run_multi_optimization.py +++ /dev/null @@ -1,442 +0,0 @@ -""" -Run 4 muon optimizations from different initial guesses, save histories, -and plot comparison of convergence (loss, position, theta, phi, energy). - -Run from project root: - python3 closure_analysis_muon/run_multi_optimization.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt -import optax -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean, make_sobolev_weight - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments_trig, - mask_outside_volume, - build_muon_forward, -) - -# ============================================================================= -# Configuration -# ============================================================================= - -N_SEGMENTS = 4000 -STEP_SIZE_MM = 0.5 - -TRUTH_X = -200.0 -TRUTH_Y = 0.0 -TRUTH_Z = 100.0 -TRUTH_THETA = np.pi / 4 -TRUTH_PHI = np.pi / 6 -TRUTH_ENERGY = 500.0 - -TRUTH_PHYS = np.array([ - TRUTH_X, TRUTH_Y, TRUTH_Z, - np.sin(TRUTH_THETA), np.cos(TRUTH_THETA), - np.sin(TRUTH_PHI), np.cos(TRUTH_PHI), - TRUTH_ENERGY, -]) - -SCALES = np.array([200.0, 200.0, 200.0, 1.0, 1.0, 1.0, 1.0, 500.0]) -SCALES_JAX = jnp.array(SCALES, dtype=jnp.float32) - -N_STEPS = 1000 -LR = 0.01 -B1 = 0.9 -B2 = 0.99 - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -# 4 different initial guesses — moderate perturbations -INIT_CONFIGS = [ - { - 'label': 'Init A', - 'dx': +400.0, 'dy': +300.0, 'dz': -300.0, - 'dtheta': +0.4, 'dphi': +0.4, 'dE': +100.0, - }, - { - 'label': 'Init B', - 'dx': -300.0, 'dy': -400.0, 'dz': +400.0, - 'dtheta': -0.4, 'dphi': -0.4, 'dE': -100.0, - }, - { - 'label': 'Init C', - 'dx': +500.0, 'dy': -300.0, 'dz': +200.0, - 'dtheta': +0.5, 'dphi': -0.3, 'dE': +150.0, - }, - { - 'label': 'Init D', - 'dx': -200.0, 'dy': +500.0, 'dz': -400.0, - 'dtheta': -0.3, 'dphi': +0.5, 'dE': -150.0, - }, -] - - -# ============================================================================= -# Helpers -# ============================================================================= - -def to_physical(norm_params): - return norm_params * SCALES_JAX - - -def project_unit_circle(norm_params): - st, ct = norm_params[3], norm_params[4] - norm_t = jnp.maximum(jnp.sqrt(st**2 + ct**2), 1e-8) - sp, cp = norm_params[5], norm_params[6] - norm_p = jnp.maximum(jnp.sqrt(sp**2 + cp**2), 1e-8) - return norm_params.at[3].set(st / norm_t).at[4].set(ct / norm_t) \ - .at[5].set(sp / norm_p).at[6].set(cp / norm_p) - - -def _make_sim_forward(forward, log_T, dedx): - def sim_forward(phys): - pos, de = generate_muon_segments_trig( - phys[7], jnp.array([phys[0], phys[1], phys[2]]), - phys[3], phys[4], phys[5], phys[6], - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - de = mask_outside_volume(pos, de) - return forward(pos, de) - return sim_forward - - -def make_init_phys(cfg): - """Build initial physical params from perturbation config.""" - theta_init = TRUTH_THETA + cfg['dtheta'] - phi_init = TRUTH_PHI + cfg['dphi'] - return np.array([ - TRUTH_X + cfg['dx'], - TRUTH_Y + cfg['dy'], - TRUTH_Z + cfg['dz'], - np.sin(theta_init), - np.cos(theta_init), - np.sin(phi_init), - np.cos(phi_init), - TRUTH_ENERGY + cfg['dE'], - ]) - - -def run_single_optimization(loss_and_grad, init_phys, run_idx): - """Run one optimization, return (param_history, loss_history).""" - init_norm = init_phys / SCALES - init_n = jnp.array(init_norm, dtype=jnp.float32) - - init_loss, init_grad = loss_and_grad(init_n) - jax.block_until_ready(init_grad) - print(f" Initial loss: {float(init_loss):.6f}") - - optimizer = optax.adam(learning_rate=LR, b1=B1, b2=B2) - opt_state = optimizer.init(init_n) - params_n = init_n - - param_history_phys = np.empty((N_STEPS + 1, 8)) - loss_history = np.empty(N_STEPS + 1) - - param_history_phys[0] = np.array(to_physical(params_n)) - loss_history[0] = float(init_loss) - - t_start = time.time() - for step in range(N_STEPS): - loss, grad = loss_and_grad(params_n) - updates, opt_state = optimizer.update(grad, opt_state, params_n) - params_n = optax.apply_updates(params_n, updates) - params_n = project_unit_circle(params_n) - - p = np.array(to_physical(params_n)) - param_history_phys[step + 1] = p - loss_history[step + 1] = float(loss) - - if (step + 1) % 50 == 0 or step == N_STEPS - 1: - eff_theta = float(jnp.arctan2(params_n[3], params_n[4])) - eff_phi = float(jnp.arctan2(params_n[5], params_n[6])) - elapsed = time.time() - t_start - print(f" Step {step+1:3d}: loss={float(loss):.6f}, " - f"x={p[0]:7.1f}, y={p[1]:7.1f}, z={p[2]:7.1f}, " - f"th={np.degrees(eff_theta):5.1f} deg, " - f"ph={np.degrees(eff_phi):5.1f} deg, " - f"E={p[7]:6.1f} MeV ({elapsed:.1f}s)", flush=True) - - total = time.time() - t_start - print(f" Done in {total:.1f}s ({total/N_STEPS:.2f}s/step)") - return param_history_phys, loss_history - - -# ============================================================================= -# Plotting -# ============================================================================= - -COLORS = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'] - - -def plot_multi_convergence(all_results, all_labels): - """5-panel comparison plot: loss, |dr|, dtheta, dphi, dE.""" - steps = np.arange(N_STEPS + 1) - - fig, axes = plt.subplots(2, 3, figsize=(16, 10)) - - # --- Loss --- - ax = axes[0, 0] - for i, (phist, lhist) in enumerate(all_results): - ax.semilogy(steps, lhist, color=COLORS[i], lw=1.5, - label=all_labels[i], alpha=0.85) - ax.set_xlabel('Step') - ax.set_ylabel('Sobolev Geomean Loss') - ax.set_title('Loss Convergence') - ax.legend(fontsize=8) - ax.grid(True, alpha=0.3) - - # --- Position difference (Euclidean |dr|) --- - ax = axes[0, 1] - for i, (phist, _) in enumerate(all_results): - dr = np.sqrt((phist[:, 0] - TRUTH_X)**2 + - (phist[:, 1] - TRUTH_Y)**2 + - (phist[:, 2] - TRUTH_Z)**2) - ax.semilogy(steps, dr + 1e-3, color=COLORS[i], lw=1.5, - label=all_labels[i], alpha=0.85) - ax.set_xlabel('Step') - ax.set_ylabel('|r - r_truth| (mm)') - ax.set_title('Position Difference') - ax.legend(fontsize=8) - ax.grid(True, alpha=0.3) - - # --- Theta difference --- - ax = axes[0, 2] - for i, (phist, _) in enumerate(all_results): - eff_theta = np.arctan2(phist[:, 3], phist[:, 4]) - dtheta = np.abs(np.degrees(eff_theta - TRUTH_THETA)) - ax.semilogy(steps, dtheta + 1e-4, color=COLORS[i], lw=1.5, - label=all_labels[i], alpha=0.85) - ax.set_xlabel('Step') - ax.set_ylabel('|theta - truth| (deg)') - ax.set_title('Theta Difference') - ax.legend(fontsize=8) - ax.grid(True, alpha=0.3) - - # --- Phi difference --- - ax = axes[1, 0] - for i, (phist, _) in enumerate(all_results): - eff_phi = np.arctan2(phist[:, 5], phist[:, 6]) - dphi = np.abs(np.degrees(eff_phi - TRUTH_PHI)) - ax.semilogy(steps, dphi + 1e-4, color=COLORS[i], lw=1.5, - label=all_labels[i], alpha=0.85) - ax.set_xlabel('Step') - ax.set_ylabel('|phi - truth| (deg)') - ax.set_title('Phi Difference') - ax.legend(fontsize=8) - ax.grid(True, alpha=0.3) - - # --- Energy difference --- - ax = axes[1, 1] - for i, (phist, _) in enumerate(all_results): - dE = np.abs(phist[:, 7] - TRUTH_ENERGY) - ax.semilogy(steps, dE + 1e-3, color=COLORS[i], lw=1.5, - label=all_labels[i], alpha=0.85) - ax.set_xlabel('Step') - ax.set_ylabel('|E - E_truth| (MeV)') - ax.set_title('Energy Difference') - ax.legend(fontsize=8) - ax.grid(True, alpha=0.3) - - # --- Final residuals table --- - ax = axes[1, 2] - ax.axis('off') - headers = ['Run', '|dr| mm', 'dth deg', 'dph deg', 'dE MeV', 'Loss'] - rows = [] - for i, (phist, lhist) in enumerate(all_results): - fp = phist[-1] - dr = np.sqrt((fp[0]-TRUTH_X)**2 + (fp[1]-TRUTH_Y)**2 + (fp[2]-TRUTH_Z)**2) - dth = np.abs(np.degrees(np.arctan2(fp[3], fp[4]) - TRUTH_THETA)) - dph = np.abs(np.degrees(np.arctan2(fp[5], fp[6]) - TRUTH_PHI)) - dE = np.abs(fp[7] - TRUTH_ENERGY) - label_short = chr(ord('A') + i) - rows.append([label_short, f'{dr:.2f}', f'{dth:.2f}', f'{dph:.2f}', - f'{dE:.2f}', f'{lhist[-1]:.6f}']) - table = ax.table(cellText=rows, colLabels=headers, loc='center', - cellLoc='center') - table.auto_set_font_size(False) - table.set_fontsize(10) - table.scale(1.0, 1.5) - for j in range(len(headers)): - table[0, j].set_facecolor('#d4e6f1') - for i in range(len(rows)): - table[i + 1, 0].set_facecolor(COLORS[i] + '33') # light tint - ax.set_title('Final Residuals', fontsize=12, pad=20) - - fig.suptitle( - f'Multi-Start Muon Optimization: {N_STEPS} steps, Adam LR={LR} b1={B1} b2={B2}, ' - f'Sobolev s=1.5\n' - f'Truth: x={TRUTH_X}, y={TRUTH_Y}, z={TRUTH_Z}, ' - f'theta={np.degrees(TRUTH_THETA):.1f} deg, ' - f'phi={np.degrees(TRUTH_PHI):.1f} deg, E={TRUTH_ENERGY} MeV', - fontsize=11, fontweight='bold', - ) - fig.tight_layout(rect=[0, 0, 1, 0.93]) - fname = os.path.join(OUT_DIR, 'multi_optimization_convergence.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f"\nSaved {fname}") - - -# ============================================================================= -# Main -# ============================================================================= - -def main(): - print("=" * 70) - print("MULTI-START MUON OPTIMIZATION (4 INITIAL GUESSES)") - print("=" * 70) - print(f"Truth: x={TRUTH_X}, y={TRUTH_Y}, z={TRUTH_Z}") - print(f" theta={np.degrees(TRUTH_THETA):.1f} deg, " - f"phi={np.degrees(TRUTH_PHI):.1f} deg, E={TRUTH_ENERGY} MeV") - print(f"N_SEGMENTS={N_SEGMENTS}, N_STEPS={N_STEPS}, LR={LR}") - print() - - # --- Load resources (shared across all runs) --- - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, - n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - sim_forward = _make_sim_forward(forward, log_T, dedx) - - # --- Generate truth signals --- - print("Compiling forward...", flush=True) - t0 = time.time() - truth_signals = jax.jit(sim_forward)( - jnp.array(TRUTH_PHYS, dtype=jnp.float32)) - for s in truth_signals: - jax.block_until_ready(s) - print(f" Compiled ({time.time()-t0:.1f}s)", flush=True) - - # --- Precompute Sobolev spectral weights --- - print("Precomputing Sobolev spectral weights (s=1.5)...", flush=True) - spec_weights_tuple = tuple( - make_sobolev_weight(*truth_signals[p].shape, s=1.5) for p in range(6) - ) - - # --- Loss + gradient --- - def loss_fn(norm_params): - sigs = sim_forward(to_physical(norm_params)) - return sobolev_loss_geomean(sigs, truth_signals, spec_weights_tuple) - - print("Compiling loss + gradient...", flush=True) - t0 = time.time() - loss_and_grad = jax.jit(jax.value_and_grad(loss_fn)) - dummy_init = jnp.array(make_init_phys(INIT_CONFIGS[0]) / SCALES, - dtype=jnp.float32) - _, dummy_g = loss_and_grad(dummy_init) - jax.block_until_ready(dummy_g) - print(f" Compiled ({time.time()-t0:.1f}s)", flush=True) - - # --- Run 4 optimizations --- - all_results = [] - all_labels = [] - total_t0 = time.time() - - for run_idx, cfg in enumerate(INIT_CONFIGS): - init_phys = make_init_phys(cfg) - init_theta = TRUTH_THETA + cfg['dtheta'] - init_phi = TRUTH_PHI + cfg['dphi'] - - print(f"\n{'='*70}") - print(f"Run {run_idx+1}/4: {cfg['label']}") - print(f" Init: x={init_phys[0]:.0f}, y={init_phys[1]:.0f}, " - f"z={init_phys[2]:.0f}, " - f"th={np.degrees(init_theta):.1f} deg, " - f"ph={np.degrees(init_phi):.1f} deg, " - f"E={init_phys[7]:.0f} MeV") - - phist, lhist = run_single_optimization(loss_and_grad, init_phys, run_idx) - all_results.append((phist, lhist)) - all_labels.append(cfg['label']) - - total_time = time.time() - total_t0 - print(f"\n{'='*70}") - print(f"All 4 optimizations complete in {total_time:.1f}s " - f"({total_time/4:.1f}s avg)") - - # --- Compute endpoints from param history --- - print(f"\nComputing track endpoints...", flush=True) - - @jax.jit - def get_endpoints(phys): - pos, de = generate_muon_segments_trig( - phys[7], jnp.array([phys[0], phys[1], phys[2]]), - phys[3], phys[4], phys[5], phys[6], - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de) - active = de > 0 - first_idx = jnp.argmax(active) - last_idx = N_SEGMENTS - 1 - jnp.argmax(active[::-1]) - return pos[first_idx], pos[last_idx] - - # Truth endpoints - truth_start, truth_end = get_endpoints( - jnp.array(TRUTH_PHYS, dtype=jnp.float32)) - truth_start = np.array(truth_start) - truth_end = np.array(truth_end) - - endpoints_starts = [] - endpoints_ends = [] - t0 = time.time() - - for ri, (phist, _) in enumerate(all_results): - starts = np.empty((N_STEPS + 1, 3)) - ends = np.empty((N_STEPS + 1, 3)) - for step in range(N_STEPS + 1): - ep_s, ep_e = get_endpoints( - jnp.array(phist[step], dtype=jnp.float32)) - jax.block_until_ready(ep_e) - starts[step] = np.array(ep_s) - ends[step] = np.array(ep_e) - endpoints_starts.append(starts) - endpoints_ends.append(ends) - elapsed = time.time() - t0 - print(f" Run {ri+1}/4 done ({elapsed:.0f}s)", flush=True) - - print(f" All endpoints computed in {time.time()-t0:.0f}s") - - # --- Save --- - out_path = os.path.join(OUT_DIR, 'multi_optimization_history.npz') - save_dict = { - 'truth_phys': TRUTH_PHYS, - 'truth_start': truth_start, - 'truth_end': truth_end, - 'scales': SCALES, - 'n_steps': N_STEPS, - 'lr': LR, - 'b1': B1, - 'b2': B2, - } - for i, (phist, lhist) in enumerate(all_results): - save_dict[f'param_history_{i}'] = phist - save_dict[f'loss_history_{i}'] = lhist - save_dict[f'init_phys_{i}'] = make_init_phys(INIT_CONFIGS[i]) - save_dict[f'label_{i}'] = all_labels[i] - save_dict[f'endpoints_starts_{i}'] = endpoints_starts[i] - save_dict[f'endpoints_ends_{i}'] = endpoints_ends[i] - np.savez(out_path, **save_dict) - print(f"Saved {out_path} ({os.path.getsize(out_path) / 1e3:.1f} KB)") - - # --- Plot --- - plot_multi_convergence(all_results, all_labels) - print("Done!") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/run_optimization.py b/closure/archive/muon_intermediate/run_optimization.py deleted file mode 100644 index 9029576..0000000 --- a/closure/archive/muon_intermediate/run_optimization.py +++ /dev/null @@ -1,253 +0,0 @@ -"""Run muon optimization(s) from specified initial guesses. - -Each run saves its own NPZ file. Can run one or many at a time. - -Usage: - python3 closure_analysis_muon/run_optimization.py A # single run - python3 closure_analysis_muon/run_optimization.py A B C D # all four - python3 closure_analysis_muon/run_optimization.py A --steps 800 --lr 0.02 -""" -import sys, os, argparse -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import optax -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments_trig, - mask_outside_volume, - build_muon_forward, -) - -# ============================================================================= -# Truth and constants -# ============================================================================= - -N_SEGMENTS = 4000 -STEP_SIZE_MM = 0.5 - -TRUTH_X = -200.0 -TRUTH_Y = 0.0 -TRUTH_Z = 100.0 -TRUTH_THETA = np.pi / 4 -TRUTH_PHI = np.pi / 6 -TRUTH_ENERGY = 500.0 - -TRUTH_PHYS = np.array([ - TRUTH_X, TRUTH_Y, TRUTH_Z, - np.sin(TRUTH_THETA), np.cos(TRUTH_THETA), - np.sin(TRUTH_PHI), np.cos(TRUTH_PHI), - TRUTH_ENERGY, -]) - -SCALES = np.array([200.0, 200.0, 200.0, 1.0, 1.0, 1.0, 1.0, 500.0]) -SCALES_JAX = jnp.array(SCALES, dtype=jnp.float32) - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -# Named initial guesses (perturbations from truth) -INIT_CONFIGS = { - 'A': {'dx': +400.0, 'dy': +300.0, 'dz': -300.0, - 'dtheta': +0.4, 'dphi': +0.4, 'dE': +100.0}, - 'B': {'dx': -300.0, 'dy': -400.0, 'dz': +400.0, - 'dtheta': -0.4, 'dphi': -0.4, 'dE': -100.0}, - 'C': {'dx': +500.0, 'dy': -300.0, 'dz': +200.0, - 'dtheta': +0.5, 'dphi': -0.3, 'dE': +150.0}, - 'D': {'dx': -200.0, 'dy': +500.0, 'dz': -400.0, - 'dtheta': -0.3, 'dphi': +0.5, 'dE': -150.0}, -} - -# ============================================================================= -# Helpers -# ============================================================================= - -def make_init_phys(cfg): - theta_init = TRUTH_THETA + cfg['dtheta'] - phi_init = TRUTH_PHI + cfg['dphi'] - return np.array([ - TRUTH_X + cfg['dx'], TRUTH_Y + cfg['dy'], TRUTH_Z + cfg['dz'], - np.sin(theta_init), np.cos(theta_init), - np.sin(phi_init), np.cos(phi_init), - TRUTH_ENERGY + cfg['dE'], - ]) - - -def project_unit_circle(p): - st, ct = p[3], p[4] - nt = jnp.maximum(jnp.sqrt(st**2 + ct**2), 1e-8) - sp, cp = p[5], p[6] - np_ = jnp.maximum(jnp.sqrt(sp**2 + cp**2), 1e-8) - return p.at[3].set(st/nt).at[4].set(ct/nt).at[5].set(sp/np_).at[6].set(cp/np_) - - -# ============================================================================= -# Setup (shared across runs) -# ============================================================================= - -def setup(): - """Compile everything, return loss_and_grad and truth data.""" - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, - n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - def fwd(phys): - pos, de = generate_muon_segments_trig( - phys[7], jnp.array([phys[0], phys[1], phys[2]]), - phys[3], phys[4], phys[5], phys[6], - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de) - sigs = forward(pos, de) - active = de > 0 - ep_start = jax.lax.stop_gradient(pos[jnp.argmax(active)]) - ep_end = jax.lax.stop_gradient(pos[N_SEGMENTS - 1 - jnp.argmax(active[::-1])]) - return sigs, ep_start, ep_end - - # Truth signals + endpoints - print("Compiling forward...", flush=True) - t0 = time.time() - truth_sigs, truth_start, truth_end = jax.jit(fwd)( - jnp.array(TRUTH_PHYS, dtype=jnp.float32)) - for s in truth_sigs: - jax.block_until_ready(s) - truth_start = np.array(truth_start) - truth_end = np.array(truth_end) - print(f" Done ({time.time()-t0:.1f}s)", flush=True) - - spec_w = tuple(make_sobolev_weight(*truth_sigs[p].shape, s=1.5) for p in range(6)) - - def loss_fn(n): - sigs, ep_start, ep_end = fwd(n * SCALES_JAX) - loss = sobolev_loss_geomean_log1p(sigs, truth_sigs, spec_w) - return loss, (ep_start, ep_end) - - print("Compiling loss + gradient...", flush=True) - t0 = time.time() - loss_and_grad = jax.jit(jax.value_and_grad(loss_fn, has_aux=True)) - dummy = jnp.array(TRUTH_PHYS / SCALES, dtype=jnp.float32) - (_, _), g = loss_and_grad(dummy) - jax.block_until_ready(g) - print(f" Done ({time.time()-t0:.1f}s)", flush=True) - - return loss_and_grad, truth_start, truth_end - - -# ============================================================================= -# Single optimization run -# ============================================================================= - -def run_one(loss_and_grad, init_phys, n_steps, lr, b1, b2): - """Run optimization, return (phist, lhist, ep_starts, ep_ends).""" - init_n = jnp.array(init_phys / SCALES, dtype=jnp.float32) - - (init_loss, (init_ep_s, init_ep_e)), init_grad = loss_and_grad(init_n) - jax.block_until_ready(init_grad) - print(f" Initial loss: {float(init_loss):.4f}") - - optimizer = optax.adam(learning_rate=lr, b1=b1, b2=b2) - opt_state = optimizer.init(init_n) - params = init_n - - phist = np.empty((n_steps + 1, 8)) - lhist = np.empty(n_steps + 1) - ep_starts = np.empty((n_steps + 1, 3)) - ep_ends = np.empty((n_steps + 1, 3)) - - phist[0] = np.array(params * SCALES_JAX) - lhist[0] = float(init_loss) - ep_starts[0] = np.array(init_ep_s) - ep_ends[0] = np.array(init_ep_e) - - t_start = time.time() - for step in range(n_steps): - (loss, (ep_s, ep_e)), grad = loss_and_grad(params) - updates, opt_state = optimizer.update(grad, opt_state, params) - params = optax.apply_updates(params, updates) - params = project_unit_circle(params) - - p = np.array(params * SCALES_JAX) - phist[step + 1] = p - lhist[step + 1] = float(loss) - ep_starts[step + 1] = np.array(ep_s) - ep_ends[step + 1] = np.array(ep_e) - - if (step + 1) % 50 == 0 or step == n_steps - 1: - th = np.degrees(np.arctan2(p[3], p[4])) - ph = np.degrees(np.arctan2(p[5], p[6])) - elapsed = time.time() - t_start - print(f" Step {step+1:4d}: loss={float(loss):.4f}, " - f"x={p[0]:7.1f} y={p[1]:7.1f} z={p[2]:7.1f} " - f"th={th:5.1f} ph={ph:5.1f} E={p[7]:6.1f} " - f"({elapsed:.0f}s)", flush=True) - - total = time.time() - t_start - print(f" Done in {total:.0f}s ({total/n_steps:.2f}s/step)") - return phist, lhist, ep_starts, ep_ends - - -# ============================================================================= -# Main -# ============================================================================= - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('inits', nargs='+', help='Init labels (A, B, C, D)') - parser.add_argument('--steps', type=int, default=600) - parser.add_argument('--lr', type=float, default=0.01) - parser.add_argument('--b1', type=float, default=0.9) - parser.add_argument('--b2', type=float, default=0.99) - args = parser.parse_args() - - for label in args.inits: - if label not in INIT_CONFIGS: - print(f"Unknown init '{label}'. Available: {list(INIT_CONFIGS.keys())}") - sys.exit(1) - - print(f"Runs: {args.inits}, steps={args.steps}, lr={args.lr}, " - f"b1={args.b1}, b2={args.b2}") - - loss_and_grad, truth_start, truth_end = setup() - - for label in args.inits: - cfg = INIT_CONFIGS[label] - init_phys = make_init_phys(cfg) - init_theta = TRUTH_THETA + cfg['dtheta'] - init_phi = TRUTH_PHI + cfg['dphi'] - - print(f"\n{'='*60}") - print(f"Run {label}: x={init_phys[0]:.0f} y={init_phys[1]:.0f} " - f"z={init_phys[2]:.0f} th={np.degrees(init_theta):.1f} " - f"ph={np.degrees(init_phi):.1f} E={init_phys[7]:.0f}") - - phist, lhist, ep_starts, ep_ends = run_one( - loss_and_grad, init_phys, args.steps, args.lr, args.b1, args.b2) - - out_path = os.path.join(OUT_DIR, f'optimization_{label}.npz') - np.savez(out_path, - label=label, - truth_phys=TRUTH_PHYS, - truth_start=truth_start, - truth_end=truth_end, - init_config=cfg, - n_steps=args.steps, - lr=args.lr, b1=args.b1, b2=args.b2, - param_history=phist, - loss_history=lhist, - endpoints_starts=ep_starts, - endpoints_ends=ep_ends) - print(f"Saved {out_path} ({os.path.getsize(out_path)/1e3:.1f} KB)") - - print("\nAll done!") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/run_optimization_save.py b/closure/archive/muon_intermediate/run_optimization_save.py deleted file mode 100644 index 362d178..0000000 --- a/closure/archive/muon_intermediate/run_optimization_save.py +++ /dev/null @@ -1,259 +0,0 @@ -""" -Run muon full-parameter optimization and save history to NPZ. - -Matches muon_full_optimization.py exactly, just saves param + loss history -instead of plotting, so GIF rendering can be done separately. - -Run from project root: - python3 closure_analysis_muon/run_optimization_save.py -""" - -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np -import optax -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean, make_sobolev_weight - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments_trig, - mask_outside_volume, - build_muon_forward, -) - -# ============================================================================= -# Configuration (identical to muon_full_optimization.py) -# ============================================================================= - -N_SEGMENTS = 4000 -STEP_SIZE_MM = 0.5 - -TRUTH_X = -200.0 -TRUTH_Y = 0.0 -TRUTH_Z = 100.0 -TRUTH_THETA = np.pi / 4 -TRUTH_PHI = np.pi / 6 -TRUTH_ENERGY = 500.0 - -TRUTH_SIN_THETA = np.sin(TRUTH_THETA) -TRUTH_COS_THETA = np.cos(TRUTH_THETA) -TRUTH_SIN_PHI = np.sin(TRUTH_PHI) -TRUTH_COS_PHI = np.cos(TRUTH_PHI) - -TRUTH_PHYS = np.array([ - TRUTH_X, TRUTH_Y, TRUTH_Z, - TRUTH_SIN_THETA, TRUTH_COS_THETA, - TRUTH_SIN_PHI, TRUTH_COS_PHI, - TRUTH_ENERGY, -]) - -SCALES = np.array([200.0, 200.0, 200.0, 1.0, 1.0, 1.0, 1.0, 500.0]) - -THETA_PERTURB = 0.5 -PHI_PERTURB = 0.5 -INIT_THETA = TRUTH_THETA + THETA_PERTURB -INIT_PHI = TRUTH_PHI + PHI_PERTURB - -INIT_PHYS = np.array([ - TRUTH_X + 100.0, - TRUTH_Y + 100.0, - TRUTH_Z - 100.0, - np.sin(INIT_THETA), - np.cos(INIT_THETA), - np.sin(INIT_PHI), - np.cos(INIT_PHI), - TRUTH_ENERGY + 100.0, -]) - -TRUTH_NORM = TRUTH_PHYS / SCALES -INIT_NORM = INIT_PHYS / SCALES - -N_STEPS = 300 -LR = 0.015 - -SCALES_JAX = jnp.array(SCALES, dtype=jnp.float32) -PARAM_NAMES = ['x', 'y', 'z', 'sin_th', 'cos_th', 'sin_ph', 'cos_ph', 'energy'] -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -# ============================================================================= -# Helpers (identical to muon_full_optimization.py) -# ============================================================================= - -def to_physical(norm_params): - return norm_params * SCALES_JAX - - -def project_unit_circle(norm_params): - st, ct = norm_params[3], norm_params[4] - norm_t = jnp.maximum(jnp.sqrt(st**2 + ct**2), 1e-8) - sp, cp = norm_params[5], norm_params[6] - norm_p = jnp.maximum(jnp.sqrt(sp**2 + cp**2), 1e-8) - return norm_params.at[3].set(st / norm_t).at[4].set(ct / norm_t) \ - .at[5].set(sp / norm_p).at[6].set(cp / norm_p) - - -def _make_sim_forward(forward, log_T, dedx): - """Build sim forward closure.""" - def sim_forward(phys): - pos, de = generate_muon_segments_trig( - phys[7], jnp.array([phys[0], phys[1], phys[2]]), - phys[3], phys[4], phys[5], phys[6], - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - de = mask_outside_volume(pos, de) - return forward(pos, de) - return sim_forward - - -# ============================================================================= -# Main -# ============================================================================= - -def main(): - print("=" * 70) - print("MUON OPTIMIZATION — SAVE HISTORY") - print("=" * 70) - print(f"Truth: x={TRUTH_X}, y={TRUTH_Y}, z={TRUTH_Z}") - print(f" theta={np.degrees(TRUTH_THETA):.1f} deg, " - f"phi={np.degrees(TRUTH_PHI):.1f} deg, E={TRUTH_ENERGY} MeV") - print(f"Init: x={INIT_PHYS[0]:.0f}, y={INIT_PHYS[1]:.0f}, z={INIT_PHYS[2]:.0f}") - print(f" theta={np.degrees(INIT_THETA):.1f} deg, " - f"phi={np.degrees(INIT_PHI):.1f} deg, E={INIT_PHYS[7]:.0f} MeV") - print(f"N_SEGMENTS={N_SEGMENTS}, N_STEPS={N_STEPS}, LR={LR}") - print() - - # --- Load resources --- - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, - n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - sim_forward = _make_sim_forward(forward, log_T, dedx) - - # --- Generate truth signals --- - print("Compiling forward...", flush=True) - t0 = time.time() - truth_signals = jax.jit(sim_forward)( - jnp.array(TRUTH_PHYS, dtype=jnp.float32)) - for s in truth_signals: - jax.block_until_ready(s) - print(f" Compiled ({time.time()-t0:.1f}s)", flush=True) - - # --- Precompute Sobolev spectral weights (s=1.5) --- - print("\nPrecomputing Sobolev spectral weights (s=1.5)...", flush=True) - spec_weights_tuple = tuple( - make_sobolev_weight(*truth_signals[p].shape, s=1.5) for p in range(6) - ) - - # --- Loss function (takes NORMALIZED params) --- - def loss_fn(norm_params): - sigs = sim_forward(to_physical(norm_params)) - return sobolev_loss_geomean(sigs, truth_signals, spec_weights_tuple) - - # --- Compile loss + grad --- - print("Compiling loss + gradient...", flush=True) - t0 = time.time() - loss_and_grad = jax.jit(jax.value_and_grad(loss_fn)) - init_n = jnp.array(INIT_NORM, dtype=jnp.float32) - init_loss, init_grad = loss_and_grad(init_n) - jax.block_until_ready(init_grad) - print(f" Compiled ({time.time()-t0:.1f}s)", flush=True) - print(f" Initial loss: {float(init_loss):.6f}") - - # --- Optimizer --- - optimizer = optax.adam(learning_rate=LR) - opt_state = optimizer.init(init_n) - - # --- Optimization loop --- - print(f"\nRunning {N_STEPS} optimization steps (LR={LR})...", flush=True) - params_n = init_n - - # History: N_STEPS+1 rows (row 0 = initial) - param_history_phys = np.empty((N_STEPS + 1, 8)) - loss_history = np.empty(N_STEPS + 1) - - param_history_phys[0] = np.array(to_physical(params_n)) - loss_history[0] = float(init_loss) - - t_start = time.time() - for step in range(N_STEPS): - loss, grad = loss_and_grad(params_n) - - updates, opt_state = optimizer.update(grad, opt_state, params_n) - params_n = optax.apply_updates(params_n, updates) - params_n = project_unit_circle(params_n) - - step_num = step + 1 - p = np.array(to_physical(params_n)) - param_history_phys[step_num] = p - loss_history[step_num] = float(loss) - - if step_num % 20 == 0 or step_num == N_STEPS: - eff_theta = float(jnp.arctan2(params_n[3], params_n[4])) - eff_phi = float(jnp.arctan2(params_n[5], params_n[6])) - elapsed = time.time() - t_start - print(f" Step {step_num:3d}: loss={float(loss):.6f}, " - f"x={p[0]:7.1f}, y={p[1]:7.1f}, z={p[2]:7.1f}, " - f"th={np.degrees(eff_theta):5.1f} deg, " - f"ph={np.degrees(eff_phi):5.1f} deg, " - f"E={p[7]:6.1f} MeV ({elapsed:.1f}s)", flush=True) - - total_time = time.time() - t_start - print(f"\nOptimization complete in {total_time:.1f}s " - f"({total_time/N_STEPS:.2f}s/step)") - - # --- Final results --- - final_phys = param_history_phys[-1] - eff_theta_final = np.arctan2(final_phys[3], final_phys[4]) - eff_phi_final = np.arctan2(final_phys[5], final_phys[6]) - - print(f"\n{'Parameter':<12} {'Truth':>10} {'Initial':>10} " - f"{'Final':>10} {'Delta':>10}") - print("-" * 55) - print(f"{'x (mm)':<12} {TRUTH_X:>10.1f} {INIT_PHYS[0]:>10.1f} " - f"{final_phys[0]:>10.1f} {final_phys[0]-TRUTH_X:>10.2f}") - print(f"{'y (mm)':<12} {TRUTH_Y:>10.1f} {INIT_PHYS[1]:>10.1f} " - f"{final_phys[1]:>10.1f} {final_phys[1]-TRUTH_Y:>10.2f}") - print(f"{'z (mm)':<12} {TRUTH_Z:>10.1f} {INIT_PHYS[2]:>10.1f} " - f"{final_phys[2]:>10.1f} {final_phys[2]-TRUTH_Z:>10.2f}") - print(f"{'theta (deg)':<12} {np.degrees(TRUTH_THETA):>10.1f} " - f"{np.degrees(INIT_THETA):>10.1f} " - f"{np.degrees(eff_theta_final):>10.1f} " - f"{np.degrees(eff_theta_final-TRUTH_THETA):>10.2f}") - print(f"{'phi (deg)':<12} {np.degrees(TRUTH_PHI):>10.1f} " - f"{np.degrees(INIT_PHI):>10.1f} " - f"{np.degrees(eff_phi_final):>10.1f} " - f"{np.degrees(eff_phi_final-TRUTH_PHI):>10.2f}") - print(f"{'E (MeV)':<12} {TRUTH_ENERGY:>10.1f} {INIT_PHYS[7]:>10.1f} " - f"{final_phys[7]:>10.1f} " - f"{final_phys[7]-TRUTH_ENERGY:>10.2f}") - - # --- Save history --- - out_path = os.path.join(OUT_DIR, 'optimization_history.npz') - np.savez( - out_path, - param_history_phys=param_history_phys, - loss_history=loss_history, - truth_phys=TRUTH_PHYS, - init_phys=INIT_PHYS, - scales=SCALES, - n_segments=N_SEGMENTS, - step_size_mm=STEP_SIZE_MM, - n_steps=N_STEPS, - lr=LR, - ) - print(f"\nSaved {out_path} ({os.path.getsize(out_path) / 1e3:.1f} KB)") - print("Done!") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/muon_intermediate/run_single_test.py b/closure/archive/muon_intermediate/run_single_test.py deleted file mode 100644 index 6b5825d..0000000 --- a/closure/archive/muon_intermediate/run_single_test.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Single run (Init A) for 1000 steps with convergence plot.""" -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax, jax.numpy as jnp, numpy as np, optax, time, matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, generate_muon_segments_trig, mask_outside_volume, build_muon_forward) - -N_SEGMENTS = 4000; STEP_SIZE_MM = 0.5 -N_STEPS = 600; LR = 0.01; B1 = 0.9; B2 = 0.99 -TRUTH_THETA = np.pi / 4; TRUTH_PHI = np.pi / 6 -TRUTH_PHYS = np.array([-200, 0, 100, np.sin(TRUTH_THETA), np.cos(TRUTH_THETA), - np.sin(TRUTH_PHI), np.cos(TRUTH_PHI), 500.0]) -SCALES = np.array([200, 200, 200, 1, 1, 1, 1, 500.0]) -SCALES_JAX = jnp.array(SCALES, dtype=jnp.float32) -INIT_PHYS = np.array([-200 + 400, 0 + 300, 100 - 300, - np.sin(TRUTH_THETA + 0.4), np.cos(TRUTH_THETA + 0.4), - np.sin(TRUTH_PHI + 0.4), np.cos(TRUTH_PHI + 0.4), 600.0]) -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -log_T, dedx = load_dedx_table_jax() -det = generate_detector('config/cubic_wireplane_config.yaml') -sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS) -forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - -def fwd(phys): - pos, de = generate_muon_segments_trig(phys[7], jnp.array([phys[0], phys[1], phys[2]]), - phys[3], phys[4], phys[5], phys[6], STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de) - sigs = forward(pos, de) - active = de > 0 - ep_start = jax.lax.stop_gradient(pos[jnp.argmax(active)]) - ep_end = jax.lax.stop_gradient(pos[N_SEGMENTS - 1 - jnp.argmax(active[::-1])]) - return sigs, ep_start, ep_end - -print('Compiling...', flush=True) -t0 = time.time() -truth_sigs, truth_start, truth_end = jax.jit(fwd)(jnp.array(TRUTH_PHYS, dtype=jnp.float32)) -for s in truth_sigs: jax.block_until_ready(s) -truth_start = np.array(truth_start); truth_end = np.array(truth_end) -spec_w = tuple(make_sobolev_weight(*truth_sigs[p].shape, s=1.5) for p in range(6)) - -def loss_fn(n): - sigs, ep_start, ep_end = fwd(n * SCALES_JAX) - loss = sobolev_loss_geomean_log1p(sigs, truth_sigs, spec_w) - return loss, (ep_start, ep_end) - -lg = jax.jit(jax.value_and_grad(loss_fn, has_aux=True)) -init_n = jnp.array(INIT_PHYS / SCALES, dtype=jnp.float32) -(l, _), g = lg(init_n); jax.block_until_ready(g) -print(f' All compiled ({time.time()-t0:.0f}s)', flush=True) - -def project_uc(p): - st, ct = p[3], p[4]; nt = jnp.maximum(jnp.sqrt(st**2 + ct**2), 1e-8) - sp, cp = p[5], p[6]; np_ = jnp.maximum(jnp.sqrt(sp**2 + cp**2), 1e-8) - return p.at[3].set(st/nt).at[4].set(ct/nt).at[5].set(sp/np_).at[6].set(cp/np_) - -opt = optax.adam(LR, b1=B1, b2=B2) -state = opt.init(init_n); params = init_n -phist = np.empty((N_STEPS + 1, 8)); lhist = np.empty(N_STEPS + 1) -ep_s = np.empty((N_STEPS + 1, 3)); ep_e = np.empty((N_STEPS + 1, 3)) -phist[0] = np.array(params * SCALES_JAX); lhist[0] = float(l) -# Get init endpoints -(_, (init_ep_s, init_ep_e)), _ = lg(init_n) -ep_s[0] = np.array(init_ep_s); ep_e[0] = np.array(init_ep_e) - -print(f'Running {N_STEPS} steps...', flush=True) -ts = time.time() -for step in range(N_STEPS): - (loss, (ep_start, ep_end)), grad = lg(params) - updates, state = opt.update(grad, state, params) - params = optax.apply_updates(params, updates) - params = project_uc(params) - p = np.array(params * SCALES_JAX) - phist[step + 1] = p; lhist[step + 1] = float(loss) - ep_s[step + 1] = np.array(ep_start); ep_e[step + 1] = np.array(ep_end) - if (step + 1) % 100 == 0: - th = np.degrees(np.arctan2(p[3], p[4])) - ph = np.degrees(np.arctan2(p[5], p[6])) - print(f' Step {step+1:4d}: loss={float(loss):.2f} x={p[0]:.0f} y={p[1]:.0f} z={p[2]:.0f} ' - f'th={th:.1f} ph={ph:.1f} E={p[7]:.0f} ({time.time()-ts:.0f}s)', flush=True) -print(f'Optimization done ({time.time()-ts:.0f}s)') - -# Save NPZ -out = os.path.join(OUT_DIR, 'multi_optimization_history.npz') -np.savez(out, truth_phys=TRUTH_PHYS, truth_start=truth_start, truth_end=truth_end, - n_steps=N_STEPS, loss_history_0=lhist, param_history_0=phist, - endpoints_starts_0=ep_s, endpoints_ends_0=ep_e) -print(f'Saved {out}') - -# Plot convergence -steps = np.arange(N_STEPS + 1) -fig, axes = plt.subplots(2, 3, figsize=(16, 10)) - -axes[0, 0].semilogy(steps, lhist, lw=1.5) -axes[0, 0].set_ylabel('Loss'); axes[0, 0].set_title('Loss'); axes[0, 0].grid(True, alpha=0.3) - -dr = np.sqrt((phist[:, 0] + 200)**2 + phist[:, 1]**2 + (phist[:, 2] - 100)**2) -axes[0, 1].semilogy(steps, dr + 1e-3, lw=1.5) -axes[0, 1].set_ylabel('|r-r_truth| mm'); axes[0, 1].set_title('Position Diff'); axes[0, 1].grid(True, alpha=0.3) - -dth = np.abs(np.degrees(np.arctan2(phist[:, 3], phist[:, 4]) - TRUTH_THETA)) -axes[0, 2].semilogy(steps, dth + 1e-4, lw=1.5) -axes[0, 2].set_ylabel('deg'); axes[0, 2].set_title('Theta Diff'); axes[0, 2].grid(True, alpha=0.3) - -dph = np.abs(np.degrees(np.arctan2(phist[:, 5], phist[:, 6]) - TRUTH_PHI)) -axes[1, 0].semilogy(steps, dph + 1e-4, lw=1.5) -axes[1, 0].set_ylabel('deg'); axes[1, 0].set_title('Phi Diff'); axes[1, 0].grid(True, alpha=0.3) - -dE = np.abs(phist[:, 7] - 500) -axes[1, 1].semilogy(steps, dE + 1e-3, lw=1.5) -axes[1, 1].set_ylabel('MeV'); axes[1, 1].set_title('Energy Diff'); axes[1, 1].grid(True, alpha=0.3) - -axes[1, 2].axis('off') -for ax in axes.flat: - if ax.get_visible(): - ax.set_xlabel('Step') - -fig.suptitle(f'Init A: {N_STEPS} steps, Adam LR={LR} b1={B1} b2={B2}\n' - f'Truth: x=-200, y=0, z=100, th=45, ph=30, E=500', fontsize=11, fontweight='bold') -fig.tight_layout(rect=[0, 0, 1, 0.93]) -fig.savefig(os.path.join(OUT_DIR, 'single_run_convergence.png'), dpi=150, bbox_inches='tight') -plt.close(fig) -print('Saved convergence plot') -print('All done!') diff --git a/closure/archive/muon_intermediate/test_csda_vs_scan.py b/closure/archive/muon_intermediate/test_csda_vs_scan.py deleted file mode 100644 index 863f468..0000000 --- a/closure/archive/muon_intermediate/test_csda_vs_scan.py +++ /dev/null @@ -1,294 +0,0 @@ -#!/usr/bin/env python3 -"""Compare CSDA parallel vs scan sequential muon segment generation. - -Tests: -1. Table consistency: verify dE/dx table integrates to CSDA range -2. Forward values (hard mode) — raw 82-pt table and densified 2000-pt table -3. Gradients (smooth mode) — both table densities -4. Speed: forward and value_and_grad timing -""" - -import jax -import jax.numpy as jnp -import numpy as np -import time -import sys -import os - -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - build_consistent_csda_table, - generate_muon_segments_scan, - generate_muon_segments_csda, - LAR_DENSITY, - _DEDX_FILE, -) - -# ---- Configuration ---- -STEP_SIZE_MM = 0.5 -N_SEGMENTS = 4000 -MIN_ENERGY = 10.0 -SMOOTH_T = 0.2 - -TEST_CASES = [ - ("Standard (500 MeV)", 500.0, 0.8, 1.2), - ("Low energy (50 MeV)", 50.0, 0.5, 0.3), - ("Near threshold (20 MeV)", 20.0, 1.0, 2.0), - ("High energy (5000 MeV)", 5000.0, 0.3, 0.7), -] - - -def _load_csda_table(n_dense=0): - """Load CSDA range table, optionally densified (no global cache).""" - data = np.loadtxt(_DEDX_FILE, delimiter=",", comments="#") - T_MeV = data[:, 0] - R_cm = data[:, 3] / LAR_DENSITY - if n_dense > 0: - log_T_raw = np.log(T_MeV) - log_T_d = np.linspace(log_T_raw[0], log_T_raw[-1], n_dense) - R_cm = np.interp(log_T_d, log_T_raw, R_cm) - T_MeV = np.exp(log_T_d) - return jnp.array(R_cm), jnp.array(T_MeV) - - -# ---- Table consistency check ---- -def check_table_consistency(): - data = np.loadtxt(_DEDX_FILE, delimiter=",", comments="#") - T = data[:, 0] - dedx = data[:, 2] * LAR_DENSITY - R_tab = data[:, 3] / LAR_DENSITY - - inv_dedx = 1.0 / dedx - R_int = np.zeros_like(T) - for i in range(1, len(T)): - R_int[i] = R_int[i-1] + 0.5 * (inv_dedx[i-1] + inv_dedx[i]) * (T[i] - T[i-1]) - - mask = T >= 10.0 - rel_err = np.abs(R_int[mask] - R_tab[mask]) / R_tab[mask] - print("Table consistency (trapezoidal integral of 1/dE/dx vs tabulated R):") - print(f" E >= 10 MeV: max rel err = {rel_err.max()*100:.2f}%, " - f"mean = {rel_err.mean()*100:.2f}%") - - -def _rel(a, b): - denom = max(abs(a), abs(b), 1e-12) - return abs(a - b) / denom * 100 - - -# ---- Forward comparison ---- -def compare_forward(name, energy, theta, phi, log_T, dedx, R_cm, T_MeV, - de_scan=None): - """Run CSDA forward and compare to scan result. Returns (de_scan, de_csda).""" - start = jnp.zeros(3) - E, th, ph = jnp.float32(energy), jnp.float32(theta), jnp.float32(phi) - - if de_scan is None: - _, de_scan = generate_muon_segments_scan( - E, start, th, ph, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, min_energy_mev=MIN_ENERGY, smooth_temperature=0.0) - jax.block_until_ready(de_scan) - - _, de_csda = generate_muon_segments_csda( - E, start, th, ph, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, R_cm, T_MeV) - jax.block_until_ready(de_csda) - - total_s = float(jnp.sum(de_scan)) - total_c = float(jnp.sum(de_csda)) - de_diff = jnp.abs(de_scan - de_csda) - - active_mask = de_scan > 0.01 # meaningful segments only - if jnp.any(active_mask): - max_rel = float(jnp.max(jnp.where( - active_mask, de_diff / jnp.maximum(de_scan, 1e-12), 0.0))) * 100 - else: - max_rel = 0.0 - - print(f" Total dE: scan={total_s:.4f}, csda={total_c:.4f} " - f"(rel {_rel(total_s, total_c):.4f}%)") - print(f" Max |dE_i| diff: {float(jnp.max(de_diff)):.6f} MeV, " - f"mean: {float(jnp.mean(de_diff)):.6f} MeV") - print(f" Max per-seg rel (dE>0.01): {max_rel:.2f}%") - - return de_scan, de_csda - - -# ---- Gradient comparison ---- -def compare_gradients(name, energy, theta, phi, log_T, dedx, R_cm, T_MeV): - start = jnp.zeros(3) - E, th, ph = jnp.float32(energy), jnp.float32(theta), jnp.float32(phi) - - def loss_scan_E(e): - _, de = generate_muon_segments_scan( - e, start, th, ph, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, min_energy_mev=MIN_ENERGY, - smooth_temperature=SMOOTH_T) - return jnp.sum(de) - - def loss_csda_E(e): - _, de = generate_muon_segments_csda( - e, start, th, ph, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, R_cm, T_MeV) - return jnp.sum(de) - - gse = float(jax.grad(loss_scan_E)(E)) - gce = float(jax.grad(loss_csda_E)(E)) - - def loss_scan_a(tv, pv): - pos, de = generate_muon_segments_scan( - E, start, tv, pv, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, min_energy_mev=MIN_ENERGY, - smooth_temperature=SMOOTH_T) - return jnp.sum(de * pos[:, 2]) - - def loss_csda_a(tv, pv): - pos, de = generate_muon_segments_csda( - E, start, tv, pv, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, R_cm, T_MeV) - return jnp.sum(de * pos[:, 2]) - - gst, gsp = [float(x) for x in jax.grad(loss_scan_a, argnums=(0, 1))(th, ph)] - gct, gcp = [float(x) for x in jax.grad(loss_csda_a, argnums=(0, 1))(th, ph)] - - print(f" d(sum(de))/dE: scan={gse: .6f} csda={gce: .6f} " - f"(rel {_rel(gse, gce):.2f}%)") - print(f" d(de*z)/dtheta: scan={gst: .2f} csda={gct: .2f} " - f"(rel {_rel(gst, gct):.2f}%)") - print(f" d(de*z)/dphi: scan={gsp: .2f} csda={gcp: .2f} " - f"(rel {_rel(gsp, gcp):.2f}%)") - - return dict(gse=gse, gce=gce, gst=gst, gct=gct) - - -# ---- Speed comparison ---- -def compare_speed(log_T, dedx, R_cm, T_MeV, n_runs=50): - start = jnp.zeros(3) - E, th, ph = jnp.float32(500.0), jnp.float32(0.8), jnp.float32(1.2) - - fwd_s = jax.jit(lambda e, t, p: generate_muon_segments_scan( - e, start, t, p, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, min_energy_mev=MIN_ENERGY, smooth_temperature=0.0)) - fwd_c = jax.jit(lambda e, t, p: generate_muon_segments_csda( - e, start, t, p, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, R_cm, T_MeV)) - - # Warm up - jax.block_until_ready(fwd_s(E, th, ph)) - jax.block_until_ready(fwd_c(E, th, ph)) - - t0 = time.perf_counter() - for _ in range(n_runs): - jax.block_until_ready(fwd_s(E, th, ph)) - ts = (time.perf_counter() - t0) / n_runs * 1000 - - t0 = time.perf_counter() - for _ in range(n_runs): - jax.block_until_ready(fwd_c(E, th, ph)) - tc = (time.perf_counter() - t0) / n_runs * 1000 - - print(f"\n Forward (500 MeV, hard, {n_runs} runs):") - print(f" Scan: {ts:.2f} ms CSDA: {tc:.2f} ms Speedup: {ts/max(tc,1e-6):.0f}x") - - # Gradient speed - gs = jax.jit(jax.value_and_grad(lambda e: jnp.sum(generate_muon_segments_scan( - e, start, th, ph, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, min_energy_mev=MIN_ENERGY, smooth_temperature=SMOOTH_T)[1]))) - gc = jax.jit(jax.value_and_grad(lambda e: jnp.sum(generate_muon_segments_csda( - e, start, th, ph, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, R_cm, T_MeV)[1]))) - - jax.block_until_ready(gs(E)) - jax.block_until_ready(gc(E)) - - t0 = time.perf_counter() - for _ in range(n_runs): - jax.block_until_ready(gs(E)) - tgs = (time.perf_counter() - t0) / n_runs * 1000 - - t0 = time.perf_counter() - for _ in range(n_runs): - jax.block_until_ready(gc(E)) - tgc = (time.perf_counter() - t0) / n_runs * 1000 - - print(f"\n value_and_grad(sum(de)) w.r.t. energy (smooth T={SMOOTH_T}):") - print(f" Scan: {tgs:.2f} ms CSDA: {tgc:.2f} ms Speedup: {tgs/max(tgc,1e-6):.0f}x") - - # Angle gradient speed - def _loss_s(t, p): - pos, de = generate_muon_segments_scan( - E, start, t, p, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, min_energy_mev=MIN_ENERGY, smooth_temperature=SMOOTH_T) - return jnp.sum(de * pos[:, 2]) - def _loss_c(t, p): - pos, de = generate_muon_segments_csda( - E, start, t, p, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, R_cm, T_MeV) - return jnp.sum(de * pos[:, 2]) - - gas = jax.jit(jax.value_and_grad(_loss_s, argnums=(0,))) - gac = jax.jit(jax.value_and_grad(_loss_c, argnums=(0,))) - jax.block_until_ready(gas(th, ph)) - jax.block_until_ready(gac(th, ph)) - - t0 = time.perf_counter() - for _ in range(n_runs): - jax.block_until_ready(gas(th, ph)) - tas = (time.perf_counter() - t0) / n_runs * 1000 - - t0 = time.perf_counter() - for _ in range(n_runs): - jax.block_until_ready(gac(th, ph)) - tac = (time.perf_counter() - t0) / n_runs * 1000 - - print(f"\n value_and_grad(sum(de*z)) w.r.t. theta:") - print(f" Scan: {tas:.2f} ms CSDA: {tac:.2f} ms Speedup: {tas/max(tac,1e-6):.0f}x") - - -def main(): - print(f"JAX devices: {jax.devices()}") - print(f"Config: step={STEP_SIZE_MM}mm, n={N_SEGMENTS}, min_E={MIN_ENERGY}MeV\n") - - check_table_consistency() - - log_T, dedx = load_dedx_table_jax() - R_pdg, T_pdg = _load_csda_table(n_dense=0) - R_con, T_con = build_consistent_csda_table(log_T, dedx, n_points=10000) - - tables = [ - ("82-pt PDG R column", R_pdg, T_pdg), - ("10k-pt integrated from dE/dx", R_con, T_con), - ] - - # ---- Forward ---- - for label, R_cm, T_MeV in tables: - print(f"\n{'='*60}") - print(f" FORWARD — {label}") - print(f"{'='*60}") - for name, energy, theta, phi in TEST_CASES: - print(f"\n {name}:") - compare_forward(name, energy, theta, phi, log_T, dedx, R_cm, T_MeV) - - # ---- Gradients ---- - for label, R_cm, T_MeV in tables: - print(f"\n{'='*60}") - print(f" GRADIENTS (smooth T={SMOOTH_T}) — {label}") - print(f"{'='*60}") - for name, energy, theta, phi in TEST_CASES: - print(f"\n {name}:") - compare_gradients(name, energy, theta, phi, log_T, dedx, R_cm, T_MeV) - - # ---- Speed (use consistent table) ---- - print(f"\n{'='*60}") - print(f" SPEED (10k-pt consistent table)") - print(f"{'='*60}") - compare_speed(log_T, dedx, R_con, T_con) - - print(f"\n{'='*60}") - print(" DONE") - print(f"{'='*60}") - - -if __name__ == "__main__": - main() diff --git a/closure/archive/muon_intermediate/test_table_density.py b/closure/archive/muon_intermediate/test_table_density.py deleted file mode 100644 index 03e5ea6..0000000 --- a/closure/archive/muon_intermediate/test_table_density.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python3 -"""Sweep n_points for the consistent CSDA table to find the sweet spot.""" - -import jax -import jax.numpy as jnp -import time -import sys -import os - -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - build_consistent_csda_table, - generate_muon_segments_scan, - generate_muon_segments_csda, -) - -STEP_SIZE_MM = 0.5 -N_SEGMENTS = 4000 -MIN_ENERGY = 10.0 -SMOOTH_T = 0.2 - -log_T, dedx = load_dedx_table_jax() -start = jnp.zeros(3) - -# Reference: scan results (compute once) -cases = [ - ("500 MeV", 500.0, 0.8, 1.2), - ("5000 MeV", 5000.0, 0.3, 0.7), - ("50 MeV", 50.0, 0.5, 0.3), - ("20 MeV", 20.0, 1.0, 2.0), -] - -print(f"{'n_pts':>8} | ", end="") -for name, *_ in cases: - print(f" {name:>10} fwd {name:>10} grad |", end="") -print(f" {'time ms':>8}") -print("-" * 140) - -scan_refs = {} -for name, energy, theta, phi in cases: - E, th, ph = jnp.float32(energy), jnp.float32(theta), jnp.float32(phi) - _, de_s = generate_muon_segments_scan( - E, start, th, ph, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, min_energy_mev=MIN_ENERGY, smooth_temperature=0.0) - jax.block_until_ready(de_s) - - g_s = float(jax.grad(lambda e: jnp.sum(generate_muon_segments_scan( - e, start, th, ph, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, min_energy_mev=MIN_ENERGY, - smooth_temperature=SMOOTH_T)[1]))(E)) - - scan_refs[name] = (float(jnp.sum(de_s)), g_s) - -for n_pts in [100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000]: - R_cm, T_MeV = build_consistent_csda_table(log_T, dedx, n_points=n_pts) - - row = f"{n_pts:>8} | " - for name, energy, theta, phi in cases: - E, th, ph = jnp.float32(energy), jnp.float32(theta), jnp.float32(phi) - ref_total, ref_grad = scan_refs[name] - - _, de_c = generate_muon_segments_csda( - E, start, th, ph, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, R_cm, T_MeV) - jax.block_until_ready(de_c) - total_c = float(jnp.sum(de_c)) - - g_c = float(jax.grad(lambda e: jnp.sum(generate_muon_segments_csda( - e, start, th, ph, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, R_cm, T_MeV)[1]))(E)) - - fwd_rel = abs(total_c - ref_total) / max(abs(ref_total), 1e-12) * 100 - grad_rel = abs(g_c - ref_grad) / max(abs(ref_grad), abs(g_c), 1e-12) * 100 - - row += f" {fwd_rel:>9.4f}% {grad_rel:>9.2f}% |" - - # Time one forward call (warm up already done from above) - fwd_jit = jax.jit(lambda e, t, p: generate_muon_segments_csda( - e, start, t, p, STEP_SIZE_MM, N_SEGMENTS, - log_T, dedx, R_cm, T_MeV)) - E0, th0, ph0 = jnp.float32(500.0), jnp.float32(0.8), jnp.float32(1.2) - jax.block_until_ready(fwd_jit(E0, th0, ph0)) - t0 = time.perf_counter() - for _ in range(20): - jax.block_until_ready(fwd_jit(E0, th0, ph0)) - ms = (time.perf_counter() - t0) / 20 * 1000 - - row += f" {ms:>7.2f}" - print(row) diff --git a/closure/archive/segments_intermediate/bench_step_time.py b/closure/archive/segments_intermediate/bench_step_time.py deleted file mode 100644 index d76066a..0000000 --- a/closure/archive/segments_intermediate/bench_step_time.py +++ /dev/null @@ -1,206 +0,0 @@ -""" -Benchmark: optimization step time vs number of segments. - -For each n_seg, JIT-compiles the grad function, runs 5 warmup steps, -then times 20 steps and reports mean ± std. - -Usage: - python3 closure_analysis_full/sweeps/bench_step_time.py -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import optax - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from closure_analysis_full.full_closure import DEFAULTS, build_loss_fn - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -SOBOLEV_S = 1.0 -WARMUP_STEPS = 5 -BENCH_STEPS = 20 - -NSEG_VALUES = [5000, 10000, 15000, 20000, 30000, 40000, 50000, 75000, 100000] - - -def main(): - print("Step time benchmark: n_seg vs time per step") - print(f"Warmup: {WARMUP_STEPS} steps, Bench: {BENCH_STEPS} steps\n") - - # Use a minimal truth signal — we just need shapes, not accuracy - # Generate from mpvmpr_20.h5 event 0 (already cached/fast) - from tools.loader import load_particle_step_data - deposit_data = load_particle_step_data('mpvmpr_20.h5', 0, verbose=False) - n_truth = deposit_data.positions_mm.shape[0] - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator( - detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, - include_electronics=False, include_track_hits=False, - recombination_model='modified_box') - response_signals, _ = sim_truth(deposit_data) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=SOBOLEV_S) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - - print("Truth signals ready.\n") - - results = [] - - for n_seg in NSEG_VALUES: - print(f"n_seg={n_seg:,}...", end=' ', flush=True) - - try: - # Build sim - sim_opt = DetectorSimulator( - detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward() - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Random init - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - replace = n_seg > n_truth - indices = rng.choice(n_truth, size=n_seg, replace=replace) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - params = jnp.array(np.column_stack([init_pos, init_de])) - - # JIT compile - t_compile = time.time() - (loss, _), grads = grad_fn(params) - jax.block_until_ready(grads) - compile_time = time.time() - t_compile - - # Optimizer - optimizer = optax.adam(0.5) - opt_state = optimizer.init(params) - - # Warmup steps (ignore timing) - for _ in range(WARMUP_STEPS): - (loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - params = optax.apply_updates(params, updates) - jax.block_until_ready(params) - - # Benchmark steps - step_times = [] - for _ in range(BENCH_STEPS): - t0 = time.time() - (loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - params = optax.apply_updates(params, updates) - jax.block_until_ready(params) - step_times.append(time.time() - t0) - - step_times = np.array(step_times) - mean_ms = step_times.mean() * 1000 - std_ms = step_times.std() * 1000 - - print(f"compile={compile_time:.1f}s, step={mean_ms:.1f} ± {std_ms:.1f} ms") - - results.append({ - 'n_seg': n_seg, - 'mean_ms': mean_ms, - 'std_ms': std_ms, - 'compile_s': compile_time, - 'step_times': step_times, - }) - - except Exception as e: - print(f"FAILED: {e}") - results.append({ - 'n_seg': n_seg, - 'mean_ms': float('nan'), - 'std_ms': float('nan'), - 'compile_s': float('nan'), - }) - - # Summary table - print(f"\n{'='*60}") - print(f"{'n_seg':>10} {'Step (ms)':>12} {'± (ms)':>10} {'Compile (s)':>12}") - print(f"{'-'*60}") - for r in results: - print(f"{r['n_seg']:>10,} {r['mean_ms']:>12.1f} {r['std_ms']:>10.1f} " - f"{r['compile_s']:>12.1f}") - - # Plot - valid = [r for r in results if not np.isnan(r['mean_ms'])] - n_segs = [r['n_seg'] for r in valid] - means = [r['mean_ms'] for r in valid] - stds = [r['std_ms'] for r in valid] - compiles = [r['compile_s'] for r in valid] - - fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5)) - - # Left: step time vs n_seg - ax1.errorbar(n_segs, means, yerr=stds, fmt='o-', color='#2196F3', - capsize=4, capthick=1.5, markersize=7, linewidth=2, - label='Mean ± 1σ') - ax1.set_xlabel('Number of Segments', fontsize=13) - ax1.set_ylabel('Time per Step (ms)', fontsize=13) - ax1.set_title('Optimization Step Time vs Segment Count', fontsize=14, fontweight='bold') - ax1.tick_params(labelsize=11) - ax1.grid(True, alpha=0.3) - ax1.legend(fontsize=11) - - # Add throughput annotation - for i, r in enumerate(valid): - throughput = r['n_seg'] / r['mean_ms'] * 1000 # segs/sec - if i % 2 == 0 or i == len(valid) - 1: - ax1.annotate(f'{throughput/1e6:.1f}M seg/s', - (r['n_seg'], r['mean_ms']), - textcoords="offset points", xytext=(0, 12), - fontsize=8, ha='center', color='gray') - - # Right: compile time vs n_seg - ax2.plot(n_segs, compiles, 's-', color='#FF5722', markersize=7, linewidth=2) - ax2.set_xlabel('Number of Segments', fontsize=13) - ax2.set_ylabel('JIT Compile Time (s)', fontsize=13) - ax2.set_title('JIT Compilation Time vs Segment Count', fontsize=14, fontweight='bold') - ax2.tick_params(labelsize=11) - ax2.grid(True, alpha=0.3) - - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'bench_step_time.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f"\nSaved {fname}") - - # Save data - save_path = os.path.join(OUT_DIR, 'bench_step_time.npz') - np.savez(save_path, - n_segs=np.array(n_segs), - means_ms=np.array(means), - stds_ms=np.array(stds), - compiles_s=np.array(compiles)) - print(f"Saved {save_path}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/check_out_h5.py b/closure/archive/segments_intermediate/check_out_h5.py deleted file mode 100644 index 387dae6..0000000 --- a/closure/archive/segments_intermediate/check_out_h5.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Check out.h5 structure and event sizes.""" -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) -import numpy as np -from tools.loader import load_particle_step_data - -for ev in range(5): - try: - d = load_particle_step_data('out.h5', event_idx=ev, verbose=False) - n = d.positions_mm.shape[0] - dx = np.asarray(d.dx) - de = np.asarray(d.de) - pos = np.asarray(d.positions_mm) - print(f'Event {ev}: {n:,} segs, total_dE={de.sum():.1f} MeV, ' - f'dx mean={dx.mean():.4f} median={np.median(dx):.4f} max={dx.max():.4f} mm, ' - f'x=[{pos[:,0].min():.0f},{pos[:,0].max():.0f}]') - except Exception as e: - print(f'Event {ev}: {e}') - break diff --git a/closure/archive/segments_intermediate/check_q_ratio.py b/closure/archive/segments_intermediate/check_q_ratio.py deleted file mode 100644 index 7fbc6a5..0000000 --- a/closure/archive/segments_intermediate/check_q_ratio.py +++ /dev/null @@ -1,89 +0,0 @@ -"""Check: is total Q correct even though total dE is high?""" -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) -import numpy as np -from tools.loader import load_particle_step_data - -DX_MM = 0.3 -DX_CM = DX_MM / 10.0 -ALPHA = 0.93 -BETA = 0.212 -LAR_DENSITY = 1.396 - -from tools.geometry import generate_detector -detector_config = generate_detector('config/cubic_wireplane_config.yaml') -field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 -B_EFF = BETA / LAR_DENSITY / field_kVcm - -def de_to_Q(de, dx_cm): - return (dx_cm / B_EFF) * np.log(ALPHA + B_EFF * de / dx_cm) - -# Truth -deposit_data = load_particle_step_data('out.h5', event_idx=2, verbose=False) -truth_de = np.asarray(deposit_data.de) -n_truth = len(truth_de) -truth_Q = de_to_Q(truth_de, DX_CM) -total_truth_Q = truth_Q.sum() -total_truth_dE = truth_de.sum() - -print(f"=== TRUTH ===") -print(f" N segments: {n_truth:,}") -print(f" Total dE: {total_truth_dE:.1f} MeV") -print(f" Total Q: {total_truth_Q:.1f}") -print(f" Mean dE: {truth_de.mean():.6f} MeV") -print(f" Mean Q: {truth_Q.mean():.6f}") - -# Optimizer final state -data = np.load('closure_analysis_full/sweeps/run_out_50k.npz') -final_params = data['final_params'] -sim_de = final_params[:, 3] -alive = sim_de > 0.012 -n_alive = alive.sum() -n_dead = (~alive).sum() - -sim_Q = de_to_Q(sim_de, DX_CM) -sim_Q_alive = sim_Q[alive] - -total_sim_Q = sim_Q.sum() -total_sim_Q_alive = sim_Q_alive.sum() -total_sim_dE = sim_de.sum() -total_sim_dE_alive = sim_de[alive].sum() - -print(f"\n=== OPTIMIZER (final) ===") -print(f" N segments: {len(sim_de):,} ({n_alive:,} alive, {n_dead:,} dead)") -print(f" Total dE: {total_sim_dE:.1f} MeV") -print(f" Total Q: {total_sim_Q:.1f}") -print(f" Total Q (alive only): {total_sim_Q_alive:.1f}") -print(f" Mean dE (alive): {sim_de[alive].mean():.6f} MeV") -print(f" Mean Q (alive): {sim_Q_alive.mean():.6f}") - -print(f"\n=== RATIOS ===") -print(f" dE ratio (total): {total_sim_dE / total_truth_dE:.3f}") -print(f" Q ratio (total): {total_sim_Q / total_truth_Q:.3f}") -print(f" Q ratio (alive): {total_sim_Q_alive / total_truth_Q:.3f}") - -# What dE_ratio would give Q_ratio=1.0? -# If all alive segments had uniform dE: -# n_alive * Q(dE_uniform) = total_truth_Q -# Q(dE_uniform) = total_truth_Q / n_alive -Q_target_per = total_truth_Q / n_alive -# Invert: dE = (dx/B) * (exp(B*Q/dx) - alpha) -dE_target = (DX_CM / B_EFF) * (np.exp(B_EFF * Q_target_per / DX_CM) - ALPHA) -total_dE_target = n_alive * dE_target + n_dead * 0.012 -dE_ratio_at_Q1 = total_dE_target / total_truth_dE - -print(f"\n=== EXPECTED dE RATIO FOR Q_ratio=1.0 ===") -print(f" If {n_alive:,} alive segments produce truth total Q:") -print(f" Q per alive segment needed: {Q_target_per:.6f}") -print(f" dE per alive segment needed: {dE_target:.6f} MeV") -print(f" Total dE: {total_dE_target:.1f} MeV") -print(f" dE ratio: {dE_ratio_at_Q1:.3f}") -print(f" This is the EXPECTED dE ratio — not a bug!") - -# Verify with per-percentile -print(f"\n=== dE vs Q DISTRIBUTION ===") -print(f" {'Percentile':>12} {'dE (MeV)':>12} {'Q':>12} {'Q/dE':>8}") -for p in [50, 90, 95, 99, 99.9]: - de_p = np.percentile(sim_de[alive], p) - q_p = de_to_Q(de_p, DX_CM) - print(f" {p:>12.1f} {de_p:>12.6f} {q_p:>12.6f} {q_p/de_p:>8.3f}") diff --git a/closure/archive/segments_intermediate/check_tracks.py b/closure/archive/segments_intermediate/check_tracks.py deleted file mode 100644 index 09dba14..0000000 --- a/closure/archive/segments_intermediate/check_tracks.py +++ /dev/null @@ -1,57 +0,0 @@ -"""Check track structure in out.h5 event 2.""" -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) -import numpy as np -from tools.loader import load_particle_step_data - -d = load_particle_step_data('out.h5', event_idx=2, verbose=False) -track_ids = np.asarray(d.track_ids) -pos = np.asarray(d.positions_mm) -de = np.asarray(d.de) -n = len(de) - -unique_tracks, counts = np.unique(track_ids, return_counts=True) -n_tracks = len(unique_tracks) - -print(f"Event 2: {n:,} segments, {n_tracks:,} tracks") -print(f"\nTrack size distribution:") -print(f" min: {counts.min()}") -print(f" median: {int(np.median(counts))}") -print(f" mean: {counts.mean():.1f}") -print(f" max: {counts.max()}") -for p in [10, 25, 50, 75, 90, 95, 99]: - print(f" {p}th: {int(np.percentile(counts, p))}") - -print(f"\nTrack spatial extent (max-min per track):") -extents = [] -for tid in unique_tracks[:500]: # sample first 500 tracks - mask = track_ids == tid - if mask.sum() < 2: - continue - t_pos = pos[mask] - extent = t_pos.max(axis=0) - t_pos.min(axis=0) - extents.append(np.linalg.norm(extent)) -extents = np.array(extents) -print(f" Sampled {len(extents)} tracks with ≥2 segments") -print(f" min extent: {extents.min():.1f} mm") -print(f" median extent: {np.median(extents):.1f} mm") -print(f" mean extent: {extents.mean():.1f} mm") -print(f" max extent: {extents.max():.1f} mm") -for p in [10, 25, 50, 75, 90, 95, 99]: - print(f" {p}th: {np.percentile(extents, p):.1f} mm") - -print(f"\nTotal dE by track size:") -big = counts >= 100 -med = (counts >= 10) & (counts < 100) -small = counts < 10 -print(f" Large (≥100 segs): {big.sum()} tracks, {sum(counts[big]):,} segs, " - f"{sum(de[np.isin(track_ids, unique_tracks[big])]):.1f} MeV") -print(f" Medium (10-99): {med.sum()} tracks, {sum(counts[med]):,} segs, " - f"{sum(de[np.isin(track_ids, unique_tracks[med])]):.1f} MeV") -print(f" Small (<10): {small.sum()} tracks, {sum(counts[small]):,} segs, " - f"{sum(de[np.isin(track_ids, unique_tracks[small])]):.1f} MeV") - -print(f"\n50mm jitter context:") -print(f" Wire pitch: 3mm → 50mm = {50/3:.0f} wire pitches") -print(f" Median track extent: {np.median(extents):.0f}mm") -print(f" 50mm jitter / median extent: {50/np.median(extents)*100:.0f}%") diff --git a/closure/archive/segments_intermediate/check_tracks2.py b/closure/archive/segments_intermediate/check_tracks2.py deleted file mode 100644 index e47d76b..0000000 --- a/closure/archive/segments_intermediate/check_tracks2.py +++ /dev/null @@ -1,34 +0,0 @@ -"""Detailed track size histogram.""" -import sys, os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) -import numpy as np -from tools.loader import load_particle_step_data - -d = load_particle_step_data('out.h5', event_idx=2, verbose=False) -track_ids = np.asarray(d.track_ids) -de = np.asarray(d.de) - -unique_tracks, counts = np.unique(track_ids, return_counts=True) - -print(f"{'N segs':>8} {'N tracks':>10} {'Total segs':>12} {'Total dE (MeV)':>15} {'% of dE':>8}") -print("-" * 58) - -for n in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: - mask = counts == n - n_tracks = mask.sum() - n_segs = n * n_tracks - track_mask = np.isin(track_ids, unique_tracks[mask]) - total_de = de[track_mask].sum() - pct = total_de / de.sum() * 100 - print(f"{n:>8} {n_tracks:>10} {n_segs:>12} {total_de:>15.1f} {pct:>8.1f}%") - -for lo, hi in [(11, 20), (21, 50), (51, 100), (101, 500), (501, 1000), (1001, 5000), (5001, 100000)]: - mask = (counts >= lo) & (counts <= hi) - n_tracks = mask.sum() - n_segs = counts[mask].sum() - track_mask = np.isin(track_ids, unique_tracks[mask]) - total_de = de[track_mask].sum() - pct = total_de / de.sum() * 100 - print(f"{lo}-{hi:>5} {n_tracks:>10} {n_segs:>12} {total_de:>15.1f} {pct:>8.1f}%") - -print(f"\n{'Total':>8} {len(unique_tracks):>10} {len(de):>12} {de.sum():>15.1f} {'100.0':>8}%") diff --git a/closure/archive/segments_intermediate/plot_progression_v2.py b/closure/archive/segments_intermediate/plot_progression_v2.py deleted file mode 100644 index ad95e35..0000000 --- a/closure/archive/segments_intermediate/plot_progression_v2.py +++ /dev/null @@ -1,186 +0,0 @@ -""" -Corrected progression plot with dE waterfall as 6th panel. -Waterfall: x=step, y=dE (keV), color=count. Dead row at bottom, overflow at top. - -Usage: - python3 closure_analysis_full/sweeps/plot_progression_v2.py -""" - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib.colors as mcolors -import os - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -DATA_PATH = os.path.join(OUT_DIR, 'best_final.npz') -PLANE_NAMES = ['east_U', 'east_V', 'east_Y', 'west_U', 'west_V', 'west_Y'] -DEATH_THRESH = 0.012 # MeV - - -def main(): - print("Loading data...") - data = np.load(DATA_PATH, allow_pickle=True) - - losses = data['losses'] - active_planes = list(data['active_planes']) - n_de_hist = int(data['n_de_hist']) - de_history_steps = data['de_history_steps'] - n_signal_snapshots = int(data['n_signal_snapshots']) - signal_steps = data['signal_steps'] - - # Reconstruct dE history - de_history = [] - for i in range(n_de_hist): - alive_de = data[f'de_hist_{i}_alive'] - n_dead = int(data[f'de_hist_{i}_dead']) - de_history.append((alive_de, n_dead)) - - # Load profiles - truth_profiles = {} - sim_profiles = {} - for p in active_planes: - truth_profiles[p] = data[f'truth_profile_{p}'] - sim_profiles[p] = [data[f'sig_profile_{p}_{j}'] for j in range(n_signal_snapshots)] - - # Q ratios (recompute from losses metadata — approximate from printed) - # Just use step markers for now - - # ===================================================================== - # Build waterfall data - # ===================================================================== - all_alive_kev = np.concatenate([h[0] * 1000 for h in de_history]) - p99_kev = np.percentile(all_alive_kev, 99) - n_bins = 80 - bin_edges_kev = np.linspace(DEATH_THRESH * 1000, p99_kev, n_bins + 1) - bin_centers_kev = 0.5 * (bin_edges_kev[:-1] + bin_edges_kev[1:]) - - # Waterfall: columns = steps, rows = dE bins + dead row + overflow row - # Layout: row 0 = overflow (top), rows 1..n_bins = dE bins (high to low), row n_bins+1 = dead (bottom) - n_steps_hist = len(de_history) - waterfall = np.zeros((n_bins + 2, n_steps_hist)) - - for j, (alive_de, n_dead) in enumerate(de_history): - alive_kev = alive_de * 1000 - hist, _ = np.histogram(alive_kev, bins=bin_edges_kev) - overflow = int(np.sum(alive_kev > p99_kev)) - waterfall[0, j] = overflow # top row = overflow - waterfall[1:n_bins+1, j] = hist[::-1] # flip so high dE is at top - waterfall[n_bins+1, j] = n_dead # bottom row = dead - - # ===================================================================== - # Plot 3x2 - # ===================================================================== - fig, axes = plt.subplots(3, 2, figsize=(18, 20)) - - # (0,0) Loss - ax = axes[0, 0] - ax.semilogy(losses, 'b-', lw=1.0, alpha=0.7) - ax.set_xlabel('Step', fontsize=14); ax.set_ylabel('Loss', fontsize=14) - ax.set_title('Loss', fontsize=15); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # (0,1) dE Waterfall - ax = axes[0, 1] - # y-axis: dE from death_thresh to p99, plus dead and overflow bands - # Use pcolormesh for proper axis mapping - step_arr = np.array(de_history_steps) - - # Build y-axis: dead band | dE bins | overflow band - dead_band = 1 # fraction of dE range for dead band - over_band = 1 - y_edges = np.concatenate([ - [0], # dead bottom - [DEATH_THRESH * 1000], # dead top = dE start - bin_edges_kev, # dE bins - [p99_kev + (p99_kev - DEATH_THRESH * 1000) * 0.05], # overflow - ]) - - # For imshow: transpose so x=step, y=dE - # waterfall shape is (n_bins+2, n_steps) — already correct for imshow with y=row - # But we want y=0 at bottom (dead), y=max at top (overflow) - # imshow origin='lower' handles this - - # imshow: x=step, y=dE. Data is (n_bins, n_steps), need to show with origin='lower' - de_data = waterfall[1:n_bins+1, :] # just dE bins, shape (n_bins, n_steps) - im = ax.imshow(de_data, aspect='auto', origin='lower', - extent=[step_arr[0], step_arr[-1], - DEATH_THRESH * 1000, p99_kev], - cmap='hot', norm=mcolors.LogNorm(vmin=1, vmax=max(de_data.max(), 2))) - - # Dead count as a separate colored band at the bottom - dead_counts = waterfall[n_bins+1, :] - ax2 = ax.twinx() - ax2.fill_between(step_arr, 0, dead_counts, alpha=0.4, color='cyan', label='Dead count') - ax2.set_ylabel('Dead segments', fontsize=11, color='cyan') - ax2.tick_params(axis='y', labelcolor='cyan', labelsize=10) - ax2.set_ylim(0, max(dead_counts) * 1.3 if max(dead_counts) > 0 else 1) - - ax.set_xlabel('Step', fontsize=14) - ax.set_ylabel('dE (keV)', fontsize=14) - ax.set_title(f'Segment dE Distribution (99th %ile = {p99_kev:.0f} keV)', fontsize=14) - cbar = fig.colorbar(im, ax=ax, label='Count', pad=0.12) - ax.tick_params(labelsize=11) - - # (1,0) West U - ax = axes[1, 0] - p = 3 - if p in active_planes: - t_prof = truth_profiles[p] - r_prof = sim_profiles[p][-1] - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # (1,1) West V - ax = axes[1, 1] - p = 4 - if p in active_planes: - t_prof = truth_profiles[p] - r_prof = sim_profiles[p][-1] - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # (2,0) West Y - ax = axes[2, 0] - p = 5 - if p in active_planes: - t_prof = truth_profiles[p] - r_prof = sim_profiles[p][-1] - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # (2,1) Overflow + dead summary - ax = axes[2, 1] - overflow_counts = waterfall[0, :] - ax.plot(step_arr, dead_counts, 'c-', lw=2, label='Dead segments') - ax.plot(step_arr, overflow_counts, 'r-', lw=2, label=f'Overflow (>{p99_kev:.0f} keV)') - ax.set_xlabel('Step', fontsize=14) - ax.set_ylabel('Count', fontsize=14) - ax.set_title('Dead & Overflow Segments', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - fig.suptitle(f'Best Final | 50k segs, s=1.0, lr=1.0, reloc 25/1000\n' - f'loss={losses[-1]:.6f}', - fontsize=15, fontweight='bold') - fig.tight_layout(rect=[0, 0, 1, 0.96]) - fname = os.path.join(OUT_DIR, 'best_final_progression_v2.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/precompute_signals.py b/closure/archive/segments_intermediate/precompute_signals.py deleted file mode 100644 index 741f6e2..0000000 --- a/closure/archive/segments_intermediate/precompute_signals.py +++ /dev/null @@ -1,111 +0,0 @@ -""" -Precompute wire signals from saved checkpoint params. -Saves per-plane 2D signal arrays at selected steps for visualization. - -Usage: - python3 closure_analysis_full/sweeps/precompute_signals.py -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np - -from tools.geometry import generate_detector -from tools.config import SegmentData, DepositData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -DATA_PATH = os.path.join(OUT_DIR, 'best_final.npz') -DX_MM = 0.3 -FRAME_EVERY = 5 # every 5th checkpoint = every 50 steps - - -def main(): - print("Loading checkpoint data...") - data = np.load(DATA_PATH, allow_pickle=True) - checkpoint_params = data['checkpoint_params'] - checkpoint_steps = data['checkpoint_steps'] - checkpoint_losses = data['checkpoint_losses'] - n_seg = int(data['n_seg']) - active_planes = list(data['active_planes']) - - frame_indices = list(range(0, len(checkpoint_steps), FRAME_EVERY)) - if frame_indices[-1] != len(checkpoint_steps) - 1: - frame_indices.append(len(checkpoint_steps) - 1) - n_frames = len(frame_indices) - print(f" {len(checkpoint_steps)} checkpoints → {n_frames} frames") - - # Setup - deposit_data = load_particle_step_data('out.h5', 2) - n_truth = deposit_data.positions_mm.shape[0] - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - # Truth signals - forced_deposit = DepositData( - positions_mm=deposit_data.positions_mm, de=deposit_data.de, - dx=np.full(n_truth, DX_MM, dtype=np.float32), - valid_mask=deposit_data.valid_mask, theta=deposit_data.theta, - phi=deposit_data.phi, track_ids=deposit_data.track_ids) - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - print("Computing truth signals...") - response_signals, _ = sim_truth(forced_deposit) - - truth_signals = {} - for (side, plane), signal in response_signals.items(): - truth_signals[(side, plane)] = np.array(signal) - - # Optimizer forward - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward(dx_mm=DX_MM) - - # JIT warmup - seg0 = SegmentData( - positions_mm=jnp.array(checkpoint_params[0][:, :3]), - de=jnp.array(checkpoint_params[0][:, 3])) - _ = fwd_opt(seg0) - for s in fwd_opt(seg0): - jax.block_until_ready(s) - print("JIT ready.\n") - - # Precompute signals at each frame - print(f"Computing {n_frames} forward passes...") - save_data = { - 'frame_steps': np.array([checkpoint_steps[ci] for ci in frame_indices]), - 'frame_losses': np.array([checkpoint_losses[ci] for ci in frame_indices]), - 'n_frames': n_frames, - 'active_planes': np.array(active_planes), - } - - # Save truth signals - for (side, plane), sig in truth_signals.items(): - save_data[f'truth_{side}_{plane}'] = sig - - t0 = time.time() - for fi, ci in enumerate(frame_indices): - params = checkpoint_params[ci] - seg = SegmentData( - positions_mm=jnp.array(params[:, :3]), - de=jnp.array(params[:, 3])) - recon = fwd_opt(seg) - - for pidx in active_planes: - side, plane = pidx // 3, pidx % 3 - save_data[f'sim_{fi}_{side}_{plane}'] = np.array(recon[pidx]) - - if fi % 5 == 0 or fi == n_frames - 1: - print(f" Frame {fi+1}/{n_frames} (step {checkpoint_steps[ci]}) — {time.time()-t0:.0f}s") - - save_path = os.path.join(OUT_DIR, 'precomputed_signals.npz') - np.savez_compressed(save_path, **save_data) - print(f"\nSaved to {save_path} ({os.path.getsize(save_path)/1e6:.1f} MB)") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/render_3d_20k.py b/closure/archive/segments_intermediate/render_3d_20k.py deleted file mode 100644 index 52647ad..0000000 --- a/closure/archive/segments_intermediate/render_3d_20k.py +++ /dev/null @@ -1,157 +0,0 @@ -"""3D annihilation plot for 20k segment run.""" - -import numpy as np -import matplotlib.pyplot as plt -from matplotlib.colors import TwoSlopeNorm -import matplotlib.animation as animation -import os, time - -DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'best_run_20k_4000.npz') -OUT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'annihilation_3d_20k.gif') - -VOXEL_SIZE = 25.0 -MIN_DIFF = 0.005 -MAX_POINT_SIZE = 80 -FPS = 50 -DPI = 120 - - -def voxelize_vectorized(positions, energies, voxel_size, origin): - idx = ((positions - origin) / voxel_size).astype(np.int64) - keys = idx[:, 0] * 1_000_000 + idx[:, 1] * 1_000 + idx[:, 2] - unique_keys, inverse = np.unique(keys, return_inverse=True) - vox_de = np.zeros(len(unique_keys)) - np.add.at(vox_de, inverse, energies) - vox_idx = np.zeros((len(unique_keys), 3), dtype=np.int64) - for i, k in enumerate(unique_keys): - vox_idx[i] = [k // 1_000_000, (k % 1_000_000) // 1_000, k % 1_000] - centers = origin + (vox_idx + 0.5) * voxel_size - return dict(zip(unique_keys.tolist(), - zip(vox_de.tolist(), centers[:, 0].tolist(), - centers[:, 1].tolist(), centers[:, 2].tolist()))) - - -def main(): - print("Loading data...") - data = np.load(DATA_PATH) - truth_pos = data['truth_pos'] - truth_de = data['truth_de'] - checkpoint_params = data['checkpoint_params'] - checkpoint_steps = data['checkpoint_steps'] - checkpoint_losses = data['checkpoint_losses'] - n_seg = int(data['n_seg']) - - n_frames = len(checkpoint_steps) - print(f" {n_frames} checkpoints, {n_seg} segments") - - all_pos_min = np.minimum(truth_pos.min(axis=0), - checkpoint_params[:, :, :3].reshape(-1, 3).min(axis=0)) - origin = all_pos_min - VOXEL_SIZE - - print("Voxelizing truth...") - truth_voxels = voxelize_vectorized(truth_pos, truth_de, VOXEL_SIZE, origin) - print(f" {len(truth_voxels)} truth voxels") - - print("Computing frame data...") - t0 = time.time() - frame_data = [] - global_max_diff = 0 - - for i in range(n_frames): - params = checkpoint_params[i] - alive = params[:, 3] > 0.001 - sim_voxels = voxelize_vectorized(params[alive, :3], params[alive, 3], - VOXEL_SIZE, origin) - all_keys = set(truth_voxels.keys()) | set(sim_voxels.keys()) - diffs = [] - for k in all_keys: - t_de = truth_voxels.get(k, (0,0,0,0))[0] - s_de = sim_voxels.get(k, (0,0,0,0))[0] - diff = t_de - s_de - if abs(diff) < MIN_DIFF: - continue - c = truth_voxels[k] if k in truth_voxels else sim_voxels[k] - diffs.append((c[1], c[2], c[3], diff)) - - if diffs: - arr = np.array(diffs) - frame_data.append(arr) - global_max_diff = max(global_max_diff, np.abs(arr[:, 3]).max()) - else: - frame_data.append(np.zeros((1, 4))) - - if i % 50 == 0: - nd = len(diffs) if diffs else 0 - md = np.abs(arr[:, 3]).max() if diffs else 0 - print(f" Frame {i}/{n_frames}: {nd} voxels, max|diff|={md:.4f}") - - print(f" Done in {time.time()-t0:.1f}s, global max|diff|={global_max_diff:.4f}") - - print("Rendering animation...") - fig = plt.figure(figsize=(10, 8), facecolor='black') - ax = fig.add_subplot(111, projection='3d', facecolor='black') - ax.view_init(elev=25, azim=-60) - - vmax = global_max_diff * 0.8 - norm = TwoSlopeNorm(vmin=-vmax, vcenter=0, vmax=vmax) - cmap = plt.cm.RdBu_r - - sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) - sm.set_array([]) - cbar = fig.colorbar(sm, ax=ax, shrink=0.6, pad=0.08, label='Truth - Sim dE (MeV)') - cbar.ax.yaxis.label.set_color('white') - cbar.ax.tick_params(colors='white') - - ax.set_xlabel('X (mm)', color='white', fontsize=10) - ax.set_ylabel('Y (mm)', color='white', fontsize=10) - ax.set_zlabel('Z (mm)', color='white', fontsize=10) - ax.tick_params(colors='white', labelsize=7) - ax.xaxis.pane.fill = False - ax.yaxis.pane.fill = False - ax.zaxis.pane.fill = False - ax.xaxis.pane.set_edgecolor('gray') - ax.yaxis.pane.set_edgecolor('gray') - ax.zaxis.pane.set_edgecolor('gray') - ax.grid(True, alpha=0.2, color='gray') - - margin = 50 - ax.set_xlim(truth_pos[:, 0].min() - margin, truth_pos[:, 0].max() + margin) - ax.set_ylim(truth_pos[:, 1].min() - margin, truth_pos[:, 1].max() + margin) - ax.set_zlim(truth_pos[:, 2].min() - margin, truth_pos[:, 2].max() + margin) - - scatter = [None] - title = ax.set_title('', color='white', fontsize=12, fontweight='bold', pad=20) - - def update(frame_idx): - if scatter[0] is not None: - scatter[0].remove() - - arr = frame_data[frame_idx] - x, y, z, diff = arr[:, 0], arr[:, 1], arr[:, 2], arr[:, 3] - sizes = np.clip(np.abs(diff) / vmax * MAX_POINT_SIZE, 2, MAX_POINT_SIZE) - alphas = np.clip(np.abs(diff) / vmax, 0.05, 0.85) - rgba = cmap(norm(diff)) - rgba[:, 3] = alphas - - scatter[0] = ax.scatter(x, y, z, c=rgba, s=sizes, - edgecolors='none', depthshade=True) - - step = checkpoint_steps[frame_idx] - loss = checkpoint_losses[frame_idx] - title.set_text(f'20k segments | Step {step:4d} | Loss: {loss:.4f} | ' - f'{len(arr)} voxels') - return scatter[0], - - print(f" Creating {n_frames} frames at {FPS}fps...") - t0 = time.time() - anim = animation.FuncAnimation(fig, update, frames=n_frames, - blit=False, interval=1000/FPS) - writer = animation.PillowWriter(fps=FPS) - anim.save(OUT_PATH, writer=writer, dpi=DPI) - print(f" Done in {time.time()-t0:.0f}s") - print(f" Saved to {OUT_PATH} ({os.path.getsize(OUT_PATH)/1e6:.1f} MB)") - plt.close(fig) - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/render_3d_annihilation.py b/closure/archive/segments_intermediate/render_3d_annihilation.py deleted file mode 100644 index fc9e781..0000000 --- a/closure/archive/segments_intermediate/render_3d_annihilation.py +++ /dev/null @@ -1,228 +0,0 @@ -""" -3D annihilation plot: voxelized truth-sim difference over training. - -Each frame shows voxels colored by (truth_dE - sim_dE): - - Blue: truth has more charge (sim is missing) - - Red: sim has more charge (sim excess) - - Size proportional to |difference| - -50fps, 8 seconds = 400 frames from checkpoints saved every 10 steps. - -Usage: - python3 closure_analysis_full/sweeps/render_3d_annihilation.py -""" - -import numpy as np -import matplotlib.pyplot as plt -from matplotlib.colors import TwoSlopeNorm -from mpl_toolkits.mplot3d import Axes3D -import matplotlib.animation as animation -import os, sys, time - -DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'best_run_4000.npz') -OUT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'annihilation_3d.gif') - -VOXEL_SIZE = 25.0 # mm (coarser for cleaner visualization) -MIN_DIFF = 0.005 # MeV, skip voxels with |diff| below this (no color for near-zero) -MAX_POINT_SIZE = 80 -FPS = 50 -DPI = 120 - - -def voxelize(positions, energies, voxel_size, origin): - """Hash positions into voxel keys, accumulate energy per voxel.""" - idx = ((positions - origin) / voxel_size).astype(np.int32) - keys = idx[:, 0] * 1_000_000 + idx[:, 1] * 1_000 + idx[:, 2] - voxels = {} - for i, k in enumerate(keys): - if k in voxels: - voxels[k][0] += energies[i] - else: - center = origin + (idx[i] + 0.5) * voxel_size - voxels[k] = [energies[i], center[0], center[1], center[2]] - return voxels - - -def voxelize_vectorized(positions, energies, voxel_size, origin): - """Vectorized voxelization using numpy.""" - idx = ((positions - origin) / voxel_size).astype(np.int64) - keys = idx[:, 0] * 1_000_000 + idx[:, 1] * 1_000 + idx[:, 2] - unique_keys, inverse = np.unique(keys, return_inverse=True) - # Sum energies per voxel - vox_de = np.zeros(len(unique_keys)) - np.add.at(vox_de, inverse, energies) - # Compute centers - vox_centers = np.zeros((len(unique_keys), 3)) - for dim in range(3): - np.add.at(vox_centers[:, dim], inverse, positions[:, dim] * energies) - # Energy-weighted center (or just voxel center) - vox_idx = np.zeros((len(unique_keys), 3), dtype=np.int64) - for i, k in enumerate(unique_keys): - vox_idx[i, 0] = k // 1_000_000 - vox_idx[i, 1] = (k % 1_000_000) // 1_000 - vox_idx[i, 2] = k % 1_000 - centers = origin + (vox_idx + 0.5) * voxel_size - return dict(zip(unique_keys.tolist(), zip(vox_de.tolist(), - centers[:, 0].tolist(), centers[:, 1].tolist(), centers[:, 2].tolist()))) - - -def main(): - print("Loading data...") - data = np.load(DATA_PATH) - - truth_pos = data['truth_pos'] - truth_de = data['truth_de'] - checkpoint_params = data['checkpoint_params'] - checkpoint_steps = data['checkpoint_steps'] - checkpoint_losses = data['checkpoint_losses'] - n_seg = int(data['n_seg']) - truth_total_de = float(data['truth_total_de']) - - n_frames = len(checkpoint_steps) - print(f" {n_frames} checkpoints, {n_seg} segments") - print(f" Truth: {len(truth_de)} segments") - - # Compute voxel grid origin (min of all positions with margin) - all_pos_min = np.minimum(truth_pos.min(axis=0), - checkpoint_params[:, :, :3].reshape(-1, 3).min(axis=0)) - origin = all_pos_min - VOXEL_SIZE - - # Pre-compute truth voxels (fixed for all frames) - print("Voxelizing truth...") - truth_voxels = voxelize_vectorized(truth_pos, truth_de, VOXEL_SIZE, origin) - print(f" {len(truth_voxels)} truth voxels") - - # Pre-compute all frame data - print("Computing frame data...") - t0 = time.time() - - frame_data = [] - global_max_diff = 0 - - for i in range(n_frames): - params = checkpoint_params[i] - sim_pos = params[:, :3] - sim_de = params[:, 3] - - # Only include alive segments - alive = sim_de > 0.001 - sim_voxels = voxelize_vectorized(sim_pos[alive], sim_de[alive], VOXEL_SIZE, origin) - - # Compute difference: truth - sim - all_keys = set(truth_voxels.keys()) | set(sim_voxels.keys()) - diffs = [] - for k in all_keys: - t_de = truth_voxels.get(k, [0, 0, 0, 0])[0] - s_de = sim_voxels.get(k, [0, 0, 0, 0])[0] - diff = t_de - s_de - if abs(diff) < MIN_DIFF: - continue - # Get center from whichever has the key - if k in truth_voxels: - _, cx, cy, cz = truth_voxels[k] - else: - _, cx, cy, cz = sim_voxels[k] - diffs.append((cx, cy, cz, diff)) - - if diffs: - arr = np.array(diffs) - frame_data.append(arr) - global_max_diff = max(global_max_diff, np.abs(arr[:, 3]).max()) - else: - frame_data.append(np.zeros((1, 4))) - - if i % 50 == 0: - print(f" Frame {i}/{n_frames}: {len(diffs)} voxels, " - f"max|diff|={np.abs(arr[:, 3]).max():.4f}") - - print(f" Done in {time.time()-t0:.1f}s") - print(f" Global max |diff|: {global_max_diff:.4f} MeV") - - # Create figure - print("Rendering animation...") - fig = plt.figure(figsize=(10, 8), facecolor='black') - ax = fig.add_subplot(111, projection='3d', facecolor='black') - - # Fixed view angle - ax.view_init(elev=25, azim=-60) - - # Color normalization (fixed across all frames, symmetric around 0) - vmax = global_max_diff * 0.8 # clip top 20% for better contrast - norm = TwoSlopeNorm(vmin=-vmax, vcenter=0, vmax=vmax) - cmap = plt.cm.RdBu_r # red=sim excess, blue=truth excess - - # Add colorbar - sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) - sm.set_array([]) - cbar = fig.colorbar(sm, ax=ax, shrink=0.6, pad=0.08, label='Truth - Sim dE (MeV)') - cbar.ax.yaxis.label.set_color('white') - cbar.ax.tick_params(colors='white') - - # Style - ax.set_xlabel('X (mm)', color='white', fontsize=10) - ax.set_ylabel('Y (mm)', color='white', fontsize=10) - ax.set_zlabel('Z (mm)', color='white', fontsize=10) - ax.tick_params(colors='white', labelsize=7) - for spine in ax.spines.values(): - spine.set_color('white') - ax.xaxis.pane.fill = False - ax.yaxis.pane.fill = False - ax.zaxis.pane.fill = False - ax.xaxis.pane.set_edgecolor('gray') - ax.yaxis.pane.set_edgecolor('gray') - ax.zaxis.pane.set_edgecolor('gray') - ax.grid(True, alpha=0.2, color='gray') - - # Set axis limits from truth extent - margin = 50 - ax.set_xlim(truth_pos[:, 0].min() - margin, truth_pos[:, 0].max() + margin) - ax.set_ylim(truth_pos[:, 1].min() - margin, truth_pos[:, 1].max() + margin) - ax.set_zlim(truth_pos[:, 2].min() - margin, truth_pos[:, 2].max() + margin) - - scatter = [None] - title = ax.set_title('', color='white', fontsize=12, fontweight='bold', pad=20) - - def update(frame_idx): - if scatter[0] is not None: - scatter[0].remove() - - arr = frame_data[frame_idx] - x, y, z, diff = arr[:, 0], arr[:, 1], arr[:, 2], arr[:, 3] - - # Size proportional to |diff| - sizes = np.clip(np.abs(diff) / vmax * MAX_POINT_SIZE, 2, MAX_POINT_SIZE) - - # Alpha proportional to |diff| — near-zero voxels are invisible - alphas = np.clip(np.abs(diff) / vmax, 0.05, 0.85) - - # Build RGBA colors manually so zero → transparent - rgba = cmap(norm(diff)) - rgba[:, 3] = alphas - - scatter[0] = ax.scatter(x, y, z, c=rgba, - s=sizes, edgecolors='none', - depthshade=True) - - step = checkpoint_steps[frame_idx] - loss = checkpoint_losses[frame_idx] - title.set_text(f'Step {step:4d} | Loss: {loss:.4f} | ' - f'{len(arr)} voxels | ' - f'max|diff|: {np.abs(diff).max():.3f} MeV') - return scatter[0], - - print(f" Creating {n_frames} frames at {FPS}fps...") - t0 = time.time() - - anim = animation.FuncAnimation(fig, update, frames=n_frames, - blit=False, interval=1000/FPS) - - writer = animation.PillowWriter(fps=FPS) - anim.save(OUT_PATH, writer=writer, dpi=DPI) - - print(f" Done in {time.time()-t0:.0f}s") - print(f" Saved to {OUT_PATH} ({os.path.getsize(OUT_PATH)/1e6:.1f} MB)") - plt.close(fig) - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/render_event_display.py b/closure/archive/segments_intermediate/render_event_display.py deleted file mode 100644 index 1131287..0000000 --- a/closure/archive/segments_intermediate/render_event_display.py +++ /dev/null @@ -1,143 +0,0 @@ -""" -Event display animation: truth / sim / diff for east and west sides. - -Top row: truth wire-summed profiles (fixed) -Middle row: sim profiles (evolving) -Bottom row: diff (truth - sim) - -One GIF per side (east, west). Each frame = one signal checkpoint. - -Usage: - python3 closure_analysis_full/sweeps/render_event_display.py -""" - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib.animation as animation -import os - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -DATA_PATH = os.path.join(OUT_DIR, 'best_final.npz') -FPS = 10 # slower for event display — want to see detail -DPI = 120 -PLANE_NAMES = ['east_U', 'east_V', 'east_Y', 'west_U', 'west_V', 'west_Y'] - - -def main(): - print("Loading data...") - data = np.load(DATA_PATH, allow_pickle=True) - - active_planes = list(data['active_planes']) - signal_steps = data['signal_steps'] - n_snapshots = int(data['n_signal_snapshots']) - losses = data['losses'] - - # Load truth and sim profiles - truth_profiles = {} - sim_profiles = {} - for p in active_planes: - truth_profiles[p] = data[f'truth_profile_{p}'] - sim_profiles[p] = [data[f'sig_profile_{p}_{j}'] for j in range(n_snapshots)] - - # Sides: east = planes 0,1,2; west = planes 3,4,5 - sides = { - 'east': [p for p in active_planes if p < 3], - 'west': [p for p in active_planes if p >= 3], - } - - for side_name, planes in sides.items(): - if not planes: - print(f" No active planes for {side_name}, skipping") - continue - - print(f"Rendering {side_name} event display ({len(planes)} planes, {n_snapshots} frames)...") - n_planes = len(planes) - fig, axes = plt.subplots(3, n_planes, figsize=(6 * n_planes, 12)) - if n_planes == 1: - axes = axes[:, np.newaxis] - - # Compute fixed y-limits per plane - ylims = {} - for col, p in enumerate(planes): - t_prof = truth_profiles[p] - all_sim = np.array(sim_profiles[p]) - ymax = max(t_prof.max(), all_sim.max()) * 1.1 - # Wire range (zoom to active) - nz = np.where(t_prof > 0)[0] - if len(nz) > 0: - wl, wh = max(0, nz[0] - 10), min(len(t_prof), nz[-1] + 11) - else: - wl, wh = 0, len(t_prof) - ylims[p] = (wl, wh, ymax) - - # Compute fixed diff range - diff_max = 0 - for p in planes: - for j in range(n_snapshots): - wl, wh, _ = ylims[p] - diff = truth_profiles[p][wl:wh] - sim_profiles[p][j][wl:wh] - diff_max = max(diff_max, np.abs(diff).max()) - diff_max *= 1.1 - - lines_truth = {} - lines_sim = {} - lines_diff = {} - - for col, p in enumerate(planes): - wl, wh, ymax = ylims[p] - wires = np.arange(wl, wh) - t_prof = truth_profiles[p][wl:wh] - - # Truth (top row) — static - ax = axes[0, col] - ax.plot(wires, t_prof, 'b-', lw=1.5) - ax.set_ylim(0, ymax) - ax.set_title(f'Truth {PLANE_NAMES[p]}', fontsize=12) - ax.set_ylabel('|Signal|', fontsize=10) - ax.grid(True, alpha=0.3) - - # Sim (middle row) — animated - ax = axes[1, col] - line, = ax.plot(wires, t_prof * 0, 'r-', lw=1.5) - ax.set_ylim(0, ymax) - ax.set_title(f'Sim {PLANE_NAMES[p]}', fontsize=12) - ax.set_ylabel('|Signal|', fontsize=10) - ax.grid(True, alpha=0.3) - lines_sim[p] = (line, wl, wh) - - # Diff (bottom row) — animated - ax = axes[2, col] - line, = ax.plot(wires, t_prof * 0, 'k-', lw=1.5) - ax.set_ylim(-diff_max, diff_max) - ax.axhline(0, color='gray', ls='-', lw=0.5) - ax.set_title(f'Diff {PLANE_NAMES[p]}', fontsize=12) - ax.set_xlabel('Wire', fontsize=10) - ax.set_ylabel('Truth - Sim', fontsize=10) - ax.grid(True, alpha=0.3) - lines_diff[p] = (line, wl, wh) - - title = fig.suptitle('', fontsize=14, fontweight='bold') - fig.tight_layout(rect=[0, 0, 1, 0.96]) - - def update(frame_idx): - step = signal_steps[frame_idx] - loss = losses[min(step, len(losses)-1)] - title.set_text(f'{side_name.upper()} | Step {step} | Loss: {loss:.6f}') - for p in planes: - wl, wh = ylims[p][0], ylims[p][1] - s_prof = sim_profiles[p][frame_idx][wl:wh] - t_prof = truth_profiles[p][wl:wh] - lines_sim[p][0].set_ydata(s_prof) - lines_diff[p][0].set_ydata(t_prof - s_prof) - - anim = animation.FuncAnimation(fig, update, frames=n_snapshots, - blit=False, interval=1000/FPS) - out_path = os.path.join(OUT_DIR, f'event_display_{side_name}.gif') - writer = animation.PillowWriter(fps=FPS) - anim.save(out_path, writer=writer, dpi=DPI) - plt.close(fig) - print(f" Saved {out_path} ({os.path.getsize(out_path)/1e6:.1f} MB)") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/render_event_display_2d.py b/closure/archive/segments_intermediate/render_event_display_2d.py deleted file mode 100644 index 33bf921..0000000 --- a/closure/archive/segments_intermediate/render_event_display_2d.py +++ /dev/null @@ -1,238 +0,0 @@ -""" -Render 2D event display GIFs from precomputed signals. -Uses same imshow/colormap/norm as visualize_wire_signals. - -Usage: - python3 closure_analysis_full/sweeps/precompute_signals.py # run first - python3 closure_analysis_full/sweeps/render_event_display_2d.py - python3 closure_analysis_full/sweeps/render_event_display_2d.py --preview # single frames only -""" - -import sys, os, time, argparse -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import numpy as np -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt -import matplotlib.gridspec as gridspec -from mpl_toolkits.axes_grid1 import make_axes_locatable -from PIL import Image - -from tools.geometry import generate_detector -from tools.visualization import _extract_viz_params, _resolve_cmap, DeadbandNorm - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -SIGNALS_PATH = os.path.join(OUT_DIR, 'precomputed_signals.npz') -GIF_FPS = 8 -THRESHOLD_ENC = 800 -GAMMA = 0.2 - -# Font sizes -TITLE_SIZE = 16 -LABEL_SIZE = 14 -TICK_SIZE = 12 -CBAR_LABEL_SIZE = 12 -CBAR_TICK_SIZE = 10 -SUPTITLE_SIZE = 18 - - -def fig_to_image(fig): - fig.canvas.draw() - w, h = fig.canvas.get_width_height() - buf = fig.canvas.buffer_rgba() - return Image.frombuffer('RGBA', (w, h), buf, 'raw', 'RGBA', 0, 1).convert('RGB').copy() - - -def add_colorbar(fig, ax, mappable, norm): - divider = make_axes_locatable(ax) - cax = divider.append_axes('right', size='3%', pad=0.02) - cbar = fig.colorbar(mappable, cax=cax) - if isinstance(norm, DeadbandNorm): - tick_norm = np.linspace(0, 1, 7) - tick_values = norm.inverse(tick_norm) - cbar.set_ticks(tick_values) - cbar.set_ticklabels([f'{v:.0f}' for v in tick_values]) - cbar.ax.tick_params(labelsize=CBAR_TICK_SIZE, colors='black') - cbar.set_label('Signal (ADC)', fontsize=CBAR_LABEL_SIZE, color='black') - return cbar - - -def build_figure(side_planes, detector_config, truth, cmap, deadband_adc, - plane_min_max, ptype_map): - """Create figure once with 3 rows × n_planes, return imshow refs.""" - vp = _extract_viz_params(detector_config) - num_time_steps = vp['num_time_steps'] - time_step_size_us = vp['time_step_size_us'] - max_time_axis = num_time_steps * time_step_size_us - max_abs_indices = vp['max_abs_indices'] - min_abs_indices = vp['min_abs_indices'] - zero_color = cmap(0.5) - - n_planes = len(side_planes) - plane_types = ['1st Induction (U)', '2nd Induction (V)', 'Collection (Y)'] - row_labels = ['Truth', 'Sim', 'Diff'] - - fig = plt.figure(figsize=(6.5 * n_planes, 15), facecolor='white') - gs = gridspec.GridSpec(3, n_planes, figure=fig, hspace=0.25, wspace=0.28) - - imshow_objects = {} - title_objects = {} - - for row in range(3): - for col, (s, p) in enumerate(side_planes): - ax = fig.add_subplot(gs[row, col]) - ax.set_facecolor(zero_color) - ax.grid(False) - - min_idx = int(min_abs_indices[s, p]) - max_idx = int(max_abs_indices[s, p]) - extent = [min_idx, max_idx + 1, 0, max_time_axis] - - pt = ptype_map[p] - vmin = plane_min_max[pt]['min'] - vmax = plane_min_max[pt]['max'] - norm = DeadbandNorm(vmin, vmax, deadband_adc, GAMMA) - - init_data = truth[(s, p)] - im = ax.imshow(init_data.T, aspect='auto', origin='lower', - extent=extent, cmap=cmap, norm=norm, - interpolation='nearest') - imshow_objects[(row, col)] = im - - cbar = add_colorbar(fig, ax, im, norm) - # Only show colorbar label on rightmost column - if col < n_planes - 1: - cbar.set_label('') - - ttl = ax.set_title(f'{row_labels[row]} {plane_types[p]}', - fontsize=TITLE_SIZE, pad=8) - title_objects[(row, col)] = ttl - - # Only xlabel on bottom row - if row == 2: - ax.set_xlabel('Absolute Wire Index', fontsize=LABEL_SIZE) - else: - ax.set_xlabel('') - - # Only ylabel on leftmost column - if col == 0: - ax.set_ylabel('Time (μs)', fontsize=LABEL_SIZE) - else: - ax.set_ylabel('') - - ax.tick_params(labelsize=TICK_SIZE) - ax.set_xlim(min_idx, max_idx + 1) - ax.set_ylim(0, max_time_axis) - - suptitle = fig.suptitle('', fontsize=SUPTITLE_SIZE, fontweight='bold', y=0.995) - fig.subplots_adjust(top=0.94) - - return fig, imshow_objects, title_objects, suptitle - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('--preview', action='store_true', - help='Save single frames only (no GIF)') - args = parser.parse_args() - - print("Loading precomputed signals...") - data = np.load(SIGNALS_PATH, allow_pickle=True) - n_frames = int(data['n_frames']) - frame_steps = data['frame_steps'] - frame_losses = data['frame_losses'] - active_planes = list(data['active_planes']) - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - electrons_per_adc = float(detector_config['electrons_per_adc']) - deadband_adc = THRESHOLD_ENC / electrons_per_adc - cmap = _resolve_cmap('obsidian') - - ptype_map = {0: 'U', 1: 'V', 2: 'Y'} - plane_types_short = ['U', 'V', 'Y'] - - # Load truth - truth = {} - for pidx in active_planes: - s, p = pidx // 3, pidx % 3 - truth[(s, p)] = data[f'truth_{s}_{p}'] - - # Compute norms from truth - plane_min_max = {'U': {'min': np.inf, 'max': -np.inf}, - 'V': {'min': np.inf, 'max': -np.inf}, - 'Y': {'min': np.inf, 'max': -np.inf}} - for pidx in active_planes: - s, p = pidx // 3, pidx % 3 - arr = truth[(s, p)] - pt = ptype_map[p] - plane_min_max[pt]['min'] = min(plane_min_max[pt]['min'], arr.min()) - plane_min_max[pt]['max'] = max(plane_min_max[pt]['max'], arr.max()) - for pt in plane_min_max: - mm = plane_min_max[pt] - if mm['min'] == np.inf: - mm['min'], mm['max'] = -25, 25 - elif pt == 'Y': - abs_max = max(abs(mm['min']), abs(mm['max'])) - mm['min'], mm['max'] = -abs_max, abs_max - - for side_idx, side_name in [(0, 'east'), (1, 'west')]: - side_planes = [(side_idx, p) for p in range(3) - if side_idx * 3 + p in active_planes] - if not side_planes: - continue - - n_p = len(side_planes) - print(f"\n{'='*50}") - print(f" {side_name.upper()} ({n_p} planes)") - print(f"{'='*50}") - - fig, ims, titles, suptitle = build_figure( - side_planes, detector_config, truth, cmap, deadband_adc, - plane_min_max, ptype_map) - - plane_types_full = ['1st Induction (U)', '2nd Induction (V)', 'Collection (Y)'] - - if args.preview: - # Just save first and last frame - for fi in [0, n_frames - 1]: - step = frame_steps[fi] - loss = frame_losses[fi] - for col, (s, p) in enumerate(side_planes): - r_sig = data[f'sim_{fi}_{s}_{p}'] - d_sig = truth[(s, p)] - r_sig - ims[(1, col)].set_data(r_sig.T) - ims[(2, col)].set_data(d_sig.T) - suptitle.set_text(f'{side_name.upper()} — Step {step} | Loss: {loss:.6f} | ' - f'Threshold: {THRESHOLD_ENC} e⁻') - fname = os.path.join(OUT_DIR, f'preview_{side_name}_step{step}.png') - fig.savefig(fname, dpi=150, bbox_inches='tight', facecolor='white') - print(f" Saved {fname}") - else: - frames = [] - t0 = time.time() - for fi in range(n_frames): - step = frame_steps[fi] - loss = frame_losses[fi] - for col, (s, p) in enumerate(side_planes): - r_sig = data[f'sim_{fi}_{s}_{p}'] - d_sig = truth[(s, p)] - r_sig - ims[(1, col)].set_data(r_sig.T) - ims[(2, col)].set_data(d_sig.T) - suptitle.set_text(f'{side_name.upper()} — Step {step} | Loss: {loss:.6f} | ' - f'Threshold: {THRESHOLD_ENC} e⁻') - frames.append(fig_to_image(fig)) - if fi % 10 == 0 or fi == n_frames - 1: - print(f" Frame {fi+1}/{n_frames} (step {step}) — {time.time()-t0:.0f}s") - - out_path = os.path.join(OUT_DIR, f'event_display_2d_{side_name}.gif') - duration_ms = int(1000 / GIF_FPS) - frames[0].save(out_path, save_all=True, append_images=frames[1:], - duration=duration_ms, loop=0) - print(f" Saved {out_path} ({os.path.getsize(out_path)/1e6:.1f} MB)") - - plt.close(fig) - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_20k.py b/closure/archive/segments_intermediate/run_20k.py deleted file mode 100644 index 284612b..0000000 --- a/closure/archive/segments_intermediate/run_20k.py +++ /dev/null @@ -1,302 +0,0 @@ -""" -Run best config at 20k segments with diagnostic plots. - -Usage: - python3 closure_analysis_full/sweeps/run_20k.py mpvmpr_20.h5 -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax -import jax.numpy as jnp -import numpy as np -import optax -import matplotlib.pyplot as plt - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import ( - DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments, -) - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -def main(): - h5_path = sys.argv[1] if len(sys.argv) > 1 else 'mpvmpr_20.h5' - n_seg = 20000 - total_steps = 4000 - save_every = 10 - - # Best config - lr = 1.0 - decay_rate = 0.999 - lr_e_mult = 0.003 - warmup = 100 - noise_lr = 0.3 - l1 = 0.0 - reloc_every = 25 - max_reloc = 100 - recomb_model = 'modified_box' - - print(f"20k segment run — {total_steps} steps") - print(f"lr={lr}, decay={decay_rate}, e_mult={lr_e_mult}, warmup={warmup}") - print(f"noise_lr={noise_lr}, l1={l1}, reloc={reloc_every}/{max_reloc}") - print(f"File: {h5_path}, n_seg={n_seg}\n") - - # --- Setup --- - deposit_data = load_particle_step_data(h5_path, 0) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - print(f"Truth: {n_truth:,} segments, total dE={truth_total_de:.2f} MeV") - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator( - detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, - include_electronics=False, include_track_hits=False, - recombination_model=recomb_model) - response_signals, _ = sim_truth(deposit_data) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=1.5) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - - # Recomb constants - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, 0.05) - - # Optimizer sim - print(f"Building differentiable simulator (n_seg={n_seg:,})...") - sim_opt = DetectorSimulator( - detector_config, differentiable=True, n_segments=n_seg, - recombination_model=recomb_model) - fwd_opt = sim_opt.build_forward() - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Init - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - print(f"e_scale={e_scale:.2f}, init total dE={float(jnp.sum(init_params[:, 3])):.2f} MeV") - - # JIT warmup - print("JIT warmup...") - t0 = time.time() - _ = grad_fn(init_params) - print(f"Done in {time.time()-t0:.1f}s\n") - - # --- Training loop --- - schedule = optax.exponential_decay( - init_value=lr, transition_steps=1, decay_rate=decay_rate) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - losses = [] - total_energies = [] - dead_counts = [] - cumulative_relocs = 0 - print_every = max(50, total_steps // 40) - t_start = time.time() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(lr_e_mult) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], DEFAULTS['min_energy'])) - - if noise_lr > 0: - lr_cur = float(schedule(step)) - noise_scale = lr_cur * noise_lr - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add( - noise_scale * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= warmup and step % reloc_every == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, max_reloc) - cumulative_relocs += int(n_reloc) - - loss_val = float(total_loss) - losses.append(loss_val) - - if step % print_every == 0 or step == total_steps - 1: - n_dead = int(jnp.sum(params[:, 3] <= DEFAULTS['death_thresh'])) - total_e = float(jnp.sum(params[:, 3])) - total_energies.append(total_e) - dead_counts.append(n_dead) - elapsed = time.time() - t_start - print(f" Step {step:5d}: loss={loss_val:.6f} " - f"total_dE={total_e:.2f} dead={n_dead} " - f"relocs={cumulative_relocs} ({elapsed:.0f}s)") - else: - total_energies.append(total_energies[-1] if total_energies else 0) - dead_counts.append(dead_counts[-1] if dead_counts else 0) - - total_time = time.time() - t_start - final_params = np.array(params) - final_de = float(np.sum(final_params[:, 3])) - de_ratio = final_de / truth_total_de - - print(f"\nDone in {total_time:.0f}s ({total_time/total_steps*1000:.0f} ms/step)") - print(f"Final: loss={losses[-1]:.6f}, dE_ratio={de_ratio:.3f}, " - f"dead={dead_counts[-1]}, relocs={cumulative_relocs}") - - # --- Generate final recon signals for plotting --- - print("\nGenerating final recon signals...") - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - recon_signals = fwd_opt(seg) - - # --- Plot --- - print("Plotting...") - losses_arr = np.array(losses) - total_energies_arr = np.array(total_energies) - - fig, axes = plt.subplots(3, 2, figsize=(18, 20)) - - # Top-left: Loss curve - ax = axes[0, 0] - ax.semilogy(losses_arr, 'b-', lw=1.0, alpha=0.7, label='Sobolev geomean log1p') - ax.axvline(warmup, color='gray', ls='--', lw=1.0, alpha=0.5, label=f'Warmup={warmup}') - ax.set_xlabel('Step', fontsize=14) - ax.set_ylabel('Loss', fontsize=14) - ax.set_title('Loss Convergence', fontsize=15) - ax.legend(fontsize=11) - ax.tick_params(labelsize=11) - ax.grid(True, alpha=0.3) - - # Top-right: Signal comparison west_U - ax = axes[0, 1] - p = 3 # west_U - if p in active_planes: - t_sig = np.array(truth_signals[p]) - r_sig = np.array(recon_signals[p]) - t_prof = np.sum(np.abs(t_sig), axis=1) - r_prof = np.sum(np.abs(r_sig), axis=1) - nz = np.where(t_prof > 0)[0] - if len(nz) > 0: - wl, wh = max(0, nz[0]-10), min(len(t_prof), nz[-1]+11) - else: - wl, wh = 0, len(t_prof) - wires = np.arange(wl, wh) - ax.plot(wires, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(wires, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_xlabel('Wire', fontsize=14) - ax.set_ylabel('|Signal| (summed over time)', fontsize=14) - ax.set_title(f'Signal Comparison ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11) - ax.tick_params(labelsize=11) - ax.grid(True, alpha=0.3) - - # Mid-left: Signal comparison west_Y - ax = axes[1, 0] - p = 5 # west_Y - if p in active_planes: - t_sig = np.array(truth_signals[p]) - r_sig = np.array(recon_signals[p]) - t_prof = np.sum(np.abs(t_sig), axis=1) - r_prof = np.sum(np.abs(r_sig), axis=1) - nz = np.where(t_prof > 0)[0] - if len(nz) > 0: - wl, wh = max(0, nz[0]-10), min(len(t_prof), nz[-1]+11) - else: - wl, wh = 0, len(t_prof) - wires = np.arange(wl, wh) - ax.plot(wires, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(wires, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_xlabel('Wire', fontsize=14) - ax.set_ylabel('|Signal| (summed over time)', fontsize=14) - ax.set_title(f'Signal Comparison ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11) - ax.tick_params(labelsize=11) - ax.grid(True, alpha=0.3) - - # Mid-right: Total energy trajectory - ax = axes[1, 1] - ax.plot(total_energies_arr * 1000, 'k-', lw=2.0, alpha=0.8, label='Optimizer total') - ax.axhline(truth_total_de * 1000, color='b', ls=':', lw=1.5, alpha=0.5, - label=f'Truth total={truth_total_de*1000:.0f} keV') - ax.set_xlabel('Step', fontsize=14) - ax.set_ylabel('Total Energy (keV)', fontsize=14) - ax.set_title('Total Energy Trajectory', fontsize=15) - ax.legend(fontsize=11) - ax.tick_params(labelsize=11) - ax.grid(True, alpha=0.3) - - # Bottom-left: Final segment energy histogram - ax = axes[2, 0] - final_de_kev = final_params[:, 3] * 1000 - alive_de = final_de_kev[final_de_kev > DEFAULTS['death_thresh'] * 1000] - n_dead_final = len(final_de_kev) - len(alive_de) - ax.hist(alive_de, bins=100, alpha=0.7, color='steelblue', - label=f'Alive ({len(alive_de):,})') - ax.axvline(DEFAULTS['death_thresh'] * 1000, color='r', ls='--', lw=1.5, - label=f'Death thresh ({n_dead_final:,} dead)') - ax.set_xlabel('dE (keV)', fontsize=14) - ax.set_ylabel('Count', fontsize=14) - ax.set_title('Final Segment Energy Distribution', fontsize=15) - ax.legend(fontsize=11) - ax.tick_params(labelsize=11) - ax.grid(True, alpha=0.3) - - # Bottom-right: empty - axes[2, 1].axis('off') - - fig.suptitle( - f'Full Closure [20k segments] | {total_steps} steps, ' - f'lr={lr}, d={decay_rate}\n' - f'loss={losses[-1]:.6f}, dE_ratio={de_ratio:.3f}, ' - f'dead={dead_counts[-1]}, relocs={cumulative_relocs}', - fontsize=15, fontweight='bold') - fig.tight_layout() - - fname = os.path.join(OUT_DIR, f'run_20k_{total_steps}steps.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - # Save results - save_path = os.path.join(OUT_DIR, f'run_20k_{total_steps}steps.npz') - np.savez_compressed(save_path, - losses=losses_arr, - total_energies=total_energies_arr, - dead_counts=np.array(dead_counts), - final_params=final_params, - truth_total_de=truth_total_de, - de_ratio=de_ratio, - n_seg=n_seg, - total_steps=total_steps, - ) - print(f"Saved {save_path}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_20k_checkpoints.py b/closure/archive/segments_intermediate/run_20k_checkpoints.py deleted file mode 100644 index 79361d3..0000000 --- a/closure/archive/segments_intermediate/run_20k_checkpoints.py +++ /dev/null @@ -1,123 +0,0 @@ -"""Run 20k segments with checkpoint saving for 3D visualization.""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np, optax -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -def main(): - h5_path = sys.argv[1] if len(sys.argv) > 1 else 'mpvmpr_20.h5' - n_seg = 20000 - total_steps = 4000 - save_every = 10 - - deposit_data = load_particle_step_data(h5_path, 0) - n_truth = deposit_data.positions_mm.shape[0] - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - print(f"Truth: {n_truth:,} segments") - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - response_signals, _ = sim_truth(deposit_data) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=1.5) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, 0.05) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward() - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - print("JIT warmup...") - _ = grad_fn(init_params) - print("Done.\n") - - schedule = optax.exponential_decay(init_value=1.0, transition_steps=1, decay_rate=0.999) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - n_checkpoints = total_steps // save_every + 1 - checkpoint_steps = [] - checkpoint_losses = [] - checkpoint_params = np.zeros((n_checkpoints, n_seg, 4), dtype=np.float32) - cumulative_relocs = 0 - t_start = time.time() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(0.003) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add(lr_cur * 0.3 * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= 100 and step % 25 == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, 100) - cumulative_relocs += int(n_reloc) - - if step % save_every == 0: - idx = step // save_every - checkpoint_steps.append(step) - checkpoint_losses.append(float(total_loss)) - checkpoint_params[idx] = np.array(params) - - if step % 200 == 0 or step == total_steps - 1: - print(f" Step {step:5d}: loss={float(total_loss):.6f} " - f"relocs={cumulative_relocs} ({time.time()-t_start:.0f}s)") - - save_path = os.path.join(OUT_DIR, 'best_run_20k_4000.npz') - np.savez_compressed(save_path, - checkpoint_steps=np.array(checkpoint_steps), - checkpoint_losses=np.array(checkpoint_losses), - checkpoint_params=checkpoint_params[:len(checkpoint_steps)], - truth_pos=truth_pos, truth_de=truth_de, - n_truth=n_truth, n_seg=n_seg, total_steps=total_steps, - truth_total_de=float(np.sum(truth_de)), - ) - print(f"\nSaved to {save_path} ({os.path.getsize(save_path)/1e6:.1f} MB)") - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_best_final.py b/closure/archive/segments_intermediate/run_best_final.py deleted file mode 100644 index 8b6775d..0000000 --- a/closure/archive/segments_intermediate/run_best_final.py +++ /dev/null @@ -1,321 +0,0 @@ -""" -Final best config run with full diagnostics. -Saves checkpoints, computes wire signals at each checkpoint for event display animations. - -Usage: - python3 closure_analysis_full/sweeps/run_best_final.py -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np, optax -import matplotlib.pyplot as plt -import matplotlib.colors as mcolors - -from tools.geometry import generate_detector -from tools.config import SegmentData, DepositData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -SOBOLEV_S = 1.0 -DX_MM = 0.3 -ALPHA_RECOMB = 0.93 -W_ION = 23.6e-6 - - -def main(): - n_seg = 50000 - total_steps = 2000 - save_every = 10 # checkpoints for 3D viz - signal_save_every = 50 # wire signals for event display (heavier) - - # Best config - lr, decay_rate, lr_e_mult = 1.0, 0.999, 0.01 - warmup, noise_lr = 100, 0.3 - reloc_every, max_reloc = 25, 1000 - track_jitter_mm = 50.0 - - print(f"Final best run: {n_seg} segs, {total_steps} steps") - print(f"lr={lr}, d={decay_rate}, e_mult={lr_e_mult}, reloc {reloc_every}/{max_reloc}") - print(f"Track jitter {track_jitter_mm}mm, noise={noise_lr}\n") - - # Setup - deposit_data = load_particle_step_data('out.h5', 2) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - truth_tids = np.asarray(deposit_data.track_ids) - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - forced_deposit = DepositData( - positions_mm=deposit_data.positions_mm, de=deposit_data.de, - dx=np.full(n_truth, DX_MM, dtype=np.float32), - valid_mask=deposit_data.valid_mask, theta=deposit_data.theta, - phi=deposit_data.phi, track_ids=deposit_data.track_ids) - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - t0 = time.time() - response_signals, _ = sim_truth(forced_deposit) - print(f"Truth sim: {time.time()-t0:.1f}s") - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=SOBOLEV_S) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - - # Save truth wire-summed profiles for event display - truth_profiles = {} - for p in active_planes: - truth_profiles[p] = np.sum(np.abs(np.array(truth_signals[p])), axis=1) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = DX_MM / 10.0 - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward(dx_mm=DX_MM) - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Per-track jitter init - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() - init_de = truth_de[indices].copy() * e_scale - init_tids = truth_tids[indices] - for tid in np.unique(init_tids): - init_pos[init_tids == tid] += rng.normal(0, track_jitter_mm, size=3) - init_de *= rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - print("JIT warmup...") - _ = grad_fn(init_params) - print("Done.\n") - - def compute_Q(de_arr): - return (dx_cm / B_eff) * np.log(np.maximum(ALPHA_RECOMB + B_eff * de_arr / dx_cm, 1.0)) - truth_total_Q = compute_Q(truth_de).sum() - - # Training - schedule = optax.exponential_decay(init_value=lr, transition_steps=1, decay_rate=decay_rate) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - # Storage - checkpoint_steps, checkpoint_losses = [], [] - n_cp = total_steps // save_every + 1 - checkpoint_params = np.zeros((n_cp, n_seg, 4), dtype=np.float32) - - # dE histogram over steps (for waterfall plot) - de_history_steps = [] - de_history = [] # list of (alive_des, n_dead) per recorded step - - # Wire signal profiles at signal_save_every - signal_steps = [] - signal_profiles = {} # {plane: list of profiles} - for p in active_planes: - signal_profiles[p] = [] - - losses, q_ratios = [], [] - cumulative_relocs = 0 - t_start = time.time() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(lr_e_mult) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add(lr_cur * noise_lr * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= warmup and step % reloc_every == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, max_reloc) - cumulative_relocs += int(n_reloc) - - loss_val = float(total_loss) - losses.append(loss_val) - - # Checkpoint (segment positions) - if step % save_every == 0: - idx = step // save_every - checkpoint_steps.append(step) - checkpoint_losses.append(loss_val) - checkpoint_params[idx] = np.array(params) - - # dE histogram snapshot - if step % save_every == 0: - p_np = np.array(params[:, 3]) - alive_de = p_np[p_np > DEFAULTS['death_thresh']] - n_dead = int(np.sum(p_np <= DEFAULTS['death_thresh'])) - de_history_steps.append(step) - de_history.append((alive_de.copy(), n_dead)) - - # Wire signal profiles (less frequent — forward pass is expensive) - if step % signal_save_every == 0 or step == total_steps - 1: - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - recon = fwd_opt(seg) - signal_steps.append(step) - for p in active_planes: - prof = np.sum(np.abs(np.array(recon[p])), axis=1) - signal_profiles[p].append(prof) - - if step % 100 == 0 or step == total_steps - 1: - p_np = np.array(params) - alive = p_np[:, 3] > 0.012 - sim_Q = compute_Q(p_np[alive, 3]).sum() - q_ratio = sim_Q / truth_total_Q - q_ratios.append((step, q_ratio)) - n_dead = int((~alive).sum()) - print(f" Step {step:5d}: loss={loss_val:.6f} Q={q_ratio:.3f} " - f"dead={n_dead} relocs={cumulative_relocs} ({time.time()-t_start:.0f}s)") - - print(f"\nDone in {time.time()-t_start:.0f}s") - - # ===================================================================== - # Save everything - # ===================================================================== - save_path = os.path.join(OUT_DIR, 'best_final.npz') - save_data = { - 'checkpoint_steps': np.array(checkpoint_steps), - 'checkpoint_losses': np.array(checkpoint_losses), - 'checkpoint_params': checkpoint_params[:len(checkpoint_steps)], - 'truth_pos': truth_pos, 'truth_de': truth_de, - 'n_truth': n_truth, 'n_seg': n_seg, 'total_steps': total_steps, - 'truth_total_de': truth_total_de, 'dx_mm': DX_MM, - 'B_eff': B_eff, 'alpha': alpha_r, - 'de_history_steps': np.array(de_history_steps), - 'signal_steps': np.array(signal_steps), - 'losses': np.array(losses), - 'active_planes': np.array(active_planes), - } - # Save dE histograms - for i, (alive_de, n_dead) in enumerate(de_history): - save_data[f'de_hist_{i}_alive'] = alive_de - save_data[f'de_hist_{i}_dead'] = n_dead - save_data['n_de_hist'] = len(de_history) - - # Save signal profiles - for p in active_planes: - save_data[f'truth_profile_{p}'] = truth_profiles[p] - for j, prof in enumerate(signal_profiles[p]): - save_data[f'sig_profile_{p}_{j}'] = prof - save_data['n_signal_snapshots'] = len(signal_steps) - - np.savez_compressed(save_path, **save_data) - print(f"Saved to {save_path} ({os.path.getsize(save_path)/1e6:.1f} MB)") - - # ===================================================================== - # dE waterfall plot - # ===================================================================== - print("Creating dE waterfall plot...") - - # Compute 99th percentile across all steps - all_alive = np.concatenate([h[0] for h in de_history]) - p99 = np.percentile(all_alive, 99) * 1000 # keV - n_bins = 100 - bin_edges = np.linspace(DEFAULTS['death_thresh'] * 1000, p99, n_bins + 1) - - waterfall = np.zeros((len(de_history), n_bins + 2)) # +2 for dead and overflow - for i, (alive_de, n_dead) in enumerate(de_history): - alive_kev = alive_de * 1000 - hist, _ = np.histogram(alive_kev, bins=bin_edges) - overflow = int(np.sum(alive_kev > p99)) - waterfall[i, 0] = n_dead - waterfall[i, 1:-1] = hist - waterfall[i, -1] = overflow - - fig, ax = plt.subplots(figsize=(14, 8)) - extent = [0, n_bins + 2, de_history_steps[-1], de_history_steps[0]] - im = ax.imshow(waterfall, aspect='auto', extent=[0, n_bins+2, de_history_steps[-1], 0], - cmap='hot', norm=mcolors.LogNorm(vmin=1, vmax=waterfall.max())) - - # Labels - ax.set_xlabel('dE bin', fontsize=14) - ax.set_ylabel('Step', fontsize=14) - ax.set_title(f'Segment dE Distribution Over Training (99th %ile={p99:.0f} keV)', fontsize=15) - - # Mark dead and overflow bins - ax.axvline(0.5, color='cyan', ls='--', lw=1, alpha=0.5) - ax.axvline(n_bins + 1.5, color='cyan', ls='--', lw=1, alpha=0.5) - ax.text(0, -20, 'Dead', ha='center', fontsize=9, color='cyan') - ax.text(n_bins + 2, -20, 'Over', ha='center', fontsize=9, color='cyan') - - cbar = fig.colorbar(im, ax=ax, label='Count') - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'best_final_waterfall.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - # ===================================================================== - # Progression plot (loss, Q, U, V, Y) - # ===================================================================== - print("Creating progression plot...") - fig, axes = plt.subplots(3, 2, figsize=(18, 20)) - - ax = axes[0, 0] - ax.semilogy(losses, 'b-', lw=1.0, alpha=0.7) - ax.set_xlabel('Step', fontsize=14); ax.set_ylabel('Loss', fontsize=14) - ax.set_title('Loss', fontsize=15); ax.grid(True, alpha=0.3) - - ax = axes[0, 1] - qs, qv = zip(*q_ratios) - ax.plot(qs, qv, 'b-', lw=2) - ax.axhline(1.0, color='green', ls='--', lw=1.5, alpha=0.5) - ax.set_xlabel('Step', fontsize=14); ax.set_ylabel('Q ratio', fontsize=14) - ax.set_title('Charge Conservation', fontsize=15); ax.grid(True, alpha=0.3) - - # U, V, Y signal comparisons (final) - for idx, (p, ax) in enumerate(zip([3, 4, 5], [axes[1,0], axes[1,1], axes[2,0]])): - if p in active_planes: - t_prof = truth_profiles[p] - r_prof = signal_profiles[p][-1] - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - axes[2, 1].axis('off') - fig.suptitle(f'Best Final | 50k segs, s=1.0, lr={lr}, reloc {reloc_every}/{max_reloc}\n' - f'loss={losses[-1]:.6f}, Q={qv[-1]:.3f}', - fontsize=15, fontweight='bold') - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'best_final_progression.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_best_full.py b/closure/archive/segments_intermediate/run_best_full.py deleted file mode 100644 index ea423aa..0000000 --- a/closure/archive/segments_intermediate/run_best_full.py +++ /dev/null @@ -1,228 +0,0 @@ -""" -Run best config for 4000 steps, saving segment state every 10 steps. - -Saves: positions, energies, loss, total_dE, dead count at each checkpoint. -Output: NPZ file for post-visualization. - -Usage: - python3 closure_analysis_full/sweeps/run_best_full.py mpvmpr_20.h5 -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax -import jax.numpy as jnp -import numpy as np -import optax - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import ( - DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments, -) - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -def main(): - h5_path = sys.argv[1] if len(sys.argv) > 1 else 'mpvmpr_20.h5' - n_seg = 10000 - total_steps = 4000 - save_every = 10 - - # Best config - lr = 1.0 - decay_rate = 0.999 - lr_e_mult = 0.003 - warmup = 100 - noise_lr = 0.3 - l1 = 0.0 - reloc_every = 25 - max_reloc = 100 - recomb_model = 'modified_box' - - print(f"Best config run — {total_steps} steps, saving every {save_every}") - print(f"lr={lr}, decay={decay_rate}, e_mult={lr_e_mult}, warmup={warmup}") - print(f"noise_lr={noise_lr}, l1={l1}, reloc={reloc_every}/{max_reloc}") - print(f"File: {h5_path}, n_seg={n_seg}\n") - - # --- Setup --- - deposit_data = load_particle_step_data(h5_path, 0) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - print(f"Truth: {n_truth:,} segments, total dE={truth_total_de:.2f} MeV") - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator( - detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, - include_electronics=False, include_track_hits=False, - recombination_model=recomb_model) - response_signals, _ = sim_truth(deposit_data) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=1.5) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - - # Recomb constants - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, 0.05) - - # Optimizer sim - sim_opt = DetectorSimulator( - detector_config, differentiable=True, n_segments=n_seg, - recombination_model=recomb_model) - fwd_opt = sim_opt.build_forward() - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Init - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - # JIT warmup - print("JIT warmup...") - t0 = time.time() - _ = grad_fn(init_params) - print(f"Done in {time.time()-t0:.1f}s\n") - - # --- Training loop with checkpointing --- - schedule = optax.exponential_decay( - init_value=lr, transition_steps=1, decay_rate=decay_rate) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - # Storage - n_checkpoints = total_steps // save_every + 1 - checkpoint_steps = [] - checkpoint_losses = [] - checkpoint_total_de = [] - checkpoint_dead = [] - checkpoint_relocs = [] - checkpoint_params = np.zeros((n_checkpoints, n_seg, 4), dtype=np.float32) - - cumulative_relocs = 0 - print_every = max(50, total_steps // 40) - t_start = time.time() - - for step in range(total_steps): - # Forward + backward - (total_loss, _), grads = grad_fn(params) - - # Adam update - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(lr_e_mult) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], DEFAULTS['min_energy'])) - - # Noise - if noise_lr > 0: - lr_cur = float(schedule(step)) - noise_scale = lr_cur * noise_lr - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add( - noise_scale * jax.random.normal(nk, shape=(n_seg, 3))) - - # Relocation - if step >= warmup and step % reloc_every == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, max_reloc) - cumulative_relocs += int(n_reloc) - - # Checkpoint - if step % save_every == 0: - idx = step // save_every - checkpoint_steps.append(step) - checkpoint_losses.append(float(total_loss)) - total_e = float(jnp.sum(params[:, 3])) - checkpoint_total_de.append(total_e) - n_dead = int(jnp.sum(params[:, 3] <= DEFAULTS['death_thresh'])) - checkpoint_dead.append(n_dead) - checkpoint_relocs.append(cumulative_relocs) - checkpoint_params[idx] = np.array(params) - - # Print - if step % print_every == 0 or step == total_steps - 1: - loss_val = float(total_loss) - total_e = float(jnp.sum(params[:, 3])) - n_dead = int(jnp.sum(params[:, 3] <= DEFAULTS['death_thresh'])) - elapsed = time.time() - t_start - print(f" Step {step:5d}: loss={loss_val:.6f} " - f"total_dE={total_e:.2f} dead={n_dead} " - f"relocs={cumulative_relocs} ({elapsed:.0f}s)") - - # Final checkpoint - idx = total_steps // save_every - if total_steps % save_every == 0: - checkpoint_steps.append(total_steps) - checkpoint_losses.append(float(total_loss)) - checkpoint_total_de.append(float(jnp.sum(params[:, 3]))) - checkpoint_dead.append(int(jnp.sum(params[:, 3] <= DEFAULTS['death_thresh']))) - checkpoint_relocs.append(cumulative_relocs) - checkpoint_params[idx] = np.array(params) - - total_time = time.time() - t_start - final_de = float(np.sum(np.array(params)[:, 3])) - de_ratio = final_de / truth_total_de - - print(f"\nDone in {total_time:.0f}s ({total_time/total_steps*1000:.0f} ms/step)") - print(f"Final: loss={checkpoint_losses[-1]:.6f}, dE_ratio={de_ratio:.3f}, " - f"dead={checkpoint_dead[-1]}, relocs={cumulative_relocs}") - - # Save - save_path = os.path.join(OUT_DIR, 'best_run_4000.npz') - np.savez_compressed(save_path, - # Checkpoints (every 10 steps) - checkpoint_steps=np.array(checkpoint_steps), - checkpoint_losses=np.array(checkpoint_losses), - checkpoint_total_de=np.array(checkpoint_total_de), - checkpoint_dead=np.array(checkpoint_dead), - checkpoint_relocs=np.array(checkpoint_relocs), - checkpoint_params=checkpoint_params[:len(checkpoint_steps)], - # Truth info - truth_total_de=truth_total_de, - truth_pos=truth_pos, - truth_de=truth_de, - n_truth=n_truth, - # Init info - init_indices=indices, - e_scale=e_scale, - # Config - n_seg=n_seg, - total_steps=total_steps, - lr=lr, decay_rate=decay_rate, lr_e_mult=lr_e_mult, - warmup=warmup, noise_lr=noise_lr, l1=l1, - reloc_every=reloc_every, max_reloc=max_reloc, - ) - print(f"Saved to {save_path} ({os.path.getsize(save_path)/1e6:.1f} MB)") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_best_steps.py b/closure/archive/segments_intermediate/run_best_steps.py deleted file mode 100644 index 7420a58..0000000 --- a/closure/archive/segments_intermediate/run_best_steps.py +++ /dev/null @@ -1,145 +0,0 @@ -""" -Step count sweep with best hyperparameters found so far. -Best: lr=1.0, decay=0.999, lr_e_mult=0.003, warmup=100 - -Usage: - python3 closure_analysis_full/sweeps/run_best_steps.py mpvmpr_20.h5 -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax -import jax.numpy as jnp -import numpy as np - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import ( - DEFAULTS, PLANE_NAMES, build_loss_fn, run_training_loop, -) - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -def main(): - h5_path = sys.argv[1] if len(sys.argv) > 1 else 'mpvmpr_20.h5' - recomb_model = 'modified_box' - n_seg = 10000 - - print(f"Step count sweep — best config") - print(f"lr=1.0, decay=0.999, lr_e_mult=0.003, warmup=100") - print(f"File: {h5_path}, n_seg={n_seg}\n") - - # Setup - deposit_data = load_particle_step_data(h5_path, 0) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator( - detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, - include_electronics=False, include_track_hits=False, - recombination_model=recomb_model) - response_signals, _ = sim_truth(deposit_data) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=1.5) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, 0.05) - - sim_opt = DetectorSimulator( - detector_config, differentiable=True, n_segments=n_seg, - recombination_model=recomb_model) - fwd_opt = sim_opt.build_forward() - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - rng = np.random.RandomState(42) - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale - init_de *= rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - print("JIT warmup...") - _ = grad_fn(init_params) - print("Done.\n") - - results = [] - for total_steps in [500, 1000, 1500, 2000, 3000]: - cfg = dict(DEFAULTS) - cfg['lr'] = 1.0 - cfg['decay_rate'] = 0.999 - cfg['lr_e_mult'] = 0.003 - cfg['warmup'] = 100 - cfg['noise_lr'] = 0.0 - cfg['l1'] = 0.0 - cfg['reloc_every'] = 25 - cfg['max_reloc'] = 100 - cfg['recomb_constants'] = recomb_constants - - print(f"[steps={total_steps}]...") - t0 = time.time() - result = run_training_loop( - grad_fn, init_params, n_seg, total_steps, 'full', cfg) - dt = time.time() - t0 - - final_de = float(np.sum(result['final_params'][:, 3])) - de_ratio = final_de / truth_total_de - print(f" loss={result['losses'][-1]:.6f} dE_ratio={de_ratio:.3f} " - f"dead={result['dead_counts'][-1]} {dt:.0f}s\n") - - results.append({ - 'steps': total_steps, - 'loss': result['losses'][-1], - 'de_ratio': de_ratio, - 'dead': result['dead_counts'][-1], - 'losses': result['losses'], - 'time': dt, - }) - - print(f"\n{'='*60}") - print(f"SUMMARY — best config step scaling") - print(f"{'='*60}") - print(f"{'Steps':>8} {'Loss':>12} {'dE_ratio':>10} {'Dead':>6} {'Time':>6}") - print("-" * 45) - for r in results: - print(f"{r['steps']:>8} {r['loss']:>12.6f} {r['de_ratio']:>10.3f} " - f"{r['dead']:>6d} {r['time']:>5.0f}s") - - save_path = os.path.join(OUT_DIR, 'sweep_best_steps.npz') - save_data = {} - for r in results: - save_data[f"steps_{r['steps']}_losses"] = r['losses'] - save_data[f"steps_{r['steps']}_loss"] = r['loss'] - save_data[f"steps_{r['steps']}_de_ratio"] = r['de_ratio'] - np.savez(save_path, **save_data) - print(f"\nSaved to {save_path}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_l1.py b/closure/archive/segments_intermediate/run_l1.py deleted file mode 100644 index 8c735fe..0000000 --- a/closure/archive/segments_intermediate/run_l1.py +++ /dev/null @@ -1,106 +0,0 @@ -"""L1 sweep at best config with noise_lr=0.3.""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, build_loss_fn, run_training_loop - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -def main(): - h5_path = sys.argv[1] if len(sys.argv) > 1 else 'mpvmpr_20.h5' - n_seg = 10000 - - deposit_data = load_particle_step_data(h5_path, 0) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - response_signals, _ = sim_truth(deposit_data) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=1.5) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, 0.05) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward() - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - rng = np.random.RandomState(42) - truth_pos, truth_de = np.asarray(deposit_data.positions_mm), np.asarray(deposit_data.de) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - print("JIT warmup...") - _ = grad_fn(init_params) - print("Done.\n") - - results = [] - for l1 in [0.0, 0.00005, 0.0001]: - cfg = dict(DEFAULTS) - cfg.update({'lr': 1.0, 'decay_rate': 0.999, 'lr_e_mult': 0.003, - 'warmup': 100, 'noise_lr': 0.3, 'l1': l1, - 'reloc_every': 25, 'max_reloc': 100, - 'recomb_constants': recomb_constants}) - - print(f"[L1={l1}]...") - t0 = time.time() - result = run_training_loop(grad_fn, init_params, n_seg, 1500, 'full', cfg) - dt = time.time() - t0 - final_de = float(np.sum(result['final_params'][:, 3])) - de_ratio = final_de / truth_total_de - print(f" loss={result['losses'][-1]:.6f} dE_ratio={de_ratio:.3f} " - f"dead={result['dead_counts'][-1]} {dt:.0f}s\n") - results.append({'l1': l1, 'loss': result['losses'][-1], - 'de_ratio': de_ratio, 'dead': result['dead_counts'][-1], - 'losses': result['losses']}) - - print(f"\n{'='*50}") - print(f"L1 SWEEP — noise_lr=0.3, 1500 steps") - print(f"{'='*50}") - print(f"{'L1':>10} {'Loss':>10} {'dE_ratio':>10} {'Dead':>6}") - print("-" * 40) - for r in results: - print(f"{r['l1']:>10.5f} {r['loss']:>10.6f} {r['de_ratio']:>10.3f} {r['dead']:>6d}") - - save_path = os.path.join(OUT_DIR, 'sweep_l1.npz') - save_data = {} - for r in results: - save_data[f"l1_{r['l1']}_losses"] = r['losses'] - save_data[f"l1_{r['l1']}_loss"] = r['loss'] - save_data[f"l1_{r['l1']}_de_ratio"] = r['de_ratio'] - np.savez(save_path, **save_data) - print(f"\nSaved to {save_path}") - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_noise.py b/closure/archive/segments_intermediate/run_noise.py deleted file mode 100644 index 8d3a9be..0000000 --- a/closure/archive/segments_intermediate/run_noise.py +++ /dev/null @@ -1,106 +0,0 @@ -"""Noise sweep at best config. Compare against known noise=0 baseline (0.026 at 1500 steps).""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, build_loss_fn, run_training_loop - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -def main(): - h5_path = sys.argv[1] if len(sys.argv) > 1 else 'mpvmpr_20.h5' - n_seg = 10000 - - deposit_data = load_particle_step_data(h5_path, 0) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - response_signals, _ = sim_truth(deposit_data) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=1.5) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, 0.05) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward() - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - rng = np.random.RandomState(42) - truth_pos, truth_de = np.asarray(deposit_data.positions_mm), np.asarray(deposit_data.de) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - print("JIT warmup...") - _ = grad_fn(init_params) - print("Done.\n") - - results = [] - for noise_lr in [0.0, 0.1, 0.3]: - cfg = dict(DEFAULTS) - cfg.update({'lr': 1.0, 'decay_rate': 0.999, 'lr_e_mult': 0.003, - 'warmup': 100, 'noise_lr': noise_lr, 'l1': 0.0, - 'reloc_every': 25, 'max_reloc': 100, - 'recomb_constants': recomb_constants}) - - print(f"[noise_lr={noise_lr}]...") - t0 = time.time() - result = run_training_loop(grad_fn, init_params, n_seg, 1500, 'full', cfg) - dt = time.time() - t0 - final_de = float(np.sum(result['final_params'][:, 3])) - de_ratio = final_de / truth_total_de - print(f" loss={result['losses'][-1]:.6f} dE_ratio={de_ratio:.3f} " - f"dead={result['dead_counts'][-1]} {dt:.0f}s\n") - results.append({'noise_lr': noise_lr, 'loss': result['losses'][-1], - 'de_ratio': de_ratio, 'dead': result['dead_counts'][-1], - 'losses': result['losses']}) - - print(f"\n{'='*50}") - print(f"NOISE SWEEP — best config, 1500 steps") - print(f"{'='*50}") - print(f"{'noise_lr':>10} {'Loss':>10} {'dE_ratio':>10} {'Dead':>6}") - print("-" * 40) - for r in results: - print(f"{r['noise_lr']:>10.1f} {r['loss']:>10.6f} {r['de_ratio']:>10.3f} {r['dead']:>6d}") - - save_path = os.path.join(OUT_DIR, 'sweep_noise.npz') - save_data = {} - for r in results: - save_data[f"noise_{r['noise_lr']}_losses"] = r['losses'] - save_data[f"noise_{r['noise_lr']}_loss"] = r['loss'] - save_data[f"noise_{r['noise_lr']}_de_ratio"] = r['de_ratio'] - np.savez(save_path, **save_data) - print(f"\nSaved to {save_path}") - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_noise2.py b/closure/archive/segments_intermediate/run_noise2.py deleted file mode 100644 index fa5b000..0000000 --- a/closure/archive/segments_intermediate/run_noise2.py +++ /dev/null @@ -1,192 +0,0 @@ -"""Extended noise sweep: higher noise_lr + constant noise test.""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np, optax -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import ( - DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments, -) - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -def run_with_noise(grad_fn, init_params, n_seg, total_steps, cfg, - constant_noise_mm=None): - """Like run_training_loop but supports constant noise option.""" - schedule = optax.exponential_decay( - init_value=cfg['lr'], transition_steps=1, decay_rate=cfg['decay_rate']) - optimizer = optax.adam(schedule, b1=cfg['b1'], b2=cfg['b2']) - - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - losses = [] - total_energies = [] - dead_counts = [] - cumulative_relocs = 0 - max_reloc = cfg.get('max_reloc', 100) - reloc_every = cfg.get('reloc_every', 25) - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(cfg['lr_e_mult']) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], cfg['min_energy'])) - - # Noise: either LR-coupled or constant - if constant_noise_mm is not None and constant_noise_mm > 0: - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add( - constant_noise_mm * jax.random.normal(nk, shape=(n_seg, 3))) - elif cfg.get('noise_lr', 0) > 0: - lr_cur = float(schedule(step)) - noise_scale = lr_cur * cfg['noise_lr'] - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add( - noise_scale * jax.random.normal(nk, shape=(n_seg, 3))) - - # Relocation - if step >= cfg['warmup'] and step % reloc_every == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, - cfg['recomb_constants'], max_reloc) - cumulative_relocs += int(n_reloc) - - loss_val = float(total_loss) - losses.append(loss_val) - - if step % 100 == 0 or step == total_steps - 1: - n_dead = int(jnp.sum(params[:, 3] <= cfg['death_thresh'])) - total_e = float(jnp.sum(params[:, 3])) - total_energies.append(total_e) - dead_counts.append(n_dead) - print(f" Step {step:5d}: loss={loss_val:.6f} " - f"total_dE={total_e:.2f} dead={n_dead} " - f"relocs={cumulative_relocs}") - else: - total_energies.append(total_energies[-1] if total_energies else 0) - dead_counts.append(dead_counts[-1] if dead_counts else 0) - - return { - 'losses': np.array(losses), - 'total_energies': np.array(total_energies), - 'final_params': np.array(params), - 'dead_counts': np.array(dead_counts), - 'cumulative_relocs': cumulative_relocs, - } - - -def main(): - h5_path = sys.argv[1] if len(sys.argv) > 1 else 'mpvmpr_20.h5' - n_seg = 10000 - total_steps = 1500 - - deposit_data = load_particle_step_data(h5_path, 0) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - response_signals, _ = sim_truth(deposit_data) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=1.5) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, 0.05) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward() - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - rng = np.random.RandomState(42) - truth_pos, truth_de = np.asarray(deposit_data.positions_mm), np.asarray(deposit_data.de) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - print("JIT warmup...") - _ = grad_fn(init_params) - print("Done.\n") - - base_cfg = dict(DEFAULTS) - base_cfg.update({'lr': 1.0, 'decay_rate': 0.999, 'lr_e_mult': 0.003, - 'warmup': 100, 'l1': 0.0, 'reloc_every': 25, 'max_reloc': 100, - 'recomb_constants': recomb_constants}) - - combos = [ - {'name': 'lr_coupled_0.5', 'noise_lr': 0.5, 'constant': None}, - {'name': 'lr_coupled_1.0', 'noise_lr': 1.0, 'constant': None}, - {'name': 'constant_0.1mm', 'noise_lr': 0.0, 'constant': 0.1}, - ] - - results = [] - for combo in combos: - cfg = dict(base_cfg) - cfg['noise_lr'] = combo['noise_lr'] - const = combo['constant'] - - desc = f"noise_lr={combo['noise_lr']}" if const is None else f"constant={const}mm" - print(f"[{combo['name']}] {desc}...") - t0 = time.time() - result = run_with_noise(grad_fn, init_params, n_seg, total_steps, cfg, - constant_noise_mm=const) - dt = time.time() - t0 - final_de = float(np.sum(result['final_params'][:, 3])) - de_ratio = final_de / truth_total_de - final_loss = result['losses'][-1] - print(f" loss={final_loss:.6f} dE_ratio={de_ratio:.3f} " - f"dead={result['dead_counts'][-1]} {dt:.0f}s\n") - results.append({'name': combo['name'], 'loss': final_loss, - 'de_ratio': de_ratio, 'dead': result['dead_counts'][-1], - 'losses': result['losses']}) - - print(f"\n{'='*60}") - print(f"EXTENDED NOISE SWEEP — 1500 steps") - print(f"{'='*60}") - print(f"Previous results for context:") - print(f" noise_lr=0.0 (lr-coupled): loss=0.027, dE_ratio=1.032") - print(f" noise_lr=0.1 (lr-coupled): loss=0.024, dE_ratio=1.024") - print(f" noise_lr=0.3 (lr-coupled): loss=0.022, dE_ratio=1.013") - print(f"\nNew results:") - print(f"{'Name':<25} {'Loss':>10} {'dE_ratio':>10} {'Dead':>6}") - print("-" * 55) - for r in results: - print(f"{r['name']:<25} {r['loss']:>10.6f} {r['de_ratio']:>10.3f} {r['dead']:>6d}") - - save_path = os.path.join(OUT_DIR, 'sweep_noise2.npz') - save_data = {} - for r in results: - save_data[f"{r['name']}_losses"] = r['losses'] - save_data[f"{r['name']}_loss"] = r['loss'] - np.savez(save_path, **save_data) - print(f"\nSaved to {save_path}") - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_out_50k.py b/closure/archive/segments_intermediate/run_out_50k.py deleted file mode 100644 index 564c293..0000000 --- a/closure/archive/segments_intermediate/run_out_50k.py +++ /dev/null @@ -1,271 +0,0 @@ -""" -Run out.h5 event 2 with 50k segments, s=1.0, dx=0.3mm matched, best hyperparameters. - -Usage: - python3 closure_analysis_full/sweeps/run_out_50k.py -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np, optax -import matplotlib.pyplot as plt - -from tools.geometry import generate_detector -from tools.config import SegmentData, DepositData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -SOBOLEV_S = 1.0 -DX_MM = 0.3 - - -def main(): - h5_path = 'out.h5' - event_idx = 2 - n_seg = 50000 - total_steps = 2000 - - # Best config - lr = 1.0 - decay_rate = 0.999 - lr_e_mult = 0.003 - warmup = 100 - noise_lr = 0.3 - l1 = 0.0 - reloc_every = 25 - max_reloc = 100 - recomb_model = 'modified_box' - - print(f"out.h5 event {event_idx}, 50k segments, s={SOBOLEV_S}, dx={DX_MM}mm") - print(f"lr={lr}, decay={decay_rate}, e_mult={lr_e_mult}") - print(f"warmup={warmup}, noise={noise_lr}, reloc={reloc_every}/{max_reloc}") - print(f"steps={total_steps}\n") - - # Setup - deposit_data = load_particle_step_data(h5_path, event_idx) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - print(f"Truth: {n_truth:,} segs, dE={truth_total_de:.1f} MeV, e_scale={n_truth/n_seg:.2f}") - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - # Force dx in truth - forced_deposit = DepositData( - positions_mm=deposit_data.positions_mm, - de=deposit_data.de, - dx=np.full(n_truth, DX_MM, dtype=np.float32), - valid_mask=deposit_data.valid_mask, - theta=deposit_data.theta, - phi=deposit_data.phi, - track_ids=deposit_data.track_ids, - ) - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model=recomb_model) - t0 = time.time() - response_signals, _ = sim_truth(forced_deposit) - print(f"Truth sim: {time.time()-t0:.1f}s") - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=SOBOLEV_S) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - planes_tuple = tuple(active_planes) - - print(f"Active planes: {[PLANE_NAMES[p] for p in active_planes]}") - for p in active_planes: - print(f" {PLANE_NAMES[p]}: {truth_signals[p].shape}, " - f"sum|sig|={float(jnp.sum(jnp.abs(truth_signals[p]))):.0f}") - - # Recomb constants - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = DX_MM / 10.0 - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - # Optimizer sim - print(f"\nBuilding differentiable simulator (n_seg={n_seg:,})...") - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model=recomb_model) - fwd_opt = sim_opt.build_forward(dx_mm=DX_MM) - - loss_fn_inner = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn_inner, has_aux=True) - - # Init - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - replace = n_seg > n_truth - indices = rng.choice(n_truth, size=n_seg, replace=replace) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - print(f"Init total dE={float(jnp.sum(init_params[:, 3])):.1f} MeV") - - # JIT - print("JIT warmup...") - t0 = time.time() - _ = grad_fn(init_params) - print(f"Done in {time.time()-t0:.1f}s\n") - - # Training - schedule = optax.exponential_decay(init_value=lr, transition_steps=1, decay_rate=decay_rate) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - losses = [] - total_energies = [] - dead_counts = [] - cumulative_relocs = 0 - print_every = max(50, total_steps // 30) - t_start = time.time() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(lr_e_mult) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - if noise_lr > 0: - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add( - lr_cur * noise_lr * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= warmup and step % reloc_every == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, max_reloc) - cumulative_relocs += int(n_reloc) - - loss_val = float(total_loss) - losses.append(loss_val) - - if step % print_every == 0 or step == total_steps - 1: - n_dead = int(jnp.sum(params[:, 3] <= DEFAULTS['death_thresh'])) - total_e = float(jnp.sum(params[:, 3])) - total_energies.append(total_e) - dead_counts.append(n_dead) - elapsed = time.time() - t_start - print(f" Step {step:5d}: loss={loss_val:.6f} " - f"total_dE={total_e:.1f} dead={n_dead} " - f"relocs={cumulative_relocs} ({elapsed:.0f}s)") - else: - total_energies.append(total_energies[-1] if total_energies else 0) - dead_counts.append(dead_counts[-1] if dead_counts else 0) - - total_time = time.time() - t_start - final_params = np.array(params) - final_de_total = float(np.sum(final_params[:, 3])) - de_ratio = final_de_total / truth_total_de - n_dead_final = int(np.sum(final_params[:, 3] <= DEFAULTS['death_thresh'])) - - print(f"\nDone in {total_time:.0f}s ({total_time/total_steps*1000:.0f} ms/step)") - print(f"Final: loss={losses[-1]:.6f}, dE_ratio={de_ratio:.3f}, " - f"dead={n_dead_final}, relocs={cumulative_relocs}") - - # Recon signals - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - recon_signals = fwd_opt(seg) - - # Plot - fig, axes = plt.subplots(3, 2, figsize=(18, 20)) - - # Loss - ax = axes[0, 0] - ax.semilogy(losses, 'b-', lw=1.0, alpha=0.7) - ax.axvline(warmup, color='gray', ls='--', lw=1.0, alpha=0.5) - ax.set_xlabel('Step', fontsize=14); ax.set_ylabel('Loss', fontsize=14) - ax.set_title(f'Loss (s={SOBOLEV_S}, dx={DX_MM}mm)', fontsize=15) - ax.grid(True, alpha=0.3) - - # West U - ax = axes[0, 1] - p = 3 - if p in active_planes: - t_prof = np.sum(np.abs(np.array(truth_signals[p])), axis=1) - r_prof = np.sum(np.abs(np.array(recon_signals[p])), axis=1) - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - # West Y - ax = axes[1, 0] - p = 5 - if p in active_planes: - t_prof = np.sum(np.abs(np.array(truth_signals[p])), axis=1) - r_prof = np.sum(np.abs(np.array(recon_signals[p])), axis=1) - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - # Energy trajectory - ax = axes[1, 1] - ax.plot(np.array(total_energies)/1000, 'k-', lw=1.5) - ax.axhline(truth_total_de/1000, color='b', ls=':', lw=1.5, - label=f'Truth={truth_total_de/1000:.1f} GeV') - ax.set_xlabel('Step', fontsize=14); ax.set_ylabel('Total Energy (GeV)', fontsize=14) - ax.set_title('Total Energy', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - # Histogram - ax = axes[2, 0] - alive_de = final_params[:, 3][final_params[:, 3] > DEFAULTS['death_thresh']] * 1000 - ax.hist(alive_de, bins=100, alpha=0.7, color='steelblue', - label=f'Alive ({len(alive_de):,})') - ax.axvline(DEFAULTS['death_thresh'] * 1000, color='r', ls='--', lw=1.5, - label=f'Dead ({n_dead_final:,})') - ax.set_xlabel('dE (keV)', fontsize=14) - ax.set_title('Segment Energy Distribution', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - axes[2, 1].axis('off') - - fig.suptitle(f'out.h5 event {event_idx} | 50k segs, s={SOBOLEV_S}, dx={DX_MM}mm | ' - f'{total_steps} steps\n' - f'loss={losses[-1]:.6f}, dE_ratio={de_ratio:.3f}, dead={n_dead_final}', - fontsize=15, fontweight='bold') - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'run_out_50k.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - # Save - np.savez_compressed(os.path.join(OUT_DIR, 'run_out_50k.npz'), - losses=np.array(losses), total_energies=np.array(total_energies), - dead_counts=np.array(dead_counts), final_params=final_params, - truth_total_de=truth_total_de, de_ratio=de_ratio, n_seg=n_seg) - print("Saved run_out_50k.npz") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_out_50k_4000.py b/closure/archive/segments_intermediate/run_out_50k_4000.py deleted file mode 100644 index e3750b8..0000000 --- a/closure/archive/segments_intermediate/run_out_50k_4000.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Run out.h5 event 2, 50k segments, 4000 steps with checkpoints.""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np, optax -from tools.geometry import generate_detector -from tools.config import SegmentData, DepositData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -def main(): - n_seg = 50000 - total_steps = 4000 - save_every = 10 - DX_MM = 0.3 - - deposit_data = load_particle_step_data('out.h5', 2) - n_truth = deposit_data.positions_mm.shape[0] - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - print(f"Truth: {n_truth:,} segs, e_scale={n_truth/n_seg:.2f}") - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - forced_deposit = DepositData( - positions_mm=deposit_data.positions_mm, de=deposit_data.de, - dx=np.full(n_truth, DX_MM, dtype=np.float32), - valid_mask=deposit_data.valid_mask, theta=deposit_data.theta, - phi=deposit_data.phi, track_ids=deposit_data.track_ids) - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - response_signals, _ = sim_truth(forced_deposit) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=1.0) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = DX_MM / 10.0 - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward(dx_mm=DX_MM) - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - print("JIT warmup...") - _ = grad_fn(init_params) - print("Done.\n") - - schedule = optax.exponential_decay(init_value=1.0, transition_steps=1, decay_rate=0.999) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - n_checkpoints = total_steps // save_every + 1 - checkpoint_steps, checkpoint_losses = [], [] - checkpoint_params = np.zeros((n_checkpoints, n_seg, 4), dtype=np.float32) - cumulative_relocs = 0 - t_start = time.time() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(0.003) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add(lr_cur * 0.3 * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= 100 and step % 25 == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, 100) - cumulative_relocs += int(n_reloc) - - if step % save_every == 0: - idx = step // save_every - checkpoint_steps.append(step) - checkpoint_losses.append(float(total_loss)) - checkpoint_params[idx] = np.array(params) - - if step % 200 == 0 or step == total_steps - 1: - print(f" Step {step:5d}: loss={float(total_loss):.6f} " - f"relocs={cumulative_relocs} ({time.time()-t_start:.0f}s)") - - save_path = os.path.join(OUT_DIR, 'best_run_out_50k_4000.npz') - np.savez_compressed(save_path, - checkpoint_steps=np.array(checkpoint_steps), - checkpoint_losses=np.array(checkpoint_losses), - checkpoint_params=checkpoint_params[:len(checkpoint_steps)], - truth_pos=truth_pos, truth_de=truth_de, - n_truth=n_truth, n_seg=n_seg, total_steps=total_steps, - truth_total_de=float(np.sum(truth_de)), - dx_mm=DX_MM, B_eff=B_eff, alpha=alpha_r, - ) - print(f"\nSaved to {save_path} ({os.path.getsize(save_path)/1e6:.1f} MB)") - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_out_50k_checkpoints.py b/closure/archive/segments_intermediate/run_out_50k_checkpoints.py deleted file mode 100644 index 03813ad..0000000 --- a/closure/archive/segments_intermediate/run_out_50k_checkpoints.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Run out.h5 event 2 with 50k segments, saving checkpoints for 3D viz.""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np, optax -from tools.geometry import generate_detector -from tools.config import SegmentData, DepositData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -def main(): - n_seg = 50000 - total_steps = 2000 - save_every = 10 - DX_MM = 0.3 - - deposit_data = load_particle_step_data('out.h5', 2) - n_truth = deposit_data.positions_mm.shape[0] - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - print(f"Truth: {n_truth:,} segs, e_scale={n_truth/n_seg:.2f}") - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - forced_deposit = DepositData( - positions_mm=deposit_data.positions_mm, de=deposit_data.de, - dx=np.full(n_truth, DX_MM, dtype=np.float32), - valid_mask=deposit_data.valid_mask, theta=deposit_data.theta, - phi=deposit_data.phi, track_ids=deposit_data.track_ids) - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - response_signals, _ = sim_truth(forced_deposit) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=1.0) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = DX_MM / 10.0 - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward(dx_mm=DX_MM) - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - print("JIT warmup...") - _ = grad_fn(init_params) - print("Done.\n") - - schedule = optax.exponential_decay(init_value=1.0, transition_steps=1, decay_rate=0.999) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - n_checkpoints = total_steps // save_every + 1 - checkpoint_steps, checkpoint_losses = [], [] - checkpoint_params = np.zeros((n_checkpoints, n_seg, 4), dtype=np.float32) - cumulative_relocs = 0 - t_start = time.time() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(0.003) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add(lr_cur * 0.3 * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= 100 and step % 25 == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, 100) - cumulative_relocs += int(n_reloc) - - if step % save_every == 0: - idx = step // save_every - checkpoint_steps.append(step) - checkpoint_losses.append(float(total_loss)) - checkpoint_params[idx] = np.array(params) - - if step % 200 == 0 or step == total_steps - 1: - print(f" Step {step:5d}: loss={float(total_loss):.6f} " - f"relocs={cumulative_relocs} ({time.time()-t_start:.0f}s)") - - save_path = os.path.join(OUT_DIR, 'best_run_out_50k_2000.npz') - np.savez_compressed(save_path, - checkpoint_steps=np.array(checkpoint_steps), - checkpoint_losses=np.array(checkpoint_losses), - checkpoint_params=checkpoint_params[:len(checkpoint_steps)], - truth_pos=truth_pos, truth_de=truth_de, - n_truth=n_truth, n_seg=n_seg, total_steps=total_steps, - truth_total_de=float(np.sum(truth_de)), - dx_mm=DX_MM, B_eff=B_eff, alpha=alpha_r, - ) - print(f"\nSaved to {save_path} ({os.path.getsize(save_path)/1e6:.1f} MB)") - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_s1_20k.py b/closure/archive/segments_intermediate/run_s1_20k.py deleted file mode 100644 index e4d839a..0000000 --- a/closure/archive/segments_intermediate/run_s1_20k.py +++ /dev/null @@ -1,241 +0,0 @@ -""" -Run 20k segments with Sobolev s=1.0 (instead of 1.5). -Saves checkpoints for 3D visualization comparison. - -Usage: - python3 closure_analysis_full/sweeps/run_s1_20k.py mpvmpr_20.h5 -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np, optax -import matplotlib.pyplot as plt - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -SOBOLEV_S = 1.0 # changed from 1.5 - - -def main(): - h5_path = sys.argv[1] if len(sys.argv) > 1 else 'mpvmpr_20.h5' - n_seg = 20000 - total_steps = 4000 - save_every = 10 - - lr, decay_rate, lr_e_mult = 1.0, 0.999, 0.003 - warmup, noise_lr, l1 = 100, 0.3, 0.0 - reloc_every, max_reloc = 25, 100 - recomb_model = 'modified_box' - - print(f"20k segments, Sobolev s={SOBOLEV_S} — {total_steps} steps") - print(f"lr={lr}, decay={decay_rate}, e_mult={lr_e_mult}") - print(f"File: {h5_path}\n") - - # Setup - deposit_data = load_particle_step_data(h5_path, 0) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model=recomb_model) - response_signals, _ = sim_truth(deposit_data) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=SOBOLEV_S) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - planes_tuple = tuple(active_planes) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, 0.05) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model=recomb_model) - fwd_opt = sim_opt.build_forward() - - def loss_fn(params): - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - sigs = fwd_opt(seg) - loss = sobolev_loss_geomean_log1p(sigs, truth_signals, spectral_weights, planes=planes_tuple) - return loss, loss - - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Init - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = truth_de[indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - print("JIT warmup...") - t0 = time.time() - _ = grad_fn(init_params) - print(f"Done in {time.time()-t0:.1f}s\n") - - # Training - schedule = optax.exponential_decay(init_value=lr, transition_steps=1, decay_rate=decay_rate) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - n_checkpoints = total_steps // save_every + 1 - checkpoint_steps = [] - checkpoint_losses = [] - checkpoint_params = np.zeros((n_checkpoints, n_seg, 4), dtype=np.float32) - cumulative_relocs = 0 - t_start = time.time() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(lr_e_mult) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add(lr_cur * noise_lr * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= warmup and step % reloc_every == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, max_reloc) - cumulative_relocs += int(n_reloc) - - if step % save_every == 0: - idx = step // save_every - checkpoint_steps.append(step) - checkpoint_losses.append(float(total_loss)) - checkpoint_params[idx] = np.array(params) - - if step % 200 == 0 or step == total_steps - 1: - total_e = float(jnp.sum(params[:, 3])) - n_dead = int(jnp.sum(params[:, 3] <= DEFAULTS['death_thresh'])) - print(f" Step {step:5d}: loss={float(total_loss):.6f} " - f"total_dE={total_e:.2f} dead={n_dead} " - f"relocs={cumulative_relocs} ({time.time()-t_start:.0f}s)") - - total_time = time.time() - t_start - final_params_np = np.array(params) - final_de_total = float(np.sum(final_params_np[:, 3])) - de_ratio = final_de_total / truth_total_de - n_dead_final = int(np.sum(final_params_np[:, 3] <= DEFAULTS['death_thresh'])) - - print(f"\nDone in {total_time:.0f}s ({total_time/total_steps*1000:.0f} ms/step)") - print(f"Final: loss={checkpoint_losses[-1]:.6f}, dE_ratio={de_ratio:.3f}, " - f"dead={n_dead_final}, relocs={cumulative_relocs}") - - # Save checkpoints - save_path = os.path.join(OUT_DIR, f'best_run_20k_s{SOBOLEV_S}_4000.npz') - np.savez_compressed(save_path, - checkpoint_steps=np.array(checkpoint_steps), - checkpoint_losses=np.array(checkpoint_losses), - checkpoint_params=checkpoint_params[:len(checkpoint_steps)], - truth_pos=truth_pos, truth_de=truth_de, - n_truth=n_truth, n_seg=n_seg, total_steps=total_steps, - truth_total_de=truth_total_de, sobolev_s=SOBOLEV_S, - ) - print(f"Saved checkpoints to {save_path} ({os.path.getsize(save_path)/1e6:.1f} MB)") - - # Diagnostic plot - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - recon_signals = fwd_opt(seg) - - fig, axes = plt.subplots(3, 2, figsize=(18, 20)) - - # Loss - ax = axes[0, 0] - ax.semilogy(checkpoint_losses, 'b-', lw=1.0, alpha=0.7) - ax.set_xlabel('Checkpoint', fontsize=14) - ax.set_ylabel('Loss', fontsize=14) - ax.set_title(f'Loss Convergence (Sobolev s={SOBOLEV_S})', fontsize=15) - ax.grid(True, alpha=0.3) - - # West U - ax = axes[0, 1] - p = 3 - if p in active_planes: - t_prof = np.sum(np.abs(np.array(truth_signals[p])), axis=1) - r_prof = np.sum(np.abs(np.array(recon_signals[p])), axis=1) - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal Comparison ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - # West Y - ax = axes[1, 0] - p = 5 - if p in active_planes: - t_prof = np.sum(np.abs(np.array(truth_signals[p])), axis=1) - r_prof = np.sum(np.abs(np.array(recon_signals[p])), axis=1) - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal Comparison ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - # Energy trajectory - ax = axes[1, 1] - # Compute from checkpoints - cp_energies = [float(checkpoint_params[i][:, 3].sum()) for i in range(0, len(checkpoint_steps), 10)] - ax.plot(cp_energies, 'k-', lw=1.5) - ax.axhline(truth_total_de, color='b', ls=':', lw=1.5, label=f'Truth={truth_total_de:.0f}') - ax.set_title('Total Energy Trajectory', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - # Histogram - ax = axes[2, 0] - alive_de = final_params_np[:, 3][final_params_np[:, 3] > DEFAULTS['death_thresh']] * 1000 - ax.hist(alive_de, bins=100, alpha=0.7, color='steelblue', - label=f'Alive ({len(alive_de):,})') - ax.axvline(DEFAULTS['death_thresh'] * 1000, color='r', ls='--', lw=1.5, - label=f'Death thresh ({n_dead_final:,} dead)') - ax.set_xlabel('dE (keV)', fontsize=14) - ax.set_title('Final Segment Energy Distribution', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - axes[2, 1].axis('off') - - fig.suptitle(f'20k segments, Sobolev s={SOBOLEV_S} | {total_steps} steps\n' - f'loss={checkpoint_losses[-1]:.6f}, dE_ratio={de_ratio:.3f}, ' - f'dead={n_dead_final}', fontsize=15, fontweight='bold') - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'run_20k_s{SOBOLEV_S}_4000steps.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_sweep.py b/closure/archive/segments_intermediate/run_sweep.py deleted file mode 100644 index 2d7423b..0000000 --- a/closure/archive/segments_intermediate/run_sweep.py +++ /dev/null @@ -1,298 +0,0 @@ -""" -Standalone sweep runner. Does NOT modify source code. -Writes results to sweeps/ folder as NPZ + text summary. - -Usage: - python3 closure_analysis_full/sweeps/run_sweep.py mpvmpr_20.h5 --sweep lr_decay - python3 closure_analysis_full/sweeps/run_sweep.py mpvmpr_20.h5 --sweep steps - python3 closure_analysis_full/sweeps/run_sweep.py mpvmpr_20.h5 --sweep nseg -""" - -import sys, os, argparse, time, json -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax -import jax.numpy as jnp -import numpy as np - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import ( - DEFAULTS, PLANE_NAMES, build_loss_fn, run_training_loop, -) - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -# ========================================================================= -# Sweep definitions -# ========================================================================= - -SWEEPS = { - 'lr_decay': { - 'description': 'LR x decay_rate sweep (lr_e_mult=0.003 fixed)', - 'combos': [ - {'name': 'lr03_d9995', 'lr': 0.3, 'decay_rate': 0.9995}, - {'name': 'lr05_d9995', 'lr': 0.5, 'decay_rate': 0.9995}, - {'name': 'lr07_d999', 'lr': 0.7, 'decay_rate': 0.999}, - {'name': 'lr10_d999', 'lr': 1.0, 'decay_rate': 0.999}, - {'name': 'lr07_d9995', 'lr': 0.7, 'decay_rate': 0.9995}, - {'name': 'lr10_d9995', 'lr': 1.0, 'decay_rate': 0.9995}, - ], - 'fixed': {'lr_e_mult': 0.003, 'n_seg': 10000, 'steps': 1500}, - }, - 'lr_decay_fine': { - 'description': 'Fine lr x decay around best region', - 'combos': [ - {'name': 'lr05_d999', 'lr': 0.5, 'decay_rate': 0.999}, - {'name': 'lr05_d9998', 'lr': 0.5, 'decay_rate': 0.9998}, - {'name': 'lr07_d9993', 'lr': 0.7, 'decay_rate': 0.9993}, - {'name': 'lr07_d9997', 'lr': 0.7, 'decay_rate': 0.9997}, - ], - 'fixed': {'lr_e_mult': 0.003, 'n_seg': 10000, 'steps': 1500}, - }, - 'steps': { - 'description': 'Step count sweep at best lr/decay', - 'combos': [ - {'name': 'steps_1000', 'steps_override': 1000}, - {'name': 'steps_1500', 'steps_override': 1500}, - {'name': 'steps_2000', 'steps_override': 2000}, - {'name': 'steps_3000', 'steps_override': 3000}, - ], - 'fixed': {'lr': 0.5, 'decay_rate': 0.9995, 'lr_e_mult': 0.003, 'n_seg': 10000}, - }, - 'warmup': { - 'description': 'Warmup length sweep', - 'combos': [ - {'name': 'warmup_100', 'warmup': 100}, - {'name': 'warmup_200', 'warmup': 200}, - {'name': 'warmup_300', 'warmup': 300}, - {'name': 'warmup_500', 'warmup': 500}, - ], - 'fixed': {'lr': 0.5, 'decay_rate': 0.9995, 'lr_e_mult': 0.003, 'n_seg': 10000, 'steps': 1500}, - }, -} - - -def setup_shared(h5_path, event_idx, n_seg, recomb_model): - """Shared setup: load data, truth sim, optimizer sim, init params.""" - print("Loading event data...") - deposit_data = load_particle_step_data(h5_path, event_idx) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - print(f" {n_truth:,} segments, total dE={truth_total_de:.2f} MeV") - - print("Generating truth signals...") - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = max(200_000, n_truth + 1000) - total_pad = ((total_pad + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator( - detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, - include_electronics=False, include_track_hits=False, - recombination_model=recomb_model) - t0 = time.time() - response_signals, _ = sim_truth(deposit_data) - print(f" Truth sim done in {time.time()-t0:.1f}s") - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=1.5) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - print(f" Active planes: {[PLANE_NAMES[p] for p in active_planes]}") - - # Recomb constants for relocation - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = 0.05 # 0.5mm - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - # Build optimizer sim - print(f"Building differentiable simulator (n_seg={n_seg:,})...") - sim_opt = DetectorSimulator( - detector_config, differentiable=True, n_segments=n_seg, - recombination_model=recomb_model) - fwd_opt = sim_opt.build_forward() - - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Init params - print("Initializing optimizer segments...") - rng = np.random.RandomState(42) - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - e_scale = n_truth / n_seg - replace = n_seg > n_truth - indices = rng.choice(n_truth, size=n_seg, replace=replace) - init_pos = truth_pos[indices].copy() - init_de = truth_de[indices].copy() * e_scale - init_pos += rng.normal(0, DEFAULTS['pos_jitter_mm'], size=(n_seg, 3)) - init_de *= rng.uniform( - 1.0 - DEFAULTS['e_jitter_frac'], - 1.0 + DEFAULTS['e_jitter_frac'], size=n_seg) - init_de = np.maximum(init_de, DEFAULTS['min_energy']) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - print(f" e_scale={e_scale:.2f}, init total dE={float(jnp.sum(init_params[:, 3])):.2f} MeV") - - # JIT warmup - print("Warming up JIT...") - t0 = time.time() - _ = grad_fn(init_params) - print(f"JIT warm-up done in {time.time()-t0:.1f}s\n") - - return { - 'grad_fn': grad_fn, - 'init_params': init_params, - 'n_seg': n_seg, - 'truth_total_de': truth_total_de, - 'recomb_constants': recomb_constants, - 'n_truth': n_truth, - } - - -def run_combo(shared, combo, fixed, mode='full'): - """Run a single combo and return results.""" - cfg = dict(DEFAULTS) - cfg['noise_lr'] = 0.0 - cfg['l1'] = 0.0 - cfg['reloc_every'] = 25 - cfg['max_reloc'] = 100 - cfg['recomb_constants'] = shared['recomb_constants'] - - # Apply fixed settings, then combo overrides - cfg.update(fixed) - cfg.update(combo) - - n_seg = cfg.pop('n_seg', shared['n_seg']) - total_steps = cfg.pop('steps_override', cfg.pop('steps', 1500)) - - name = combo['name'] - print(f"[{name}] lr={cfg['lr']}, decay={cfg['decay_rate']}, " - f"e_mult={cfg['lr_e_mult']}, warmup={cfg['warmup']}, " - f"steps={total_steps}...") - - t0 = time.time() - result = run_training_loop( - shared['grad_fn'], shared['init_params'], shared['n_seg'], - total_steps, mode, cfg) - dt = time.time() - t0 - - final_de = float(np.sum(result['final_params'][:, 3])) - de_ratio = final_de / shared['truth_total_de'] - - print(f" loss={result['losses'][-1]:.6f} dE_ratio={de_ratio:.3f} " - f"dead={result['dead_counts'][-1]} {dt:.0f}s\n") - - return { - 'name': name, - 'losses': result['losses'], - 'total_energies': result['total_energies'], - 'dead_counts': result['dead_counts'], - 'final_loss': float(result['losses'][-1]), - 'de_ratio': de_ratio, - 'total_steps': total_steps, - **{k: v for k, v in combo.items() if k != 'name'}, - **{k: v for k, v in fixed.items()}, - 'time_s': dt, - } - - -def main(): - parser = argparse.ArgumentParser(description='Systematic sweep runner') - parser.add_argument('h5_path', help='Path to HDF5 event file') - parser.add_argument('--sweep', required=True, choices=list(SWEEPS.keys())) - parser.add_argument('--event', type=int, default=0) - parser.add_argument('--recomb', type=str, default='modified_box') - parser.add_argument('--mode', type=str, default='full', - choices=['baseline', 'full']) - args = parser.parse_args() - - sweep_def = SWEEPS[args.sweep] - combos = sweep_def['combos'] - fixed = sweep_def['fixed'] - n_seg = fixed.get('n_seg', 10000) - - print(f"{'='*70}") - print(f"SWEEP: {args.sweep} — {sweep_def['description']}") - print(f" {len(combos)} combos, mode={args.mode}, recomb={args.recomb}") - print(f" Fixed: {fixed}") - print(f"{'='*70}\n") - - shared = setup_shared(args.h5_path, args.event, n_seg, args.recomb) - - all_results = [] - for combo in combos: - r = run_combo(shared, combo, fixed, mode=args.mode) - all_results.append(r) - - # Summary - print(f"\n{'='*70}") - print(f"SUMMARY — {args.sweep}") - print(f"{'='*70}") - - # Build header from combo keys - combo_keys = [k for k in combos[0].keys() if k != 'name'] - header = f"{'Name':<20}" - for k in combo_keys: - header += f" {k:>12}" - header += f" {'Loss':>10} {'dE_ratio':>10} {'Dead':>6} {'Time':>6}" - print(header) - print("-" * len(header)) - - for r in all_results: - line = f"{r['name']:<20}" - for k in combo_keys: - v = r.get(k, '') - if isinstance(v, float): - line += f" {v:>12.4f}" - else: - line += f" {str(v):>12}" - line += f" {r['final_loss']:>10.6f} {r['de_ratio']:>10.3f}" - line += f" {r['dead_counts'][-1]:>6d} {r['time_s']:>5.0f}s" - print(line) - - # Save - save_path = os.path.join(OUT_DIR, f'sweep_{args.sweep}.npz') - save_data = {'sweep_name': args.sweep, 'mode': args.mode} - for r in all_results: - prefix = r['name'] - save_data[f'{prefix}_losses'] = r['losses'] - save_data[f'{prefix}_total_energies'] = r['total_energies'] - save_data[f'{prefix}_dead_counts'] = r['dead_counts'] - save_data[f'{prefix}_final_loss'] = r['final_loss'] - save_data[f'{prefix}_de_ratio'] = r['de_ratio'] - save_data['combo_names'] = np.array([c['name'] for c in combos]) - np.savez(save_path, **save_data) - print(f"\nSaved to {save_path}") - - # Also save text summary - txt_path = os.path.join(OUT_DIR, f'sweep_{args.sweep}.txt') - with open(txt_path, 'w') as f: - f.write(f"Sweep: {args.sweep}\n") - f.write(f"Description: {sweep_def['description']}\n") - f.write(f"Mode: {args.mode}, Recomb: {args.recomb}\n") - f.write(f"Fixed: {fixed}\n\n") - for r in all_results: - f.write(f"{r['name']}: loss={r['final_loss']:.6f}, " - f"dE_ratio={r['de_ratio']:.3f}, " - f"dead={r['dead_counts'][-1]}, " - f"steps={r['total_steps']}, time={r['time_s']:.0f}s\n") - print(f"Saved to {txt_path}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_track_jitter.py b/closure/archive/segments_intermediate/run_track_jitter.py deleted file mode 100644 index 17c9633..0000000 --- a/closure/archive/segments_intermediate/run_track_jitter.py +++ /dev/null @@ -1,292 +0,0 @@ -""" -Run out.h5 event 2 with per-track 50mm jitter initialization. -50k segments, s=1.0, dx=0.3mm matched. -Saves checkpoints + diagnostic plot. - -Usage: - python3 closure_analysis_full/sweeps/run_track_jitter.py -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np, optax -import matplotlib.pyplot as plt - -from tools.geometry import generate_detector -from tools.config import SegmentData, DepositData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -SOBOLEV_S = 1.0 -DX_MM = 0.3 -W_ION = 23.6e-6 -ALPHA_RECOMB = 0.93 - - -def main(): - n_seg = 50000 - total_steps = 2000 - save_every = 10 - track_jitter_mm = 50.0 - e_jitter_frac = 0.8 - - lr, decay_rate, lr_e_mult = 1.0, 0.999, 0.003 - warmup, noise_lr = 100, 0.3 - reloc_every, max_reloc = 25, 100 - - print(f"Per-track jitter run: {track_jitter_mm}mm, {n_seg} segs, {total_steps} steps") - print(f"s={SOBOLEV_S}, dx={DX_MM}mm, e_jitter=±{e_jitter_frac*100:.0f}%\n") - - # Load - deposit_data = load_particle_step_data('out.h5', 2) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - truth_tids = np.asarray(deposit_data.track_ids) - print(f"Truth: {n_truth:,} segs, {len(np.unique(truth_tids)):,} tracks, " - f"dE={truth_total_de:.1f} MeV") - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - # Truth sim with forced dx - forced_deposit = DepositData( - positions_mm=deposit_data.positions_mm, de=deposit_data.de, - dx=np.full(n_truth, DX_MM, dtype=np.float32), - valid_mask=deposit_data.valid_mask, theta=deposit_data.theta, - phi=deposit_data.phi, track_ids=deposit_data.track_ids) - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - response_signals, _ = sim_truth(forced_deposit) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=SOBOLEV_S) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - planes_tuple = tuple(active_planes) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = DX_MM / 10.0 - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - # Per-track jitter initialization - print(f"Initializing with per-track {track_jitter_mm}mm jitter...") - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - - # Subsample - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() - init_de = truth_de[indices].copy() * e_scale - init_tids = truth_tids[indices] - - # Per-track jitter: same displacement for all segments in a track - unique_tids = np.unique(init_tids) - track_displacements = {} - for tid in unique_tids: - track_displacements[tid] = rng.normal(0, track_jitter_mm, size=3) - for i in range(n_seg): - init_pos[i] += track_displacements[init_tids[i]] - - # Energy jitter (per-segment, independent) - init_de *= rng.uniform(1.0 - e_jitter_frac, 1.0 + e_jitter_frac, size=n_seg) - init_de = np.maximum(init_de, 0.001) - - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - # Measure init displacement - orig_pos = truth_pos[indices] - displacements = np.sqrt(np.sum((init_pos - orig_pos)**2, axis=1)) - print(f" Mean displacement: {displacements.mean():.1f}mm ({displacements.mean()/3:.0f} wire pitches)") - print(f" Total init dE: {float(jnp.sum(init_params[:, 3])):.1f} MeV") - - # Optimizer sim - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward(dx_mm=DX_MM) - - def loss_fn(params): - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - sigs = fwd_opt(seg) - return sobolev_loss_geomean_log1p(sigs, truth_signals, spectral_weights, - planes=planes_tuple), None - - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - print("JIT warmup...") - t0 = time.time() - _ = grad_fn(init_params) - print(f"Done in {time.time()-t0:.1f}s\n") - - # Training - schedule = optax.exponential_decay(init_value=lr, transition_steps=1, decay_rate=decay_rate) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - n_checkpoints = total_steps // save_every + 1 - checkpoint_steps, checkpoint_losses = [], [] - checkpoint_params = np.zeros((n_checkpoints, n_seg, 4), dtype=np.float32) - - losses = [] - q_ratios = [] - de_ratios = [] - cumulative_relocs = 0 - t_start = time.time() - - def compute_Q(de_arr): - return (dx_cm / B_eff) * np.log(np.maximum(ALPHA_RECOMB + B_eff * de_arr / dx_cm, 1.0)) - - truth_total_Q = compute_Q(truth_de).sum() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(lr_e_mult) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add(lr_cur * noise_lr * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= warmup and step % reloc_every == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, max_reloc) - cumulative_relocs += int(n_reloc) - - loss_val = float(total_loss) - losses.append(loss_val) - - if step % save_every == 0: - idx = step // save_every - checkpoint_steps.append(step) - checkpoint_losses.append(loss_val) - checkpoint_params[idx] = np.array(params) - - if step % 100 == 0 or step == total_steps - 1: - p_np = np.array(params) - alive = p_np[:, 3] > 0.012 - sim_Q = compute_Q(p_np[alive, 3]).sum() - q_ratio = sim_Q / truth_total_Q - de_ratio = p_np[:, 3].sum() / truth_total_de - q_ratios.append((step, q_ratio)) - de_ratios.append((step, de_ratio)) - n_dead = int((~alive).sum()) - print(f" Step {step:5d}: loss={loss_val:.6f} Q_ratio={q_ratio:.3f} " - f"dE_ratio={de_ratio:.3f} dead={n_dead} ({time.time()-t_start:.0f}s)") - - total_time = time.time() - t_start - final_params = np.array(params) - print(f"\nDone in {total_time:.0f}s ({total_time/total_steps*1000:.0f} ms/step)") - - # Save checkpoints - save_path = os.path.join(OUT_DIR, 'track_jitter_50k.npz') - np.savez_compressed(save_path, - checkpoint_steps=np.array(checkpoint_steps), - checkpoint_losses=np.array(checkpoint_losses), - checkpoint_params=checkpoint_params[:len(checkpoint_steps)], - truth_pos=truth_pos, truth_de=truth_de, - n_truth=n_truth, n_seg=n_seg, total_steps=total_steps, - truth_total_de=truth_total_de, dx_mm=DX_MM, B_eff=B_eff, alpha=alpha_r, - track_jitter_mm=track_jitter_mm, - ) - print(f"Saved checkpoints to {save_path}") - - # Recon signals for plotting - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - recon_signals = fwd_opt(seg) - - # Diagnostic plot - fig, axes = plt.subplots(3, 2, figsize=(18, 20)) - - # Loss - ax = axes[0, 0] - ax.semilogy(losses, 'b-', lw=1.0, alpha=0.7) - ax.set_xlabel('Step', fontsize=14); ax.set_ylabel('Loss', fontsize=14) - ax.set_title(f'Loss (track jitter {track_jitter_mm}mm)', fontsize=15) - ax.grid(True, alpha=0.3) - - # West U - ax = axes[0, 1] - p = 3 - if p in active_planes: - t_prof = np.sum(np.abs(np.array(truth_signals[p])), axis=1) - r_prof = np.sum(np.abs(np.array(recon_signals[p])), axis=1) - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - # West Y - ax = axes[1, 0] - p = 5 - if p in active_planes: - t_prof = np.sum(np.abs(np.array(truth_signals[p])), axis=1) - r_prof = np.sum(np.abs(np.array(recon_signals[p])), axis=1) - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - # Q ratio vs dE ratio - ax = axes[1, 1] - q_steps, q_vals = zip(*q_ratios) - de_steps, de_vals = zip(*de_ratios) - ax.plot(q_steps, q_vals, 'b-', lw=2, label='Q ratio') - ax.plot(de_steps, de_vals, 'r-', lw=2, label='dE ratio') - ax.axhline(1.0, color='green', ls='--', lw=1.5, alpha=0.5, label='Target=1.0') - ax.set_xlabel('Step', fontsize=14); ax.set_ylabel('Ratio (sim/truth)', fontsize=14) - ax.set_title('Q Ratio vs dE Ratio', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - # Energy histogram - ax = axes[2, 0] - alive_de = final_params[:, 3][final_params[:, 3] > 0.012] * 1000 - n_dead = len(final_params) - len(alive_de) - ax.hist(alive_de, bins=100, alpha=0.7, color='steelblue', - label=f'Alive ({len(alive_de):,})') - ax.axvline(0.012 * 1000, color='r', ls='--', lw=1.5, - label=f'Dead ({n_dead:,})') - ax.set_xlabel('dE (keV)', fontsize=14) - ax.set_title('Segment Energy Distribution', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3) - - axes[2, 1].axis('off') - - fig.suptitle(f'out.h5 ev2 | 50k segs, per-track {track_jitter_mm}mm jitter, s={SOBOLEV_S}\n' - f'loss={losses[-1]:.6f}, Q_ratio={q_vals[-1]:.3f}, dE_ratio={de_vals[-1]:.3f}', - fontsize=15, fontweight='bold') - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'track_jitter_50k.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/run_track_jitter_v2.py b/closure/archive/segments_intermediate/run_track_jitter_v2.py deleted file mode 100644 index 6eff8bd..0000000 --- a/closure/archive/segments_intermediate/run_track_jitter_v2.py +++ /dev/null @@ -1,266 +0,0 @@ -"""Per-track 50mm jitter, 50k segs, s=1.0, dx=0.3mm. More checkpoints, U/V/Y planes.""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np, optax -import matplotlib.pyplot as plt - -from tools.geometry import generate_detector -from tools.config import SegmentData, DepositData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -SOBOLEV_S = 1.0 -DX_MM = 0.3 -W_ION = 23.6e-6 -ALPHA_RECOMB = 0.93 - - -def main(): - n_seg = 50000 - total_steps = 2000 - save_every = 5 # more checkpoints - track_jitter_mm = 50.0 - e_jitter_frac = 0.8 - - lr, decay_rate, lr_e_mult = 1.0, 0.999, 0.003 - warmup, noise_lr = 100, 0.3 - reloc_every, max_reloc = 25, 100 - - print(f"Per-track jitter v2: {track_jitter_mm}mm, {n_seg} segs, {total_steps} steps") - print(f"Checkpoints every {save_every} steps\n") - - deposit_data = load_particle_step_data('out.h5', 2) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - truth_tids = np.asarray(deposit_data.track_ids) - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - forced_deposit = DepositData( - positions_mm=deposit_data.positions_mm, de=deposit_data.de, - dx=np.full(n_truth, DX_MM, dtype=np.float32), - valid_mask=deposit_data.valid_mask, theta=deposit_data.theta, - phi=deposit_data.phi, track_ids=deposit_data.track_ids) - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - response_signals, _ = sim_truth(forced_deposit) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=SOBOLEV_S) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - planes_tuple = tuple(active_planes) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = DX_MM / 10.0 - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - # Per-track jitter init - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() - init_de = truth_de[indices].copy() * e_scale - init_tids = truth_tids[indices] - - unique_tids = np.unique(init_tids) - for tid in unique_tids: - disp = rng.normal(0, track_jitter_mm, size=3) - mask = init_tids == tid - init_pos[mask] += disp - - init_de *= rng.uniform(1.0 - e_jitter_frac, 1.0 + e_jitter_frac, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward(dx_mm=DX_MM) - - def loss_fn(params): - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - sigs = fwd_opt(seg) - return sobolev_loss_geomean_log1p(sigs, truth_signals, spectral_weights, - planes=planes_tuple), None - - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - print("JIT warmup...") - _ = grad_fn(init_params) - print("Done.\n") - - schedule = optax.exponential_decay(init_value=lr, transition_steps=1, decay_rate=decay_rate) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - n_checkpoints = total_steps // save_every + 1 - checkpoint_steps, checkpoint_losses = [], [] - checkpoint_params = np.zeros((n_checkpoints, n_seg, 4), dtype=np.float32) - - def compute_Q(de_arr): - return (dx_cm / B_eff) * np.log(np.maximum(ALPHA_RECOMB + B_eff * de_arr / dx_cm, 1.0)) - - truth_total_Q = compute_Q(truth_de).sum() - losses, q_ratios = [], [] - cumulative_relocs = 0 - t_start = time.time() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(lr_e_mult) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add(lr_cur * noise_lr * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= warmup and step % reloc_every == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, max_reloc) - cumulative_relocs += int(n_reloc) - - loss_val = float(total_loss) - losses.append(loss_val) - - if step % save_every == 0: - idx = step // save_every - checkpoint_steps.append(step) - checkpoint_losses.append(loss_val) - checkpoint_params[idx] = np.array(params) - - if step % 100 == 0 or step == total_steps - 1: - p_np = np.array(params) - alive = p_np[:, 3] > 0.012 - sim_Q = compute_Q(p_np[alive, 3]).sum() - q_ratio = sim_Q / truth_total_Q - q_ratios.append((step, q_ratio)) - print(f" Step {step:5d}: loss={loss_val:.6f} Q_ratio={q_ratio:.3f} " - f"dead={int((~alive).sum())} ({time.time()-t_start:.0f}s)") - - final_params = np.array(params) - print(f"\nDone in {time.time()-t_start:.0f}s") - - # Save checkpoints - save_path = os.path.join(OUT_DIR, 'track_jitter_v2_50k.npz') - np.savez_compressed(save_path, - checkpoint_steps=np.array(checkpoint_steps), - checkpoint_losses=np.array(checkpoint_losses), - checkpoint_params=checkpoint_params[:len(checkpoint_steps)], - truth_pos=truth_pos, truth_de=truth_de, - n_truth=n_truth, n_seg=n_seg, total_steps=total_steps, - truth_total_de=truth_total_de, dx_mm=DX_MM, B_eff=B_eff, alpha=alpha_r, - track_jitter_mm=track_jitter_mm, - ) - print(f"Saved {save_path}") - - # Recon signals - seg = SegmentData(positions_mm=params[:, :3], de=params[:, 3]) - recon_signals = fwd_opt(seg) - - # Plot: 3x2 — loss, Q ratio, west_U, west_V, west_Y, energy hist - fig, axes = plt.subplots(3, 2, figsize=(18, 20)) - - # Loss - ax = axes[0, 0] - ax.semilogy(losses, 'b-', lw=1.0, alpha=0.7) - ax.set_xlabel('Step', fontsize=14); ax.set_ylabel('Loss', fontsize=14) - ax.set_title(f'Loss (track jitter {track_jitter_mm}mm)', fontsize=15) - ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # Q ratio - ax = axes[0, 1] - q_steps, q_vals = zip(*q_ratios) - ax.plot(q_steps, q_vals, 'b-', lw=2, label='Q ratio (sim/truth)') - ax.axhline(1.0, color='green', ls='--', lw=1.5, alpha=0.5) - ax.set_xlabel('Step', fontsize=14); ax.set_ylabel('Q Ratio', fontsize=14) - ax.set_title('Charge Conservation', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # West U - ax = axes[1, 0] - p = 3 - if p in active_planes: - t_prof = np.sum(np.abs(np.array(truth_signals[p])), axis=1) - r_prof = np.sum(np.abs(np.array(recon_signals[p])), axis=1) - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # West V - ax = axes[1, 1] - p = 4 - if p in active_planes: - t_prof = np.sum(np.abs(np.array(truth_signals[p])), axis=1) - r_prof = np.sum(np.abs(np.array(recon_signals[p])), axis=1) - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # West Y - ax = axes[2, 0] - p = 5 - if p in active_planes: - t_prof = np.sum(np.abs(np.array(truth_signals[p])), axis=1) - r_prof = np.sum(np.abs(np.array(recon_signals[p])), axis=1) - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # Energy histogram - ax = axes[2, 1] - alive_de = final_params[:, 3][final_params[:, 3] > 0.012] * 1000 - n_dead = len(final_params) - len(alive_de) - ax.hist(alive_de, bins=100, alpha=0.7, color='steelblue', - label=f'Alive ({len(alive_de):,})') - ax.axvline(0.012 * 1000, color='r', ls='--', lw=1.5, label=f'Dead ({n_dead:,})') - ax.set_xlabel('dE (keV)', fontsize=14) - ax.set_title('Segment Energy Distribution', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - fig.suptitle(f'out.h5 ev2 | 50k segs, per-track {track_jitter_mm}mm jitter, s={SOBOLEV_S}\n' - f'loss={losses[-1]:.6f}, Q_ratio={q_vals[-1]:.3f}', - fontsize=15, fontweight='bold') - fig.tight_layout() - fname = os.path.join(OUT_DIR, 'track_jitter_v2_50k.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/sweep.py b/closure/archive/segments_intermediate/sweep.py deleted file mode 100644 index 34e6bb4..0000000 --- a/closure/archive/segments_intermediate/sweep.py +++ /dev/null @@ -1,237 +0,0 @@ -""" -Hyperparameter sweep for full event closure analysis. - -Runs multiple hyperparameter combinations with shared truth signals -and JIT-compiled gradient function. Truth generation runs once; -optimizer runs per combo. Results saved to NPZ for later analysis. - -Run from project root: - python3 closure_analysis_full/sweep.py mpvmpr_20.h5 --n-seg 10000 --steps 1000 -""" - -import sys, os, argparse, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -import jax -import jax.numpy as jnp -import numpy as np - -from tools.geometry import generate_detector -from tools.config import SegmentData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight -from closure_analysis_full.full_closure import ( - DEFAULTS, PLANE_NAMES, - build_loss_fn, run_training_loop, -) - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -# lr x decay sweep with relocation, no noise/L1 -COMBOS = [ - {'name': 'lr10_d999', 'lr': 1.0, 'decay_rate': 0.999}, -] - - -def main(): - parser = argparse.ArgumentParser( - description='Full closure hyperparameter sweep') - parser.add_argument('h5_path', help='Path to HDF5 event file') - parser.add_argument('--event', type=int, default=0) - parser.add_argument('--n-seg', type=int, default=10000) - parser.add_argument('--steps', type=int, default=1000) - parser.add_argument('--mode', choices=['baseline', 'noise', 'full'], - default='baseline') - parser.add_argument('--recomb', type=str, default='modified_box', - choices=['modified_box', 'emb']) - args = parser.parse_args() - - n_seg = args.n_seg - total_steps = args.steps - mode = args.mode - - print(f"Full Closure Sweep — {len(COMBOS)} combos, " - f"{total_steps} steps, mode={mode}") - print(f"File: {args.h5_path}, event={args.event}, n_seg={n_seg:,}") - print(f"Recomb: {args.recomb}\n") - - # ================================================================= - # Shared setup (runs once) - # ================================================================= - - print("Loading event data...") - deposit_data = load_particle_step_data(args.h5_path, args.event) - n_truth = deposit_data.positions_mm.shape[0] - truth_total_de = float(np.sum(deposit_data.de)) - print(f" {n_truth:,} segments, total dE={truth_total_de:.2f} MeV") - - print("Generating truth signals...") - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = max(200_000, n_truth + 1000) - total_pad = ((total_pad + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator( - detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, - include_electronics=False, include_track_hits=False, - recombination_model=args.recomb) - - t0 = time.time() - response_signals, _ = sim_truth(deposit_data) - print(f" Truth sim done in {time.time() - t0:.1f}s") - - # Build 6-element tuples - truth_signals_dict = {} - active_planes = [] - sob_weights_dict = {} - for (side, plane), signal in response_signals.items(): - plane_idx = side * 3 + plane - signal = jnp.asarray(signal) - truth_signals_dict[plane_idx] = signal - if jnp.any(signal != 0): - active_planes.append(plane_idx) - sob_weights_dict[plane_idx] = make_sobolev_weight(*signal.shape, s=1.5) - active_planes.sort() - - truth_signals = tuple( - truth_signals_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - spectral_weights = tuple( - sob_weights_dict.get(i, jnp.zeros((1, 1))) for i in range(6)) - print(f" Active planes: {[PLANE_NAMES[p] for p in active_planes]}") - - # Differentiable optimizer simulator - print(f"Building differentiable simulator (n_seg={n_seg:,})...") - sim_opt = DetectorSimulator( - detector_config, differentiable=True, n_segments=n_seg, - recombination_model=args.recomb) - fwd_opt = sim_opt.build_forward() - - # Shared loss + grad - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, - active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Shared init params (subsample + jitter + e_scale) - print("Initializing optimizer segments...") - rng = np.random.RandomState(42) - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - - e_scale = n_truth / n_seg - replace = n_seg > n_truth - indices = rng.choice(n_truth, size=n_seg, replace=replace) - init_pos = truth_pos[indices].copy() - init_de = truth_de[indices].copy() * e_scale - - init_pos += rng.normal(0, DEFAULTS['pos_jitter_mm'], size=(n_seg, 3)) - init_de *= rng.uniform( - 1.0 - DEFAULTS['e_jitter_frac'], - 1.0 + DEFAULTS['e_jitter_frac'], size=n_seg) - init_de = np.maximum(init_de, DEFAULTS['min_energy']) - - init_params = jnp.array(np.column_stack([init_pos, init_de])) - init_total = float(jnp.sum(init_params[:, 3])) - print(f" e_scale={e_scale:.2f}, init total dE={init_total:.2f} MeV") - - # JIT warmup - print("Warming up JIT...") - t0 = time.time() - _ = grad_fn(init_params) - print(f"JIT warm-up done in {time.time() - t0:.1f}s\n") - - # ================================================================= - # Run combos - # ================================================================= - - all_results = {} - - # Compute recomb constants for relocation (needed for full mode) - from tools.recombination import extract_recombination_params - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = 0.05 # 0.5mm - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - for combo in COMBOS: - cfg = dict(DEFAULTS) - cfg['lr'] = 0.5 - cfg['decay_rate'] = 0.9995 - cfg['lr_e_mult'] = 0.003 - cfg['noise_lr'] = 0.0 - cfg['l1'] = 0.0 - cfg['reloc_every'] = 25 - cfg['max_reloc'] = 100 - cfg['recomb_model'] = args.recomb - cfg['recomb_constants'] = recomb_constants - cfg.update(combo) - - print(f"[{combo['name']}] lr={cfg['lr']}, decay={cfg['decay_rate']}...") - t0 = time.time() - result = run_training_loop( - grad_fn, init_params, n_seg, total_steps, mode, cfg) - dt = time.time() - t0 - - final_de = float(np.sum(result['final_params'][:, 3])) - de_ratio = final_de / truth_total_de if truth_total_de > 0 else 0 - - print(f" loss={result['losses'][-1]:.6f} " - f"dE_ratio={de_ratio:.3f} " - f"dead={result['dead_counts'][-1]} " - f"{dt:.0f}s\n") - - all_results[combo['name']] = { - 'losses': result['losses'], - 'total_energies': result['total_energies'], - 'dead_counts': result['dead_counts'], - 'final_loss': result['losses'][-1], - 'de_ratio': de_ratio, - 'lr': cfg['lr'], - 'decay_rate': cfg['decay_rate'], - 'lr_e_mult': cfg['lr_e_mult'], - } - - # ================================================================= - # Summary table - # ================================================================= - - print(f"\n{'=' * 70}") - print(f"SUMMARY — {n_seg:,} segs, {total_steps} steps, mode={mode}, " - f"lr_e_mult=0.003") - print(f"{'=' * 70}") - print(f"{'Name':<20} {'LR':>6} {'Decay':>8} {'Final Loss':>12} " - f"{'dE_ratio':>10} {'Dead':>6}") - print("-" * 65) - for name in [c['name'] for c in COMBOS]: - r = all_results[name] - print(f"{name:<20} {r.get('lr', 0.5):>6.2f} {r.get('decay_rate', 0.9995):>8.4f} " - f"{r['final_loss']:>12.6f} {r['de_ratio']:>10.3f} " - f"{r['dead_counts'][-1]:>6d}") - - # ================================================================= - # Save results - # ================================================================= - - save_path = os.path.join(OUT_DIR, 'sweep_results.npz') - save_data = {} - for name, r in all_results.items(): - save_data[f'{name}_losses'] = r['losses'] - save_data[f'{name}_total_energies'] = r['total_energies'] - save_data[f'{name}_dead_counts'] = r['dead_counts'] - save_data[f'{name}_final_loss'] = r['final_loss'] - save_data[f'{name}_de_ratio'] = r['de_ratio'] - save_data[f'{name}_lr_e_mult'] = r['lr_e_mult'] - - save_data['combo_names'] = np.array([c['name'] for c in COMBOS]) - save_data['n_seg'] = n_seg - save_data['total_steps'] = total_steps - save_data['mode'] = mode - save_data['truth_total_de'] = truth_total_de - - np.savez(save_path, **save_data) - print(f"\nResults saved to {save_path}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/sweep_reloc_big.py b/closure/archive/segments_intermediate/sweep_reloc_big.py deleted file mode 100644 index d116bd6..0000000 --- a/closure/archive/segments_intermediate/sweep_reloc_big.py +++ /dev/null @@ -1,161 +0,0 @@ -"""Push max_reloc higher: 750, 1000.""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np, optax -from tools.geometry import generate_detector -from tools.config import SegmentData, DepositData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -FINDINGS = os.path.join(OUT_DIR, 'FINDINGS_S1.md') -DX_MM = 0.3 -ALPHA_RECOMB = 0.93 -W_ION = 23.6e-6 - -def main(): - n_seg = 50000 - total_steps = 1000 - - deposit_data = load_particle_step_data('out.h5', 2) - n_truth = deposit_data.positions_mm.shape[0] - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - truth_tids = np.asarray(deposit_data.track_ids) - truth_total_de = float(np.sum(truth_de)) - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - forced_deposit = DepositData( - positions_mm=deposit_data.positions_mm, de=deposit_data.de, - dx=np.full(n_truth, DX_MM, dtype=np.float32), - valid_mask=deposit_data.valid_mask, theta=deposit_data.theta, - phi=deposit_data.phi, track_ids=deposit_data.track_ids) - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - response_signals, _ = sim_truth(forced_deposit) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=1.0) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = DX_MM / 10.0 - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward(dx_mm=DX_MM) - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Per-track 50mm jitter init - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() - init_de = truth_de[indices].copy() * e_scale - init_tids = truth_tids[indices] - for tid in np.unique(init_tids): - init_pos[init_tids == tid] += rng.normal(0, 50.0, size=3) - init_de *= rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - _ = grad_fn(init_params) - print("Ready.\n") - - def compute_Q(de_arr): - return (dx_cm / B_eff) * np.log(np.maximum(ALPHA_RECOMB + B_eff * de_arr / dx_cm, 1.0)) - truth_total_Q = compute_Q(truth_de).sum() - - combos = [ - {'reloc_every': 25, 'max_reloc': 500}, # reference from previous sweep - {'reloc_every': 25, 'max_reloc': 750}, - {'reloc_every': 25, 'max_reloc': 1000}, - ] - - results = [] - for combo in combos: - cfg = {'lr': 1.0, 'decay_rate': 0.999, 'lr_e_mult': 0.01, - 'warmup': 100, 'noise_lr': 0.3} - cfg.update(combo) - - schedule = optax.exponential_decay(init_value=cfg['lr'], transition_steps=1, - decay_rate=cfg['decay_rate']) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - cumulative_relocs = 0 - losses = [] - t0 = time.time() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(cfg['lr_e_mult']) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add( - lr_cur * cfg['noise_lr'] * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= cfg['warmup'] and step % cfg['reloc_every'] == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, cfg['max_reloc']) - cumulative_relocs += int(n_reloc) - - losses.append(float(total_loss)) - - dt = time.time() - t0 - p_np = np.array(params) - alive = p_np[:, 3] > 0.012 - sim_Q = compute_Q(p_np[alive, 3]).sum() - q_ratio = sim_Q / truth_total_Q - n_dead = int((~alive).sum()) - - cs = f"every={combo['reloc_every']}, max={combo['max_reloc']}" - print(f" [{cs}] loss={losses[-1]:.6f} Q={q_ratio:.3f} " - f"dead={n_dead} relocs={cumulative_relocs} {dt:.0f}s") - results.append({'combo': combo, 'loss': losses[-1], 'q_ratio': q_ratio, - 'dead': n_dead, 'relocs': cumulative_relocs}) - - print(f"\n{'Config':<30} {'Loss':>10} {'Q':>6} {'Dead':>6} {'Relocs':>8}") - print("-" * 65) - for r in results: - cs = f"every={r['combo']['reloc_every']}, max={r['combo']['max_reloc']}" - print(f"{cs:<30} {r['loss']:>10.6f} {r['q_ratio']:>6.3f} {r['dead']:>6} {r['relocs']:>8}") - - with open(FINDINGS, 'a') as f: - f.write(f"\n## relocation_big: Push max_reloc higher\n") - f.write(f"out.h5 ev2, 50k, s=1.0, lr=1.0, d=0.999, e_mult=0.01, noise=0.3, {total_steps} steps\n\n") - f.write(f"| Config | Loss | Q_ratio | Dead | Relocs |\n|---|---|---|---|---|\n") - for r in results: - cs = f"every={r['combo']['reloc_every']}, max={r['combo']['max_reloc']}" - f.write(f"| {cs} | {r['loss']:.6f} | {r['q_ratio']:.3f} | {r['dead']} | {r['relocs']} |\n") - f.write('\n') - print(f"\nAppended to {FINDINGS}") - -if __name__ == '__main__': - main() diff --git a/closure/archive/segments_intermediate/sweep_s1_out50k.py b/closure/archive/segments_intermediate/sweep_s1_out50k.py deleted file mode 100644 index 95fac30..0000000 --- a/closure/archive/segments_intermediate/sweep_s1_out50k.py +++ /dev/null @@ -1,265 +0,0 @@ -""" -Sequential hyperparameter sweeps for s=1.0 on out.h5 event 2, 50k segments. -Runs: lr_e_mult → lr_decay → noise → relocation. - -Usage: - python3 closure_analysis_full/sweeps/sweep_s1_out50k.py -""" - -import sys, os, time -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - -import jax, jax.numpy as jnp, numpy as np, optax -from tools.geometry import generate_detector -from tools.config import SegmentData, DepositData -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from tools.recombination import extract_recombination_params -from closure_analysis_full.full_closure import DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -FINDINGS = os.path.join(OUT_DIR, 'FINDINGS_S1.md') -SOBOLEV_S = 1.0 -DX_MM = 0.3 -ALPHA_RECOMB = 0.93 -W_ION = 23.6e-6 - - -def setup(n_seg=50000): - deposit_data = load_particle_step_data('out.h5', 2) - n_truth = deposit_data.positions_mm.shape[0] - truth_pos = np.asarray(deposit_data.positions_mm) - truth_de = np.asarray(deposit_data.de) - truth_tids = np.asarray(deposit_data.track_ids) - truth_total_de = float(np.sum(truth_de)) - - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - forced_deposit = DepositData( - positions_mm=deposit_data.positions_mm, de=deposit_data.de, - dx=np.full(n_truth, DX_MM, dtype=np.float32), - valid_mask=deposit_data.valid_mask, theta=deposit_data.theta, - phi=deposit_data.phi, track_ids=deposit_data.track_ids) - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - response_signals, _ = sim_truth(forced_deposit) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=SOBOLEV_S) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - - _, dens, _, alpha_r, beta_r = extract_recombination_params(detector_config) - field_kVcm = detector_config['electric_field']['field_strength'] / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = DX_MM / 10.0 - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - fwd_opt = sim_opt.build_forward(dx_mm=DX_MM) - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Per-track 50mm jitter init - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() - init_de = truth_de[indices].copy() * e_scale - init_tids = truth_tids[indices] - for tid in np.unique(init_tids): - disp = rng.normal(0, 50.0, size=3) - init_pos[init_tids == tid] += disp - init_de *= rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - # JIT warmup - _ = grad_fn(init_params) - - def compute_Q(de_arr): - return (dx_cm / B_eff) * np.log(np.maximum(ALPHA_RECOMB + B_eff * de_arr / dx_cm, 1.0)) - truth_total_Q = compute_Q(truth_de).sum() - - return { - 'grad_fn': grad_fn, 'init_params': init_params, 'n_seg': n_seg, - 'truth_total_de': truth_total_de, 'truth_total_Q': truth_total_Q, - 'recomb_constants': recomb_constants, 'compute_Q': compute_Q, - 'B_eff': B_eff, 'dx_cm': dx_cm, - } - - -def run_one(shared, cfg, total_steps=1000): - n_seg = shared['n_seg'] - schedule = optax.exponential_decay( - init_value=cfg['lr'], transition_steps=1, decay_rate=cfg['decay_rate']) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = shared['init_params'] - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - cumulative_relocs = 0 - losses = [] - t0 = time.time() - - for step in range(total_steps): - (total_loss, _), grads = shared['grad_fn'](params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(cfg['lr_e_mult']) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - if cfg.get('noise_lr', 0) > 0: - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add( - lr_cur * cfg['noise_lr'] * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= cfg.get('warmup', 100) and step % cfg.get('reloc_every', 25) == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, - shared['recomb_constants'], cfg.get('max_reloc', 100)) - cumulative_relocs += int(n_reloc) - - losses.append(float(total_loss)) - - dt = time.time() - t0 - p_np = np.array(params) - alive = p_np[:, 3] > 0.012 - sim_Q = shared['compute_Q'](p_np[alive, 3]).sum() - q_ratio = sim_Q / shared['truth_total_Q'] - de_ratio = p_np[:, 3].sum() / shared['truth_total_de'] - n_dead = int((~alive).sum()) - - return { - 'loss': losses[-1], 'q_ratio': q_ratio, 'de_ratio': de_ratio, - 'dead': n_dead, 'relocs': cumulative_relocs, 'time': dt, - } - - -def run_sweep(name, desc, combos, shared, total_steps=1000, base_cfg=None): - if base_cfg is None: - base_cfg = {'lr': 1.0, 'decay_rate': 0.999, 'lr_e_mult': 0.003, - 'warmup': 100, 'noise_lr': 0.3, 'reloc_every': 25, 'max_reloc': 100} - - print(f"\n{'='*60}") - print(f"SWEEP: {name} — {desc}") - print(f"{'='*60}") - - results = [] - for combo in combos: - cfg = dict(base_cfg) - cfg.update(combo) - combo_str = ', '.join(f'{k}={v}' for k, v in combo.items()) - print(f"\n [{combo_str}]...", end=' ', flush=True) - r = run_one(shared, cfg, total_steps) - print(f"loss={r['loss']:.6f} Q={r['q_ratio']:.3f} dead={r['dead']} {r['time']:.0f}s") - r['combo'] = combo - results.append(r) - - # Summary - print(f"\n {'Config':<30} {'Loss':>10} {'Q_ratio':>8} {'Dead':>6}") - print(f" {'-'*58}") - for r in results: - cs = ', '.join(f'{k}={v}' for k, v in r['combo'].items()) - print(f" {cs:<30} {r['loss']:>10.6f} {r['q_ratio']:>8.3f} {r['dead']:>6}") - - # Append to findings - with open(FINDINGS, 'a') as f: - f.write(f"\n## {name}: {desc}\n") - f.write(f"out.h5 ev2, 50k segs, s=1.0, dx=0.3mm, {total_steps} steps, track jitter 50mm\n\n") - f.write(f"| Config | Loss | Q_ratio | Dead |\n|---|---|---|---|\n") - for r in results: - cs = ', '.join(f'{k}={v}' for k, v in r['combo'].items()) - f.write(f"| {cs} | {r['loss']:.6f} | {r['q_ratio']:.3f} | {r['dead']} |\n") - f.write('\n') - print(f"\n Appended to {FINDINGS}") - - return results - - -def main(): - print("Setting up (50k segs, out.h5 event 2, s=1.0, dx=0.3mm)...") - shared = setup(50000) - print("Ready.\n") - - # Sweep 1: lr_e_mult - results_emult = run_sweep( - 'lr_e_mult (s=1.0, out.h5)', - 'lr_e_mult sweep at 50k segments', - [{'lr_e_mult': 0.001}, {'lr_e_mult': 0.003}, - {'lr_e_mult': 0.005}, {'lr_e_mult': 0.01}], - shared, total_steps=1000) - - best_emult = min(results_emult, key=lambda r: r['loss'])['combo']['lr_e_mult'] - print(f"\n>>> Best lr_e_mult: {best_emult}") - - # Sweep 2: lr × decay - base2 = {'lr': 1.0, 'decay_rate': 0.999, 'lr_e_mult': best_emult, - 'warmup': 100, 'noise_lr': 0.3, 'reloc_every': 25, 'max_reloc': 100} - results_lr = run_sweep( - 'lr_decay (s=1.0, out.h5)', - f'lr × decay sweep (lr_e_mult={best_emult})', - [{'lr': 0.5, 'decay_rate': 0.9995}, - {'lr': 0.7, 'decay_rate': 0.999}, - {'lr': 1.0, 'decay_rate': 0.999}, - {'lr': 1.5, 'decay_rate': 0.998}, - {'lr': 2.0, 'decay_rate': 0.997}], - shared, total_steps=1000, base_cfg=base2) - - best_lr_combo = min(results_lr, key=lambda r: r['loss'])['combo'] - print(f"\n>>> Best lr/decay: {best_lr_combo}") - - # Sweep 3: noise - base3 = dict(base2) - base3.update(best_lr_combo) - results_noise = run_sweep( - 'noise (s=1.0, out.h5)', - f'noise sweep (lr_e_mult={best_emult}, {best_lr_combo})', - [{'noise_lr': 0.0}, {'noise_lr': 0.1}, {'noise_lr': 0.3}, - {'noise_lr': 0.5}, {'noise_lr': 1.0}], - shared, total_steps=1000, base_cfg=base3) - - best_noise = min(results_noise, key=lambda r: r['loss'])['combo']['noise_lr'] - print(f"\n>>> Best noise_lr: {best_noise}") - - # Sweep 4: relocation - base4 = dict(base3) - base4['noise_lr'] = best_noise - results_reloc = run_sweep( - 'relocation (s=1.0, out.h5)', - f'relocation sweep (all best so far)', - [{'reloc_every': 25, 'max_reloc': 50}, - {'reloc_every': 25, 'max_reloc': 100}, - {'reloc_every': 25, 'max_reloc': 200}, - {'reloc_every': 25, 'max_reloc': 500}, - {'reloc_every': 10, 'max_reloc': 100}, - {'reloc_every': 10, 'max_reloc': 200}], - shared, total_steps=1000, base_cfg=base4) - - best_reloc = min(results_reloc, key=lambda r: r['loss'])['combo'] - print(f"\n>>> Best relocation: {best_reloc}") - - # Final summary - print(f"\n{'='*60}") - print(f"FINAL BEST CONFIG (s=1.0, out.h5, 50k segs):") - print(f" lr_e_mult={best_emult}") - print(f" {best_lr_combo}") - print(f" noise_lr={best_noise}") - print(f" {best_reloc}") - print(f"{'='*60}") - - -if __name__ == '__main__': - main() diff --git a/closure/archive/slides/lossslide1_spectral_weights.png b/closure/archive/slides/lossslide1_spectral_weights.png deleted file mode 100644 index ba6b8f2..0000000 Binary files a/closure/archive/slides/lossslide1_spectral_weights.png and /dev/null differ diff --git a/closure/archive/slides/lossslide1_spectral_weights.py b/closure/archive/slides/lossslide1_spectral_weights.py deleted file mode 100644 index 9901c47..0000000 --- a/closure/archive/slides/lossslide1_spectral_weights.py +++ /dev/null @@ -1,82 +0,0 @@ -"""Lossslide 1: Spectral weights in frequency domain — MSE vs Blur MSE vs Sobolev.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl - -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 16, - 'axes.labelsize': 18, - 'axes.titlesize': 20, - 'xtick.labelsize': 14, - 'ytick.labelsize': 14, - 'legend.fontsize': 13, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, - 'xtick.minor.width': 0.6, - 'ytick.minor.width': 0.6, - 'lines.linewidth': 2.5, -}) - -# --------------------------------------------------------------------------- -# Build 1D radial spectral weights for N = 4096 (matches padded size) -# --------------------------------------------------------------------------- -N = 4096 -freqs = np.fft.fftfreq(N) -# Take positive half only for plotting -pos = freqs[:N // 2] - -# --- MSE: flat weight = 1 --- -w_mse = np.ones_like(pos) - -# --- Blur MSE: sum of Gaussian weights --- -sigmas = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256) -w_blur = np.zeros_like(pos) -for s in sigmas: - if s == 0: - w_blur += 1.0 - else: - w_blur += s**2 * np.exp(-4 * np.pi**2 * s**2 * pos**2) - -# --- Sobolev s=1.5 --- -max_pad = 1024 -eps = 1.0 / (np.pi**2 * max_pad**2) -w_sob15 = 1.0 / (pos**2 + eps)**1.5 - -# --- Sobolev s=2.0 --- -w_sob20 = 1.0 / (pos**2 + eps)**2.0 - -# --------------------------------------------------------------------------- -# Plot -# --------------------------------------------------------------------------- -fig, ax = plt.subplots(figsize=(10, 6)) - -ax.loglog(pos, w_mse, color='0.5', lw=2, ls='--', label='MSE ($W = 1$)', zorder=2) -ax.loglog(pos, w_blur, color='#4393C3', lw=2.5, label='Gaussian Pyramid', zorder=3) -ax.loglog(pos, w_sob15, color='#D6604D', lw=2.5, label=r'Sobolev $H^{-1.5}$', zorder=4) -ax.loglog(pos, w_sob20, color='#B2182B', lw=2.5, ls='-.', label=r'Sobolev $H^{-2}$', zorder=4) - -ax.set_xlabel('Frequency $|f|$ (cycles / pixel)') -ax.set_ylabel('Spectral Weight $W(f)$') -ax.set_title('Frequency-Domain Loss Weights') -ax.set_xlim(pos[1], pos[-1]) -ax.legend(loc='upper right', framealpha=0.9) -ax.grid(True, which='major', ls='-', alpha=0.25) -ax.grid(True, which='minor', ls=':', alpha=0.12) - -# Annotate low-frequency amplification -ax.annotate('Low-freq amplification\n(large-scale structure)', - xy=(3e-3, 1e8), fontsize=12, color='#B2182B', - ha='center', style='italic') - -fig.tight_layout() -out = os.path.join(os.path.dirname(__file__), 'lossslide1_spectral_weights.png') -fig.savefig(out, bbox_inches='tight') -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/lossslide2_spatial_kernels.png b/closure/archive/slides/lossslide2_spatial_kernels.png deleted file mode 100644 index ea06165..0000000 Binary files a/closure/archive/slides/lossslide2_spatial_kernels.png and /dev/null differ diff --git a/closure/archive/slides/lossslide2_spatial_kernels.py b/closure/archive/slides/lossslide2_spatial_kernels.py deleted file mode 100644 index 9e98f67..0000000 --- a/closure/archive/slides/lossslide2_spatial_kernels.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Lossslide 2: 2D spatial-domain kernels — IFFT of spectral weights.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl -from matplotlib.colors import LogNorm - -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 16, - 'axes.labelsize': 18, - 'axes.titlesize': 20, - 'xtick.labelsize': 14, - 'ytick.labelsize': 14, - 'legend.fontsize': 13, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, - 'xtick.minor.width': 0.6, - 'ytick.minor.width': 0.6, - 'lines.linewidth': 2.5, -}) - -# --------------------------------------------------------------------------- -# Build 2D spectral weights, IFFT to get spatial kernels -# --------------------------------------------------------------------------- -N = 1024 -max_pad = 512 -eps = 1.0 / (np.pi**2 * max_pad**2) - -fy = np.fft.fftfreq(N) -fx = np.fft.fftfreq(N) -freq_sq = fy[:, None]**2 + fx[None, :]**2 - -# Gaussian Pyramid -sigmas = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256) -W_blur = np.zeros((N, N)) -for s in sigmas: - if s == 0: - W_blur += 1.0 - else: - W_blur += s**2 * np.exp(-4 * np.pi**2 * s**2 * freq_sq) - -# Sobolev -W_sob15 = 1.0 / (freq_sq + eps)**1.5 -W_sob20 = 1.0 / (freq_sq + eps)**2.0 - -# K_hat = sqrt(W), then IFFT for spatial kernel -K_blur = np.fft.fftshift(np.fft.ifft2(np.sqrt(W_blur)).real) -K_sob15 = np.fft.fftshift(np.fft.ifft2(np.sqrt(W_sob15)).real) -K_sob20 = np.fft.fftshift(np.fft.ifft2(np.sqrt(W_sob20)).real) - -# Normalize to peak=1 -K_blur /= K_blur.max() -K_sob15 /= K_sob15.max() -K_sob20 /= K_sob20.max() - -# Crop to +/- crop_r pixels around center -crop_r = 250 -c = N // 2 -sl = slice(c - crop_r, c + crop_r) -extent = [-crop_r, crop_r, -crop_r, crop_r] - -K_blur_c = K_blur[sl, sl] -K_sob15_c = K_sob15[sl, sl] -K_sob20_c = K_sob20[sl, sl] - -# --------------------------------------------------------------------------- -# Plot: 3 panels -# --------------------------------------------------------------------------- -fig, axes = plt.subplots(1, 3, figsize=(16, 5.5)) - -vmin = 1e-3 -titles = ['Gaussian Pyramid', r'Sobolev $s = 1.5$', r'Sobolev $s = 2$'] -kernels = [K_blur_c, K_sob15_c, K_sob20_c] - -for ax, K, title in zip(axes, kernels, titles): - K_pos = np.clip(K, vmin, None) - im = ax.imshow(K_pos, cmap='inferno', origin='lower', extent=extent, - norm=LogNorm(vmin=vmin, vmax=1.0)) - ax.set_title(title) - ax.set_xlabel('$\\Delta x$ (pixels)') - ax.set_ylabel('$\\Delta y$ (pixels)') - fig.colorbar(im, ax=ax, shrink=0.82, pad=0.02) - -fig.suptitle('Spatial Convolution Kernels $K(\\Delta x, \\Delta y)$', - fontsize=20, fontweight='bold', y=1.02) -fig.tight_layout() -out = os.path.join(os.path.dirname(__file__), 'lossslide2_spatial_kernels.png') -fig.savefig(out, bbox_inches='tight') -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/lossslide3_convolution_demo.png b/closure/archive/slides/lossslide3_convolution_demo.png deleted file mode 100644 index 140de19..0000000 Binary files a/closure/archive/slides/lossslide3_convolution_demo.png and /dev/null differ diff --git a/closure/archive/slides/lossslide3_convolution_demo.py b/closure/archive/slides/lossslide3_convolution_demo.py deleted file mode 100644 index 61cd373..0000000 --- a/closure/archive/slides/lossslide3_convolution_demo.py +++ /dev/null @@ -1,116 +0,0 @@ -"""Lossslide 3: Convolution demo — a displaced 2D Gaussian before/after Sobolev kernel.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl -from matplotlib.colors import TwoSlopeNorm - -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 16, - 'axes.labelsize': 18, - 'axes.titlesize': 18, - 'xtick.labelsize': 13, - 'ytick.labelsize': 13, - 'legend.fontsize': 13, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, -}) - -# --------------------------------------------------------------------------- -# Create a simple 2D test case: Gaussian blob, truth vs displaced -# --------------------------------------------------------------------------- -H, W = 256, 256 -y, x = np.mgrid[:H, :W] - -# Truth: Gaussian at center -cx_t, cy_t = 128, 128 -sig = 12.0 -truth = np.exp(-((x - cx_t)**2 + (y - cy_t)**2) / (2 * sig**2)) - -# Sim: same blob displaced by 60 pixels -shift = 60 -cx_s, cy_s = cx_t + shift, cy_t + int(shift * 0.5) -sim = np.exp(-((x - cx_s)**2 + (y - cy_s)**2) / (2 * sig**2)) - -diff = sim - truth - -# --------------------------------------------------------------------------- -# Build Sobolev spectral weights and convolve the difference -# --------------------------------------------------------------------------- -max_pad = 128 -H_pad, W_pad = H + 2 * max_pad, W + 2 * max_pad -fy = np.fft.fftfreq(H_pad) -fx = np.fft.fftfreq(W_pad) -freq_sq = fy[:, None]**2 + fx[None, :]**2 -eps = 1.0 / (np.pi**2 * max_pad**2) - -# K_hat = sqrt(W) = 1/(freq_sq + eps)^{s/2} -def convolve_sobolev(diff_2d, s, max_pad): - H, W = diff_2d.shape - H_pad, W_pad = H + 2 * max_pad, W + 2 * max_pad - fy = np.fft.fftfreq(H_pad) - fx = np.fft.fftfreq(W_pad) - freq_sq = fy[:, None]**2 + fx[None, :]**2 - eps = 1.0 / (np.pi**2 * max_pad**2) - K_hat = 1.0 / (freq_sq + eps)**(s / 2.0) - diff_pad = np.pad(diff_2d, max_pad) - convolved_pad = np.fft.ifft2(np.fft.fft2(diff_pad) * K_hat).real - return convolved_pad[max_pad:max_pad + H, max_pad:max_pad + W] - - -conv_15 = convolve_sobolev(diff, s=1.5, max_pad=max_pad) -conv_20 = convolve_sobolev(diff, s=2.0, max_pad=max_pad) - -# --------------------------------------------------------------------------- -# Plot: 2 rows x 3 cols -# Row 1: Truth, Sim, Difference -# Row 2: (empty), Convolved s=1.5, Convolved s=2.0 -# --------------------------------------------------------------------------- -fig, axes = plt.subplots(2, 3, figsize=(14, 9)) - -# Row 1 -im0 = axes[0, 0].imshow(truth, cmap='inferno', origin='lower', vmin=0, vmax=1) -axes[0, 0].set_title('Truth Signal') - -im1 = axes[0, 1].imshow(sim, cmap='inferno', origin='lower', vmin=0, vmax=1) -axes[0, 1].set_title('Simulated Signal (shifted)') - -vmax_d = np.max(np.abs(diff)) -norm_d = TwoSlopeNorm(vmin=-vmax_d, vcenter=0, vmax=vmax_d) -im2 = axes[0, 2].imshow(diff, cmap='RdBu_r', origin='lower', norm=norm_d) -axes[0, 2].set_title('Difference (MSE input)') -fig.colorbar(im2, ax=axes[0, 2], shrink=0.8) - -# Row 2 -axes[1, 0].axis('off') - -vmax_15 = np.max(np.abs(conv_15)) -norm_15 = TwoSlopeNorm(vmin=-vmax_15, vcenter=0, vmax=vmax_15) -im3 = axes[1, 1].imshow(conv_15, cmap='RdBu_r', origin='lower', norm=norm_15) -axes[1, 1].set_title(r'$K_{1.5} \ast$ Difference ($s=1.5$)') -fig.colorbar(im3, ax=axes[1, 1], shrink=0.8) - -vmax_20 = np.max(np.abs(conv_20)) -norm_20 = TwoSlopeNorm(vmin=-vmax_20, vcenter=0, vmax=vmax_20) -im4 = axes[1, 2].imshow(conv_20, cmap='RdBu_r', origin='lower', norm=norm_20) -axes[1, 2].set_title(r'$K_{2} \ast$ Difference ($s=2$)') -fig.colorbar(im4, ax=axes[1, 2], shrink=0.8) - -for ax in axes.flat: - if ax.get_visible() and ax.images: - ax.set_xlabel('Wire') - ax.set_ylabel('Time') - -fig.suptitle('Sobolev Convolution: Displaced Gaussian Blob', - fontsize=20, fontweight='bold', y=1.01) -fig.tight_layout() -out = os.path.join(os.path.dirname(__file__), 'lossslide3_convolution_demo.png') -fig.savefig(out, bbox_inches='tight') -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/lossslide4_event_convolution.png b/closure/archive/slides/lossslide4_event_convolution.png deleted file mode 100644 index d370596..0000000 Binary files a/closure/archive/slides/lossslide4_event_convolution.png and /dev/null differ diff --git a/closure/archive/slides/lossslide4_event_convolution.py b/closure/archive/slides/lossslide4_event_convolution.py deleted file mode 100644 index 005de68..0000000 --- a/closure/archive/slides/lossslide4_event_convolution.py +++ /dev/null @@ -1,216 +0,0 @@ -"""Lossslide 4: Real muon event — truth vs displaced sim, MSE vs Sobolev view. - -Generates a truth muon and a displaced sim muon through the full detector -simulation, then shows the raw difference (what MSE sees) vs the Sobolev- -convolved difference (what the Sobolev loss sees) for one wire plane. -""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl -from matplotlib.colors import TwoSlopeNorm -import time - -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 16, - 'axes.labelsize': 18, - 'axes.titlesize': 18, - 'xtick.labelsize': 13, - 'ytick.labelsize': 13, - 'legend.fontsize': 13, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, -}) - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments, - build_muon_forward, -) - -# --------------------------------------------------------------------------- -# Config -# --------------------------------------------------------------------------- -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 -PLANE = 2 # Y-plane for clearest display - -# Truth muon -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 2 -TRUTH_ENERGY = 200.0 - -# Displaced muon (shift position and angle) -SIM_X, SIM_Y, SIM_Z = -400.0, 80.0, 0.0 -SIM_THETA, SIM_PHI = TRUTH_THETA + 0.15, TRUTH_PHI - 0.1 -SIM_ENERGY = 220.0 - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - - -def convolve_sobolev_2d(diff_2d, s, max_pad): - """Convolve 2D difference with Sobolev kernel K_hat = 1/(|f|^2+eps)^{s/2}.""" - H, W = diff_2d.shape - H_pad, W_pad = H + 2 * max_pad, W + 2 * max_pad - fy = np.fft.fftfreq(H_pad) - fx = np.fft.fftfreq(W_pad) - freq_sq = fy[:, None]**2 + fx[None, :]**2 - eps = 1.0 / (np.pi**2 * max_pad**2) - K_hat = 1.0 / (freq_sq + eps)**(s / 2.0) - diff_pad = np.pad(diff_2d, max_pad) - convolved_pad = np.fft.ifft2(np.fft.fft2(diff_pad) * K_hat).real - return convolved_pad[max_pad:max_pad + H, max_pad:max_pad + W] - - -def main(): - print("Setting up detector...", flush=True) - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - def make_signals(x, y, z, theta, phi, energy): - pos, de = generate_muon_segments( - energy, jnp.array([x, y, z]), theta, phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - return forward(pos, de) - - make_signals_jit = jax.jit(make_signals) - - # Generate truth - print("Generating truth signals...", flush=True) - t0 = time.time() - truth_sigs = make_signals_jit( - jnp.float32(TRUTH_X), jnp.float32(TRUTH_Y), jnp.float32(TRUTH_Z), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), jnp.float32(TRUTH_ENERGY)) - for s in truth_sigs: - jax.block_until_ready(s) - print(f" Done ({time.time()-t0:.1f}s)", flush=True) - - # Generate displaced sim - print("Generating displaced sim signals...", flush=True) - t0 = time.time() - sim_sigs = make_signals_jit( - jnp.float32(SIM_X), jnp.float32(SIM_Y), jnp.float32(SIM_Z), - jnp.float32(SIM_THETA), jnp.float32(SIM_PHI), jnp.float32(SIM_ENERGY)) - for s in sim_sigs: - jax.block_until_ready(s) - print(f" Done ({time.time()-t0:.1f}s)", flush=True) - - truth_plane = np.array(truth_sigs[PLANE]) - sim_plane = np.array(sim_sigs[PLANE]) - diff = sim_plane - truth_plane - - # Crop to region of interest (nonzero region with margin) - nonzero_mask = (np.abs(truth_plane) + np.abs(sim_plane)) > 0 - rows = np.any(nonzero_mask, axis=1) - cols = np.any(nonzero_mask, axis=0) - r_lo, r_hi = np.argmax(rows), len(rows) - np.argmax(rows[::-1]) - c_lo, c_hi = np.argmax(cols), len(cols) - np.argmax(cols[::-1]) - margin = 30 - r_lo = max(0, r_lo - margin) - r_hi = min(truth_plane.shape[0], r_hi + margin) - c_lo = max(0, c_lo - margin) - c_hi = min(truth_plane.shape[1], c_hi + margin) - - truth_crop = truth_plane[r_lo:r_hi, c_lo:c_hi] - sim_crop = sim_plane[r_lo:r_hi, c_lo:c_hi] - diff_crop = diff[r_lo:r_hi, c_lo:c_hi] - - # Convolve full arrays then crop (avoids edge artifacts) - max_pad = 256 - conv_15_full = convolve_sobolev_2d(diff, s=1.5, max_pad=max_pad) - conv_20_full = convolve_sobolev_2d(diff, s=2.0, max_pad=max_pad) - conv_15_crop = conv_15_full[r_lo:r_hi, c_lo:c_hi] - conv_20_crop = conv_20_full[r_lo:r_hi, c_lo:c_hi] - - print(f"Plane shape: {truth_plane.shape}, crop: [{r_lo}:{r_hi}, {c_lo}:{c_hi}]") - - # ----------------------------------------------------------------------- - # Figure: 2 rows x 3 cols - # Row 1: Truth | Sim | Difference - # Row 2: K_{1.5} * Diff | K_{2} * Diff | (empty or annotation) - # ----------------------------------------------------------------------- - fig, axes = plt.subplots(2, 3, figsize=(16, 10)) - - sig_vmax = max(np.max(np.abs(truth_crop)), np.max(np.abs(sim_crop))) - - # Row 1: signals and raw difference - im0 = axes[0, 0].imshow(truth_crop.T, cmap='inferno', origin='lower', - aspect='auto', vmin=0, vmax=sig_vmax) - axes[0, 0].set_title('Truth') - - im1 = axes[0, 1].imshow(sim_crop.T, cmap='inferno', origin='lower', - aspect='auto', vmin=0, vmax=sig_vmax) - axes[0, 1].set_title('Sim (displaced)') - - vmax_d = np.max(np.abs(diff_crop)) - norm_d = TwoSlopeNorm(vmin=-vmax_d, vcenter=0, vmax=vmax_d) - im2 = axes[0, 2].imshow(diff_crop.T, cmap='RdBu_r', origin='lower', - aspect='auto', norm=norm_d) - axes[0, 2].set_title('Difference (MSE input)') - fig.colorbar(im2, ax=axes[0, 2], shrink=0.75, pad=0.02) - - # Row 2: convolved differences - vmax_15 = np.max(np.abs(conv_15_crop)) - norm_15 = TwoSlopeNorm(vmin=-vmax_15, vcenter=0, vmax=vmax_15) - im3 = axes[1, 0].imshow(conv_15_crop.T, cmap='RdBu_r', origin='lower', - aspect='auto', norm=norm_15) - axes[1, 0].set_title(r'$K_{1.5} \ast$ Diff (Sobolev $s\!=\!1.5$ input)') - fig.colorbar(im3, ax=axes[1, 0], shrink=0.75, pad=0.02) - - vmax_20 = np.max(np.abs(conv_20_crop)) - norm_20 = TwoSlopeNorm(vmin=-vmax_20, vcenter=0, vmax=vmax_20) - im4 = axes[1, 1].imshow(conv_20_crop.T, cmap='RdBu_r', origin='lower', - aspect='auto', norm=norm_20) - axes[1, 1].set_title(r'$K_{2} \ast$ Diff (Sobolev $s\!=\!2$ input)') - fig.colorbar(im4, ax=axes[1, 1], shrink=0.75, pad=0.02) - - # Bottom-right: annotation panel - axes[1, 2].axis('off') - info = ( - "Y-plane event display\n\n" - f"Truth: ({TRUTH_X:.0f}, {TRUTH_Y:.0f}, {TRUTH_Z:.0f}) mm\n" - f" $\\theta$={np.degrees(TRUTH_THETA):.0f}°, " - f"$\\phi$={np.degrees(TRUTH_PHI):.0f}°, " - f"E={TRUTH_ENERGY:.0f} MeV\n\n" - f"Sim: ({SIM_X:.0f}, {SIM_Y:.0f}, {SIM_Z:.0f}) mm\n" - f" $\\theta$={np.degrees(SIM_THETA):.0f}°, " - f"$\\phi$={np.degrees(SIM_PHI):.0f}°, " - f"E={SIM_ENERGY:.0f} MeV\n\n" - "The Sobolev kernel smears\n" - "the difference signal across\n" - "the gap between truth and sim,\n" - "providing gradient information\n" - "even where features don't overlap." - ) - axes[1, 2].text(0.05, 0.95, info, transform=axes[1, 2].transAxes, - fontsize=14, va='top', ha='left', family='serif', - bbox=dict(boxstyle='round,pad=0.5', fc='#f7f7f7', ec='0.7')) - - for ax in axes.flat: - if ax.images: - ax.set_xlabel('Wire') - ax.set_ylabel('Time Tick') - - fig.suptitle('Muon Event: What MSE vs Sobolev Loss "See"', - fontsize=20, fontweight='bold', y=1.01) - fig.tight_layout() - out = os.path.join(OUT_DIR, 'lossslide4_event_convolution.png') - fig.savefig(out, bbox_inches='tight') - plt.close(fig) - print(f'Saved {out}') - - -if __name__ == '__main__': - main() diff --git a/closure/archive/slides/slide1_dedx_and_range.png b/closure/archive/slides/slide1_dedx_and_range.png deleted file mode 100644 index 990b4dd..0000000 Binary files a/closure/archive/slides/slide1_dedx_and_range.png and /dev/null differ diff --git a/closure/archive/slides/slide1_dedx_and_range.py b/closure/archive/slides/slide1_dedx_and_range.py deleted file mode 100644 index b4dd802..0000000 --- a/closure/archive/slides/slide1_dedx_and_range.py +++ /dev/null @@ -1,112 +0,0 @@ -"""Slide 1: Muon dE/dx (Bethe-Bloch) curve and CSDA range in liquid argon.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl - -# ── Professional style ── -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 14, - 'axes.labelsize': 16, - 'axes.titlesize': 18, - 'xtick.labelsize': 13, - 'ytick.labelsize': 13, - 'legend.fontsize': 13, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, - 'xtick.minor.width': 0.6, - 'ytick.minor.width': 0.6, - 'lines.linewidth': 2.0, -}) - -LAR_DENSITY = 1.396 # g/cm^3 - -# ── Load data ── -data = np.loadtxt('tools/data/muon_dedx_lar.csv', delimiter=',', comments='#') -T_MeV = data[:, 0] -dedx_MeVcm2g = data[:, 2] -dedx_MeVcm = dedx_MeVcm2g * LAR_DENSITY -R_gcm2 = data[:, 3] -R_cm = R_gcm2 / LAR_DENSITY - -# MIP location -mip_idx = np.argmin(dedx_MeVcm2g) -T_mip = T_MeV[mip_idx] -dedx_mip = dedx_MeVcm[mip_idx] - -# ── Figure: two panels ── -fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5.5)) - -# --- Left: dE/dx vs T --- -ax1.loglog(T_MeV, dedx_MeVcm, color='#2166AC', lw=2.5, zorder=3) -ax1.axhline(dedx_mip, color='#B2182B', ls='--', lw=1.5, alpha=0.7, zorder=2) -ax1.plot(T_mip, dedx_mip, 'o', color='#B2182B', ms=8, zorder=4, - label=f'MIP: {dedx_mip:.2f} MeV/cm at {T_mip:.0f} MeV') - -# Shade unreliable region -ax1.axvspan(T_MeV[0], 10, color='gray', alpha=0.12, zorder=1) -ax1.text(3, 25, 'PDG\nunreliable', fontsize=10, color='gray', - ha='center', va='top', style='italic') - -# Bragg peak annotation -ax1.annotate('Bragg peak\n(rising dE/dx)', xy=(5, 12), fontsize=11, - color='#2166AC', ha='center', va='bottom', - arrowprops=dict(arrowstyle='->', color='#2166AC', lw=1.2), - xytext=(20, 25)) - -# Relativistic rise annotation -ax1.annotate('Relativistic\nrise', xy=(5e4, dedx_MeVcm[-3]), - fontsize=11, color='#2166AC', ha='center', - xytext=(1e4, 10), - arrowprops=dict(arrowstyle='->', color='#2166AC', lw=1.2)) - -ax1.set_xlabel('Kinetic Energy $T$ (MeV)') -ax1.set_ylabel('Stopping Power $-dE/dx$ (MeV/cm)') -ax1.set_title('Muon Stopping Power in LAr') -ax1.legend(loc='upper right', framealpha=0.9, edgecolor='0.7') -ax1.set_xlim(T_MeV[0], T_MeV[-1]) -ax1.set_ylim(1.5, 45) -ax1.grid(True, which='major', ls='-', alpha=0.25) -ax1.grid(True, which='minor', ls=':', alpha=0.12) - -# --- Right: CSDA range vs T --- -ax2.loglog(T_MeV, R_cm, color='#D6604D', lw=2.5, zorder=3) - -# Mark a few reference energies -ref_energies = [50, 200, 500, 2000] -for E_ref in ref_energies: - idx = np.argmin(np.abs(T_MeV - E_ref)) - R_ref = R_cm[idx] - ax2.plot(T_MeV[idx], R_ref, 's', color='#D6604D', ms=6, zorder=4) - if E_ref == 200: - ax2.annotate(f'{E_ref} MeV\nR = {R_ref:.0f} cm', - xy=(T_MeV[idx], R_ref), fontsize=10, - ha='left', va='top', - xytext=(T_MeV[idx]*1.8, R_ref*0.4), - arrowprops=dict(arrowstyle='->', color='0.4', lw=1.0)) - elif E_ref == 500: - ax2.annotate(f'{E_ref} MeV\nR = {R_ref:.0f} cm', - xy=(T_MeV[idx], R_ref), fontsize=10, - ha='left', va='bottom', - xytext=(T_MeV[idx]*1.5, R_ref*2), - arrowprops=dict(arrowstyle='->', color='0.4', lw=1.0)) - -ax2.set_xlabel('Kinetic Energy $T$ (MeV)') -ax2.set_ylabel('CSDA Range $R$ (cm)') -ax2.set_title('CSDA Range in LAr') -ax2.set_xlim(T_MeV[0], T_MeV[-1]) -ax2.grid(True, which='major', ls='-', alpha=0.25) -ax2.grid(True, which='minor', ls=':', alpha=0.12) - -fig.tight_layout(w_pad=3) - -out = os.path.join(os.path.dirname(__file__), 'slide1_dedx_and_range.png') -fig.savefig(out) -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/slide1_dedx_curve.png b/closure/archive/slides/slide1_dedx_curve.png deleted file mode 100644 index 1651d57..0000000 Binary files a/closure/archive/slides/slide1_dedx_curve.png and /dev/null differ diff --git a/closure/archive/slides/slide1_dedx_curve.py b/closure/archive/slides/slide1_dedx_curve.py deleted file mode 100644 index 2293329..0000000 --- a/closure/archive/slides/slide1_dedx_curve.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Slide 1: Muon dE/dx (Bethe-Bloch) curve in liquid argon.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl - -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 16, - 'axes.labelsize': 18, - 'axes.titlesize': 20, - 'xtick.labelsize': 14, - 'ytick.labelsize': 14, - 'legend.fontsize': 14, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, - 'xtick.minor.width': 0.6, - 'ytick.minor.width': 0.6, - 'lines.linewidth': 2.5, -}) - -LAR_DENSITY = 1.396 - -data = np.loadtxt('tools/data/muon_dedx_lar.csv', delimiter=',', comments='#') -T_MeV = data[:, 0] -dedx_MeVcm = data[:, 2] * LAR_DENSITY - -mip_idx = np.argmin(data[:, 2]) -T_mip = T_MeV[mip_idx] -dedx_mip = dedx_MeVcm[mip_idx] - -fig, ax = plt.subplots(figsize=(9, 6)) - -ax.loglog(T_MeV, dedx_MeVcm, color='#2166AC', lw=2.5, zorder=3) - -# MIP point -ax.axhline(dedx_mip, color='#B2182B', ls='--', lw=1.5, alpha=0.5, zorder=2) -ax.plot(T_mip, dedx_mip, 'o', color='#B2182B', ms=9, zorder=4) -ax.annotate(f'MIP: {dedx_mip:.2f} MeV/cm\nat $T$ = {T_mip:.0f} MeV', - xy=(T_mip, dedx_mip), fontsize=13, - xytext=(3000, 3.5), - arrowprops=dict(arrowstyle='->', color='#B2182B', lw=1.3), - color='#B2182B') - -# Shade unreliable region -ax.axvspan(T_MeV[0], 10, color='gray', alpha=0.1, zorder=1) -ax.text(3.5, 30, 'PDG\nunreliable', fontsize=12, color='0.5', - ha='center', va='top', style='italic') - -ax.set_xlabel('Kinetic Energy $T$ (MeV)') -ax.set_ylabel('Stopping Power $-dE/dx$ (MeV/cm)') -ax.set_title('Muon Stopping Power in Liquid Argon') -ax.set_xlim(T_MeV[0], T_MeV[-1]) -ax.set_ylim(1.5, 45) -ax.grid(True, which='major', ls='-', alpha=0.25) -ax.grid(True, which='minor', ls=':', alpha=0.12) - -fig.tight_layout() -out = os.path.join(os.path.dirname(__file__), 'slide1_dedx_curve.png') -fig.savefig(out, bbox_inches='tight') -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/slide2_de_per_segment.png b/closure/archive/slides/slide2_de_per_segment.png deleted file mode 100644 index 93ee208..0000000 Binary files a/closure/archive/slides/slide2_de_per_segment.png and /dev/null differ diff --git a/closure/archive/slides/slide2_de_per_segment.py b/closure/archive/slides/slide2_de_per_segment.py deleted file mode 100644 index faa37a0..0000000 --- a/closure/archive/slides/slide2_de_per_segment.py +++ /dev/null @@ -1,70 +0,0 @@ -"""Slide 2: Energy deposit per segment for muon tracks — showing Bragg peak.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl - -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 16, - 'axes.labelsize': 18, - 'axes.titlesize': 20, - 'xtick.labelsize': 14, - 'ytick.labelsize': 14, - 'legend.fontsize': 14, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, - 'lines.linewidth': 2.2, -}) - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments_scan, -) - -STEP_SIZE_MM = 0.5 -N_SEGMENTS = 4000 -MIN_ENERGY = 10.0 -ENERGIES = [100.0, 200.0, 500.0] -COLORS = ['#D6604D', '#2166AC', '#4DAF4A'] - -log_T, dedx = load_dedx_table_jax() -start = jnp.zeros(3) - -fig, ax = plt.subplots(figsize=(9, 6)) - -for E, color in zip(ENERGIES, COLORS): - _, de = generate_muon_segments_scan( - jnp.float32(E), start, jnp.float32(0.8), jnp.float32(1.2), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - min_energy_mev=MIN_ENERGY, smooth_temperature=0.0) - jax.block_until_ready(de) - de_np = np.array(de) - dist_cm = np.arange(N_SEGMENTS) * STEP_SIZE_MM / 10.0 - n_active = int(np.sum(de_np > 1e-6)) - range_cm = n_active * STEP_SIZE_MM / 10.0 - - # Plot up to just past where the muon stops - end = min(n_active + 30, N_SEGMENTS) - ax.plot(dist_cm[:end], de_np[:end], color=color, lw=2.2, - label=f'{E:.0f} MeV ($R$ = {range_cm:.0f} cm)') - -ax.set_xlabel('Distance Along Track (cm)') -ax.set_ylabel('Energy Deposit $\\Delta E$ per Segment (MeV)') -ax.set_title('Muon Energy Deposit Profile') -ax.legend(loc='upper left', framealpha=0.9, edgecolor='0.7') -ax.grid(True, which='major', ls='-', alpha=0.25) -ax.set_ylim(bottom=-0.005) - -fig.tight_layout() -out = os.path.join(os.path.dirname(__file__), 'slide2_de_per_segment.png') -fig.savefig(out, bbox_inches='tight') -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/slide2_scan_method.png b/closure/archive/slides/slide2_scan_method.png deleted file mode 100644 index 861f998..0000000 Binary files a/closure/archive/slides/slide2_scan_method.png and /dev/null differ diff --git a/closure/archive/slides/slide2_scan_method.py b/closure/archive/slides/slide2_scan_method.py deleted file mode 100644 index fd6db0b..0000000 --- a/closure/archive/slides/slide2_scan_method.py +++ /dev/null @@ -1,132 +0,0 @@ -"""Slide 2: Sequential scan method — dE per segment showing the Bragg peak.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl - -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 14, - 'axes.labelsize': 16, - 'axes.titlesize': 18, - 'xtick.labelsize': 13, - 'ytick.labelsize': 13, - 'legend.fontsize': 12, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, - 'lines.linewidth': 2.0, -}) - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments_scan, -) - -STEP_SIZE_MM = 0.5 -N_SEGMENTS = 4000 -MIN_ENERGY = 10.0 -ENERGIES = [100.0, 200.0, 500.0] -COLORS = ['#D6604D', '#2166AC', '#4DAF4A'] - -log_T, dedx = load_dedx_table_jax() -start = jnp.zeros(3) - -fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5.5)) - -# ── Left panel: dE per segment for multiple energies ── -for E, color in zip(ENERGIES, COLORS): - _, de = generate_muon_segments_scan( - jnp.float32(E), start, jnp.float32(0.8), jnp.float32(1.2), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - min_energy_mev=MIN_ENERGY, smooth_temperature=0.0) - jax.block_until_ready(de) - de_np = np.array(de) - - # Convert segment index to distance in cm - dist_cm = np.arange(N_SEGMENTS) * STEP_SIZE_MM / 10.0 - n_active = int(np.sum(de_np > 1e-6)) - range_cm = n_active * STEP_SIZE_MM / 10.0 - - ax1.plot(dist_cm[:n_active+50], de_np[:n_active+50], - color=color, lw=1.8, - label=f'{E:.0f} MeV (R = {range_cm:.0f} cm)') - -ax1.set_xlabel('Distance Along Track (cm)') -ax1.set_ylabel('Energy Deposit $\\Delta E$ (MeV / segment)') -ax1.set_title('Energy Deposit per Segment') -ax1.legend(loc='upper left', framealpha=0.9, edgecolor='0.7') -ax1.grid(True, which='major', ls='-', alpha=0.25) -ax1.set_ylim(bottom=-0.005) - -# Add annotation for Bragg peak -ax1.annotate('Bragg peak', xy=(34, 0.17), fontsize=12, - color='#D6604D', ha='center', - arrowprops=dict(arrowstyle='->', color='#D6604D', lw=1.2), - xytext=(25, 0.22)) - -# Add annotation for MIP region -ax1.annotate('MIP region\n(~flat dE/dx)', xy=(50, 0.076), - fontsize=11, color='#2166AC', ha='center', va='bottom', - xytext=(50, 0.16), - arrowprops=dict(arrowstyle='->', color='#2166AC', lw=1.2)) - -# ── Right panel: zoom on Bragg peak for 200 MeV ── -_, de200 = generate_muon_segments_scan( - jnp.float32(200.0), start, jnp.float32(0.8), jnp.float32(1.2), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - min_energy_mev=MIN_ENERGY, smooth_temperature=0.0) -jax.block_until_ready(de200) -de200_np = np.array(de200) -n_active_200 = int(np.sum(de200_np > 1e-6)) -dist_cm = np.arange(N_SEGMENTS) * STEP_SIZE_MM / 10.0 - -# Show energy evolution on right y-axis -# Reconstruct energy along track -energies_along = np.zeros(n_active_200 + 20) -energies_along[0] = 200.0 -for i in range(1, len(energies_along)): - energies_along[i] = max(energies_along[i-1] - de200_np[i-1], MIN_ENERGY) - -zoom_lo = max(0, n_active_200 - 200) -zoom_hi = n_active_200 + 20 -sl = slice(zoom_lo, zoom_hi) - -ax2.plot(dist_cm[sl], de200_np[sl], color='#2166AC', lw=2, - label='$\\Delta E$ per segment') -ax2.set_xlabel('Distance Along Track (cm)') -ax2.set_ylabel('$\\Delta E$ (MeV / segment)', color='#2166AC') -ax2.tick_params(axis='y', labelcolor='#2166AC') - -# Energy on secondary axis -ax2r = ax2.twinx() -ax2r.plot(dist_cm[sl], energies_along[:zoom_hi - zoom_lo], - color='#B2182B', lw=2, ls='--', label='Kinetic energy') -ax2r.set_ylabel('Kinetic Energy $T$ (MeV)', color='#B2182B') -ax2r.tick_params(axis='y', labelcolor='#B2182B') -ax2r.axhline(MIN_ENERGY, color='gray', ls=':', lw=1.2, alpha=0.6) -ax2r.text(dist_cm[zoom_hi-5], MIN_ENERGY + 2, - f'$E_{{\\min}}$ = {MIN_ENERGY} MeV', fontsize=10, - color='gray', ha='right', va='bottom') - -ax2.set_title('Bragg Peak Region (200 MeV)') -ax2.grid(True, which='major', ls='-', alpha=0.25) - -# Combined legend -lines1, labels1 = ax2.get_legend_handles_labels() -lines2, labels2 = ax2r.get_legend_handles_labels() -ax2.legend(lines1 + lines2, labels1 + labels2, - loc='upper left', framealpha=0.9, edgecolor='0.7') - -fig.tight_layout(w_pad=3) - -out = os.path.join(os.path.dirname(__file__), 'slide2_scan_method.png') -fig.savefig(out, bbox_inches='tight') -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/slide3_csda_range.png b/closure/archive/slides/slide3_csda_range.png deleted file mode 100644 index 27e8e80..0000000 Binary files a/closure/archive/slides/slide3_csda_range.png and /dev/null differ diff --git a/closure/archive/slides/slide3_csda_range.py b/closure/archive/slides/slide3_csda_range.py deleted file mode 100644 index a1d1aad..0000000 --- a/closure/archive/slides/slide3_csda_range.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Slide 3: CSDA range curve — the key concept enabling parallelization.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl - -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 16, - 'axes.labelsize': 18, - 'axes.titlesize': 20, - 'xtick.labelsize': 14, - 'ytick.labelsize': 14, - 'legend.fontsize': 14, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, - 'xtick.minor.width': 0.6, - 'ytick.minor.width': 0.6, - 'lines.linewidth': 2.5, -}) - -LAR_DENSITY = 1.396 - -data = np.loadtxt('tools/data/muon_dedx_lar.csv', delimiter=',', comments='#') -T_MeV = data[:, 0] -R_cm = data[:, 3] / LAR_DENSITY - -fig, ax = plt.subplots(figsize=(9, 6)) - -ax.loglog(T_MeV, R_cm, color='#D6604D', lw=2.5, zorder=3) - -# Annotate a few reference energies -refs = [(200, 'left'), (500, 'left'), (1000, 'right')] -for E_ref, ha in refs: - idx = np.argmin(np.abs(T_MeV - E_ref)) - R_ref = R_cm[idx] - ax.plot(T_MeV[idx], R_ref, 's', color='#D6604D', ms=7, zorder=4) - - if E_ref == 200: - ax.annotate(f'{E_ref} MeV, $R$ = {R_ref:.0f} cm', - xy=(T_MeV[idx], R_ref), fontsize=13, - xytext=(8, R_ref * 4), ha='left', - arrowprops=dict(arrowstyle='->', color='0.35', lw=1.2)) - elif E_ref == 500: - ax.annotate(f'{E_ref} MeV, $R$ = {R_ref:.0f} cm', - xy=(T_MeV[idx], R_ref), fontsize=13, - xytext=(T_MeV[idx] * 3, R_ref * 0.15), ha='left', - arrowprops=dict(arrowstyle='->', color='0.35', lw=1.2)) - elif E_ref == 1000: - ax.annotate(f'{E_ref} MeV, $R$ = {R_ref:.0f} cm', - xy=(T_MeV[idx], R_ref), fontsize=13, - xytext=(T_MeV[idx] * 3, R_ref * 0.35), ha='left', - arrowprops=dict(arrowstyle='->', color='0.35', lw=1.2)) - -ax.set_xlabel('Kinetic Energy $T$ (MeV)') -ax.set_ylabel('CSDA Range $R(T)$ (cm)') -ax.set_title('CSDA Range in Liquid Argon') -ax.set_xlim(T_MeV[0], T_MeV[-1]) -ax.grid(True, which='major', ls='-', alpha=0.25) -ax.grid(True, which='minor', ls=':', alpha=0.12) - -# Add the key formula -ax.text(0.03, 0.95, - r'$R(T) = \int_0^T \frac{1}{dE/dx}\, dT^\prime$', - transform=ax.transAxes, fontsize=17, - va='top', ha='left', - bbox=dict(boxstyle='round,pad=0.4', facecolor='white', - edgecolor='0.7', alpha=0.9)) - -fig.tight_layout() -out = os.path.join(os.path.dirname(__file__), 'slide3_csda_range.png') -fig.savefig(out, bbox_inches='tight') -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/slide3_smoothing_problem.py b/closure/archive/slides/slide3_smoothing_problem.py deleted file mode 100644 index 7855bbb..0000000 --- a/closure/archive/slides/slide3_smoothing_problem.py +++ /dev/null @@ -1,158 +0,0 @@ -"""Slide 3: Hard clamp vs softplus smoothing at the stopping boundary.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl - -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 14, - 'axes.labelsize': 16, - 'axes.titlesize': 18, - 'xtick.labelsize': 13, - 'ytick.labelsize': 13, - 'legend.fontsize': 12, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, - 'lines.linewidth': 2.0, -}) - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - generate_muon_segments_scan, -) - -STEP_SIZE_MM = 0.5 -N_SEGMENTS = 4000 -MIN_ENERGY = 10.0 -ENERGY = 200.0 - -log_T, dedx = load_dedx_table_jax() -start = jnp.zeros(3) -theta, phi = jnp.float32(0.8), jnp.float32(1.2) - -# ── Generate hard and smooth (multiple temperatures) ── -_, de_hard = generate_muon_segments_scan( - jnp.float32(ENERGY), start, theta, phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - min_energy_mev=MIN_ENERGY, smooth_temperature=0.0) -jax.block_until_ready(de_hard) - -smooth_temps = [0.05, 0.2, 1.0] -smooth_colors = ['#4DAF4A', '#FF7F00', '#984EA3'] -de_smooth = {} -for T in smooth_temps: - _, de_s = generate_muon_segments_scan( - jnp.float32(ENERGY), start, theta, phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - min_energy_mev=MIN_ENERGY, smooth_temperature=T) - jax.block_until_ready(de_s) - de_smooth[T] = np.array(de_s) - -de_hard_np = np.array(de_hard) -n_active = int(np.sum(de_hard_np > 1e-6)) -dist_cm = np.arange(N_SEGMENTS) * STEP_SIZE_MM / 10.0 - -# ── Compute gradients w.r.t. energy for hard and smooth ── -def loss_hard(E): - _, de = generate_muon_segments_scan( - E, start, theta, phi, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - min_energy_mev=MIN_ENERGY, smooth_temperature=0.0) - return jnp.sum(de) - -def loss_smooth_02(E): - _, de = generate_muon_segments_scan( - E, start, theta, phi, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - min_energy_mev=MIN_ENERGY, smooth_temperature=0.2) - return jnp.sum(de) - -grad_hard_fn = jax.jit(jax.value_and_grad(loss_hard)) -grad_smooth_fn = jax.jit(jax.value_and_grad(loss_smooth_02)) - -# Warm up -_ = grad_hard_fn(jnp.float32(ENERGY)) -_ = grad_smooth_fn(jnp.float32(ENERGY)) - -E_sweep = np.linspace(100, 280, 80) -grad_hard_vals = np.empty(len(E_sweep)) -grad_smooth_vals = np.empty(len(E_sweep)) -loss_hard_vals = np.empty(len(E_sweep)) -loss_smooth_vals = np.empty(len(E_sweep)) - -for i, E in enumerate(E_sweep): - lh, gh = grad_hard_fn(jnp.float32(E)) - ls, gs = grad_smooth_fn(jnp.float32(E)) - grad_hard_vals[i] = float(gh) - grad_smooth_vals[i] = float(gs) - loss_hard_vals[i] = float(lh) - loss_smooth_vals[i] = float(ls) - -# ── Figure ── -fig, axes = plt.subplots(1, 3, figsize=(17, 5.5)) - -# --- Panel 1: dE per segment near stopping --- -ax = axes[0] -zoom_lo = max(0, n_active - 150) -zoom_hi = n_active + 30 -sl = slice(zoom_lo, zoom_hi) - -ax.plot(dist_cm[sl], de_hard_np[sl], color='#2166AC', lw=2.5, - label='Hard clamp ($T=0$)', zorder=5) -for T, color in zip(smooth_temps, smooth_colors): - ax.plot(dist_cm[sl], de_smooth[T][sl], color=color, lw=1.8, - alpha=0.85, label=f'Softplus $T={T}$') - -ax.set_xlabel('Distance Along Track (cm)') -ax.set_ylabel('$\\Delta E$ (MeV / segment)') -ax.set_title('Stopping Boundary') -ax.legend(loc='upper left', framealpha=0.9, edgecolor='0.7', fontsize=10) -ax.grid(True, alpha=0.25) - -# --- Panel 2: total dE vs initial energy (forward) --- -ax = axes[1] -ax.plot(E_sweep, loss_hard_vals, color='#2166AC', lw=2.5, - label='Hard clamp') -ax.plot(E_sweep, loss_smooth_vals, color='#FF7F00', lw=2, ls='--', - label='Softplus $T=0.2$') -ax.set_xlabel('Initial Kinetic Energy (MeV)') -ax.set_ylabel('Total Energy Deposited (MeV)') -ax.set_title('Forward: $\\sum \\Delta E$ vs Energy') -ax.legend(framealpha=0.9, edgecolor='0.7') -ax.grid(True, alpha=0.25) - -# --- Panel 3: gradient d(sum dE)/dE --- -ax = axes[2] -ax.plot(E_sweep, grad_hard_vals, color='#2166AC', lw=2.5, - label='Hard clamp (AD)') -ax.plot(E_sweep, grad_smooth_vals, color='#FF7F00', lw=2, - label='Softplus $T=0.2$ (AD)') -ax.axhline(1.0, color='gray', ls=':', lw=1.2, alpha=0.6) -ax.text(280, 1.02, 'Ideal = 1.0', fontsize=10, color='gray', - ha='right', va='bottom') - -ax.set_xlabel('Initial Kinetic Energy (MeV)') -ax.set_ylabel('$\\partial (\\sum \\Delta E) / \\partial E_0$') -ax.set_title('Autodiff Gradient') -ax.legend(framealpha=0.9, edgecolor='0.7') -ax.grid(True, alpha=0.25) - -# Annotate the hard-clamp gradient problem -ax.annotate('Hard clamp:\nnon-smooth gradient', - xy=(130, grad_hard_vals[np.argmin(np.abs(E_sweep - 130))]), - fontsize=10, color='#2166AC', - xytext=(140, 0.4), - arrowprops=dict(arrowstyle='->', color='#2166AC', lw=1.2)) - -fig.tight_layout(w_pad=2.5) - -out = os.path.join(os.path.dirname(__file__), 'slide3_smoothing_problem.png') -fig.savefig(out, bbox_inches='tight') -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/slide4_scan_vs_csda.png b/closure/archive/slides/slide4_scan_vs_csda.png deleted file mode 100644 index ce1f425..0000000 Binary files a/closure/archive/slides/slide4_scan_vs_csda.png and /dev/null differ diff --git a/closure/archive/slides/slide4_scan_vs_csda.py b/closure/archive/slides/slide4_scan_vs_csda.py deleted file mode 100644 index 7d12802..0000000 --- a/closure/archive/slides/slide4_scan_vs_csda.py +++ /dev/null @@ -1,139 +0,0 @@ -"""Slide 4: Scan vs CSDA — identical results, massive speedup.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl -import time - -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 16, - 'axes.labelsize': 18, - 'axes.titlesize': 20, - 'xtick.labelsize': 14, - 'ytick.labelsize': 14, - 'legend.fontsize': 13, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, - 'lines.linewidth': 2.0, -}) - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - build_consistent_csda_table, - generate_muon_segments_scan, - generate_muon_segments_csda, -) - -STEP_SIZE_MM = 0.5 -N_SEGMENTS = 4000 -MIN_ENERGY = 10.0 -ENERGY = 200.0 - -log_T, dedx = load_dedx_table_jax() -R_cm, T_MeV = build_consistent_csda_table(log_T, dedx, n_points=10000) - -start = jnp.zeros(3) -theta, phi = jnp.float32(0.8), jnp.float32(1.2) -E = jnp.float32(ENERGY) - -# Generate with both methods -_, de_scan = generate_muon_segments_scan( - E, start, theta, phi, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - min_energy_mev=MIN_ENERGY, smooth_temperature=0.0) -jax.block_until_ready(de_scan) - -_, de_csda = generate_muon_segments_csda( - E, start, theta, phi, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - R_cm, T_MeV, relax_steps=2.0) -jax.block_until_ready(de_csda) - -de_scan_np = np.array(de_scan) -de_csda_np = np.array(de_csda) -dist_cm = np.arange(N_SEGMENTS) * STEP_SIZE_MM / 10.0 -n_active = int(np.sum(de_scan_np > 1e-6)) - -# Speed benchmark -fwd_scan = jax.jit(lambda: generate_muon_segments_scan( - E, start, theta, phi, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - min_energy_mev=MIN_ENERGY, smooth_temperature=0.0)) -fwd_csda = jax.jit(lambda: generate_muon_segments_csda( - E, start, theta, phi, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - R_cm, T_MeV)) - -# Warm up -jax.block_until_ready(fwd_scan()) -jax.block_until_ready(fwd_csda()) - -N_RUNS = 100 -t0 = time.perf_counter() -for _ in range(N_RUNS): - jax.block_until_ready(fwd_scan()) -t_scan = (time.perf_counter() - t0) / N_RUNS * 1000 - -t0 = time.perf_counter() -for _ in range(N_RUNS): - jax.block_until_ready(fwd_csda()) -t_csda = (time.perf_counter() - t0) / N_RUNS * 1000 - -speedup = t_scan / t_csda -print(f'Scan: {t_scan:.2f} ms, CSDA: {t_csda:.3f} ms, Speedup: {speedup:.0f}x') - -# ── Figure ── -fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5.5)) - -# Left: overlay of dE profiles -end = n_active + 30 -ax1.plot(dist_cm[:end], de_scan_np[:end], color='#2166AC', lw=2.5, - label='Sequential scan', zorder=3) -ax1.plot(dist_cm[:end], de_csda_np[:end], color='#D6604D', lw=1.5, - ls='--', label='CSDA parallel', zorder=4) - -ax1.set_xlabel('Distance Along Track (cm)') -ax1.set_ylabel('$\\Delta E$ per Segment (MeV)') -ax1.set_title('Energy Deposits: Scan vs CSDA') -ax1.legend(framealpha=0.9, edgecolor='0.7') -ax1.grid(True, alpha=0.25) -ax1.set_ylim(bottom=-0.005) - -# Inset: residual over the active region -ax_in = ax1.inset_axes([0.3, 0.45, 0.55, 0.4]) -active_end = n_active + 5 -residual = de_scan_np[:active_end] - de_csda_np[:active_end] -ax_in.plot(dist_cm[:active_end], residual * 1e3, color='0.3', lw=1.2) -ax_in.set_ylabel('Residual ($\\times 10^{-3}$ MeV)', fontsize=10) -ax_in.set_xlabel('Distance (cm)', fontsize=10) -ax_in.tick_params(labelsize=9) -max_res = np.nanmax(np.abs(residual)) -ax_in.set_title(f'max |res| = {max_res:.1e} MeV', fontsize=10) -ax_in.grid(True, alpha=0.2) -ax_in.axhline(0, color='k', lw=0.5) - -# Right: speed comparison bar chart -methods = ['Scan\n(sequential)', 'CSDA\n(parallel)'] -times = [t_scan, t_csda] -colors = ['#2166AC', '#D6604D'] -bars = ax2.bar(methods, times, color=colors, width=0.5, edgecolor='0.3', lw=1.2) - -# Add time labels on bars -for bar, t in zip(bars, times): - ax2.text(bar.get_x() + bar.get_width()/2, bar.get_height() + t_scan*0.03, - f'{t:.2f} ms', ha='center', va='bottom', fontsize=14, fontweight='bold') - -ax2.set_ylabel('Runtime (ms)') -ax2.set_title(f'Forward Pass Speed ({speedup:.0f}x faster)') -ax2.grid(True, axis='y', alpha=0.25) -ax2.set_ylim(0, t_scan * 1.25) - -fig.tight_layout(w_pad=3) -out = os.path.join(os.path.dirname(__file__), 'slide4_scan_vs_csda.png') -fig.savefig(out, bbox_inches='tight') -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/slide5_softplus_relaxation.png b/closure/archive/slides/slide5_softplus_relaxation.png deleted file mode 100644 index bf00e54..0000000 Binary files a/closure/archive/slides/slide5_softplus_relaxation.png and /dev/null differ diff --git a/closure/archive/slides/slide5_softplus_relaxation.py b/closure/archive/slides/slide5_softplus_relaxation.py deleted file mode 100644 index 27452e9..0000000 --- a/closure/archive/slides/slide5_softplus_relaxation.py +++ /dev/null @@ -1,129 +0,0 @@ -"""Slide 5: Softplus relaxation — the smooth clamp and its effect on the Bragg peak.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl - -mpl.rcParams.update({ - 'font.family': 'serif', - 'font.size': 16, - 'axes.labelsize': 18, - 'axes.titlesize': 20, - 'xtick.labelsize': 14, - 'ytick.labelsize': 14, - 'legend.fontsize': 13, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'xtick.major.width': 1.0, - 'ytick.major.width': 1.0, - 'lines.linewidth': 2.2, -}) - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - build_consistent_csda_table, -) - -STEP_SIZE_MM = 0.5 -STEP_SIZE_CM = STEP_SIZE_MM / 10.0 -N_SEGMENTS = 4000 -ENERGY = 200.0 - -log_T, dedx = load_dedx_table_jax() -R_cm, T_MeV = build_consistent_csda_table(log_T, dedx, n_points=10000) -R_cm_j = jnp.array(R_cm) -T_MeV_j = jnp.array(T_MeV) -E = jnp.float32(ENERGY) - -# ── Hard clamp CSDA baseline (no softplus) ── -def csda_hard(energy): - indices = jnp.arange(N_SEGMENTS) - R_initial = jnp.interp(jnp.log(energy), jnp.log(T_MeV_j), R_cm_j) - R_at_start = R_initial - indices * STEP_SIZE_CM - R_at_end = R_initial - (indices + 1) * STEP_SIZE_CM - R_floor = R_cm_j[0] - E_start = jnp.interp(jnp.maximum(R_at_start, R_floor), R_cm_j, T_MeV_j) - E_end = jnp.interp(jnp.maximum(R_at_end, R_floor), R_cm_j, T_MeV_j) - return jnp.maximum(E_start - E_end, 0.0) - -def csda_soft(energy, relax_steps): - indices = jnp.arange(N_SEGMENTS) - relax = STEP_SIZE_CM * relax_steps - R_initial = jnp.interp(jnp.log(energy), jnp.log(T_MeV_j), R_cm_j) - R_at_start = R_initial - indices * STEP_SIZE_CM - R_at_end = R_initial - (indices + 1) * STEP_SIZE_CM - R_floor = R_cm_j[0] - R_s = R_floor + jax.nn.softplus((R_at_start - R_floor) / relax) * relax - R_e = R_floor + jax.nn.softplus((R_at_end - R_floor) / relax) * relax - E_start = jnp.interp(R_s, R_cm_j, T_MeV_j) - E_end = jnp.interp(R_e, R_cm_j, T_MeV_j) - return jnp.maximum(E_start - E_end, 0.0) - -de_hard_np = np.array(csda_hard(E)) -n_active = int(np.sum(de_hard_np > 1e-6)) -dist_cm = np.arange(N_SEGMENTS) * STEP_SIZE_CM - -relax_vals = [1.0, 2.0, 5.0, 10.0] -relax_colors = ['#4DAF4A', '#2166AC', '#FF7F00', '#984EA3'] -de_relax = {} -for rv in relax_vals: - de_relax[rv] = np.array(csda_soft(E, rv)) - -# ── Figure: two panels ── -fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5.5)) - -# --- Left: softplus vs max illustration --- -x = np.linspace(-4, 4, 500) -ax1.plot(x, np.maximum(x, 0), color='0.3', lw=2.5, label='$\\max(x, 0)$') -for relax_w, color, label in [(0.5, '#4DAF4A', '$\\lambda = 0.5$'), - (1.0, '#2166AC', '$\\lambda = 1.0$'), - (2.0, '#FF7F00', '$\\lambda = 2.0$')]: - sp = relax_w * np.log(1 + np.exp(x / relax_w)) - ax1.plot(x, sp, color=color, lw=2, label=f'softplus, {label}') - -ax1.set_xlabel('$x$') -ax1.set_ylabel('$f(x)$') -ax1.set_title('Softplus Approximation') -ax1.legend(framealpha=0.9, edgecolor='0.7', fontsize=12) -ax1.grid(True, alpha=0.25) -ax1.set_xlim(-4, 4) -ax1.set_ylim(-0.3, 4.5) - -ax1.text(0.03, 0.97, - r'$\mathrm{softplus}_\lambda(x) = \lambda \ln(1 + e^{x/\lambda})$', - transform=ax1.transAxes, fontsize=14, - va='top', ha='left', - bbox=dict(boxstyle='round,pad=0.3', facecolor='white', - edgecolor='0.7', alpha=0.9)) - -# --- Right: Bragg peak region for different relax values --- -zoom_lo = max(0, n_active - 120) -zoom_hi = n_active + 40 -sl = slice(zoom_lo, zoom_hi) - -ax2.plot(dist_cm[sl], de_hard_np[sl], color='0.3', lw=2.5, - label='Hard clamp (max)', zorder=5) -for rv, color in zip(relax_vals, relax_colors): - is_default = (rv == 2.0) - lw = 2.5 if is_default else 1.5 - suffix = ' (default)' if is_default else '' - ax2.plot(dist_cm[sl], de_relax[rv][sl], color=color, lw=lw, - label=f'relax = {rv:.0f}$\\times$ step{suffix}', - zorder=4 if is_default else 3) - -ax2.set_xlabel('Distance Along Track (cm)') -ax2.set_ylabel('$\\Delta E$ per Segment (MeV)') -ax2.set_title('Effect on Bragg Peak') -ax2.legend(framealpha=0.9, edgecolor='0.7', fontsize=11) -ax2.grid(True, alpha=0.25) - -fig.tight_layout(w_pad=3) -out = os.path.join(os.path.dirname(__file__), 'slide5_softplus_relaxation.png') -fig.savefig(out, bbox_inches='tight') -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/slide6_gradient_fix.png b/closure/archive/slides/slide6_gradient_fix.png deleted file mode 100644 index b438727..0000000 Binary files a/closure/archive/slides/slide6_gradient_fix.png and /dev/null differ diff --git a/closure/archive/slides/slide6_gradient_fix.py b/closure/archive/slides/slide6_gradient_fix.py deleted file mode 100644 index 2017858..0000000 --- a/closure/archive/slides/slide6_gradient_fix.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Slide 6: Hard clamp vs softplus — per-segment gradient w.r.t. energy.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt - -plt.rcParams.update({ - 'font.family': 'serif', - 'font.size': 14, - 'axes.labelsize': 16, - 'axes.titlesize': 18, - 'xtick.labelsize': 13, - 'ytick.labelsize': 13, - 'legend.fontsize': 12, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'lines.linewidth': 2.0, -}) - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - build_consistent_csda_table, -) - -STEP_SIZE_MM = 0.5 -STEP_SIZE_CM = STEP_SIZE_MM / 10.0 -N_SEGMENTS = 4000 -ENERGY = 200.0 - -log_T, dedx = load_dedx_table_jax() -R_cm, T_MeV = build_consistent_csda_table(log_T, dedx, n_points=10000) -R_cm = jnp.array(R_cm) -T_MeV = jnp.array(T_MeV) - -def csda_hard(energy): - indices = jnp.arange(N_SEGMENTS) - log_T_csda = jnp.log(T_MeV) - R_initial = jnp.interp(jnp.log(energy), log_T_csda, R_cm) - R_at_start = R_initial - indices * STEP_SIZE_CM - R_at_end = R_initial - (indices + 1) * STEP_SIZE_CM - R_floor = R_cm[0] - E_start = jnp.interp(jnp.maximum(R_at_start, R_floor), R_cm, T_MeV) - E_end = jnp.interp(jnp.maximum(R_at_end, R_floor), R_cm, T_MeV) - return jnp.maximum(E_start - E_end, 0.0) - -relax_val = STEP_SIZE_CM * 2.0 -def csda_soft(energy): - indices = jnp.arange(N_SEGMENTS) - log_T_csda = jnp.log(T_MeV) - R_initial = jnp.interp(jnp.log(energy), log_T_csda, R_cm) - R_at_start = R_initial - indices * STEP_SIZE_CM - R_at_end = R_initial - (indices + 1) * STEP_SIZE_CM - R_floor = R_cm[0] - R_s = R_floor + jax.nn.softplus((R_at_start - R_floor) / relax_val) * relax_val - R_e = R_floor + jax.nn.softplus((R_at_end - R_floor) / relax_val) * relax_val - E_start = jnp.interp(R_s, R_cm, T_MeV) - E_end = jnp.interp(R_e, R_cm, T_MeV) - return jnp.maximum(E_start - E_end, 0.0) - -# Jacobian: d(dE_i)/d(E0) for each segment i -jac_hard_fn = jax.jit(jax.jacfwd(csda_hard)) -jac_soft_fn = jax.jit(jax.jacfwd(csda_soft)) - -E0 = jnp.float32(ENERGY) -jac_hard = np.array(jac_hard_fn(E0)) -jac_soft = np.array(jac_soft_fn(E0)) - -de_hard = np.array(csda_hard(E0)) -de_soft = np.array(csda_soft(E0)) - -n_active = int(np.sum(de_hard > 1e-6)) -dist_cm = np.arange(N_SEGMENTS) * STEP_SIZE_CM - -# ── Figure ── -fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5.5)) - -zoom_lo = max(0, n_active - 120) -zoom_hi = n_active + 30 -sl = slice(zoom_lo, zoom_hi) - -# Left: dE per segment near stopping -ax1.plot(dist_cm[sl], de_hard[sl], color='0.3', lw=2.5, label='Hard clamp') -ax1.plot(dist_cm[sl], de_soft[sl], color='#D6604D', lw=2, ls='--', - label='Softplus (relax = 2x)') -ax1.set_xlabel('Distance Along Track (cm)') -ax1.set_ylabel('dE per segment (MeV)') -ax1.set_title('Energy Deposits Near Stopping') -ax1.legend(framealpha=0.9, edgecolor='0.7') -ax1.grid(True, alpha=0.25) - -# Right: per-segment gradient d(dE_i)/d(E0) -ax2.plot(dist_cm[sl], jac_hard[sl], color='0.3', lw=2.5, label='Hard clamp') -ax2.plot(dist_cm[sl], jac_soft[sl], color='#D6604D', lw=2, label='Softplus (relax = 2x)') -ax2.set_xlabel('Distance Along Track (cm)') -ax2.set_ylabel('d(dE_i) / d(E0)') -ax2.set_title('Per-Segment Gradient w.r.t. Energy') -ax2.legend(framealpha=0.9, edgecolor='0.7') -ax2.grid(True, alpha=0.25) -ax2.axhline(0, color='k', lw=0.5) - -fig.subplots_adjust(left=0.07, right=0.97, bottom=0.12, top=0.92, wspace=0.25) -out = os.path.join(os.path.dirname(__file__), 'slide6_gradient_fix.png') -fig.savefig(out, dpi=200) -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/archive/slides/slide7_speed.png b/closure/archive/slides/slide7_speed.png deleted file mode 100644 index 477376b..0000000 Binary files a/closure/archive/slides/slide7_speed.png and /dev/null differ diff --git a/closure/archive/slides/slide7_speed.py b/closure/archive/slides/slide7_speed.py deleted file mode 100644 index 6724fbe..0000000 --- a/closure/archive/slides/slide7_speed.py +++ /dev/null @@ -1,134 +0,0 @@ -"""Slide 7: Speed comparison — scan vs CSDA for forward and gradient passes.""" -import sys, os -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt -import time - -plt.rcParams.update({ - 'font.family': 'serif', - 'font.size': 16, - 'axes.labelsize': 18, - 'axes.titlesize': 20, - 'xtick.labelsize': 14, - 'ytick.labelsize': 14, - 'legend.fontsize': 14, - 'figure.dpi': 200, - 'savefig.dpi': 200, - 'axes.linewidth': 1.2, - 'lines.linewidth': 2.0, -}) - -from closure_analysis_muon.diff_muon_generator import ( - load_dedx_table_jax, - build_consistent_csda_table, - generate_muon_segments_scan, - generate_muon_segments_csda, -) - -STEP_SIZE_MM = 0.5 -N_SEGMENTS = 4000 -MIN_ENERGY = 10.0 -N_RUNS = 100 - -log_T, dedx = load_dedx_table_jax() -R_cm, T_MeV = build_consistent_csda_table(log_T, dedx, n_points=10000) - -start = jnp.zeros(3) -E = jnp.float32(500.0) -theta, phi = jnp.float32(0.8), jnp.float32(1.2) - -# Forward functions -fwd_scan = jax.jit(lambda e: generate_muon_segments_scan( - e, start, theta, phi, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - min_energy_mev=MIN_ENERGY, smooth_temperature=0.0)) -fwd_csda = jax.jit(lambda e: generate_muon_segments_csda( - e, start, theta, phi, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - R_cm, T_MeV)) - -# Gradient functions -grad_scan = jax.jit(jax.value_and_grad( - lambda e: jnp.sum(generate_muon_segments_scan( - e, start, theta, phi, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - min_energy_mev=MIN_ENERGY, smooth_temperature=0.2)[1]))) -grad_csda = jax.jit(jax.value_and_grad( - lambda e: jnp.sum(generate_muon_segments_csda( - e, start, theta, phi, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - R_cm, T_MeV)[1]))) - -# Warm up -jax.block_until_ready(fwd_scan(E)) -jax.block_until_ready(fwd_csda(E)) -jax.block_until_ready(grad_scan(E)) -jax.block_until_ready(grad_csda(E)) - -# Benchmark -def bench(fn, E, n): - t0 = time.perf_counter() - for _ in range(n): - jax.block_until_ready(fn(E)) - return (time.perf_counter() - t0) / n * 1000 - -t_fwd_scan = bench(fwd_scan, E, N_RUNS) -t_fwd_csda = bench(fwd_csda, E, N_RUNS) -t_grad_scan = bench(grad_scan, E, N_RUNS) -t_grad_csda = bench(grad_csda, E, N_RUNS) - -print(f'Forward: scan={t_fwd_scan:.1f}ms csda={t_fwd_csda:.2f}ms ' - f'speedup={t_fwd_scan/t_fwd_csda:.0f}x') -print(f'Gradient: scan={t_grad_scan:.1f}ms csda={t_grad_csda:.2f}ms ' - f'speedup={t_grad_scan/t_grad_csda:.0f}x') - -# ── Figure ── -fig, ax = plt.subplots(figsize=(9, 6)) - -labels = ['Forward\n(scan)', 'Forward\n(CSDA)', 'Gradient\n(scan)', 'Gradient\n(CSDA)'] -times = [t_fwd_scan, t_fwd_csda, t_grad_scan, t_grad_csda] -colors = ['#2166AC', '#D6604D', '#2166AC', '#D6604D'] -hatches = [None, None, '///', '///'] - -bars = ax.bar(labels, times, color=colors, width=0.55, edgecolor='0.2', lw=1.2) -for bar, h in zip(bars, hatches): - if h: - bar.set_hatch(h) - -# Time labels -for bar, t in zip(bars, times): - if t > 100: - txt = f'{t:.0f} ms' - else: - txt = f'{t:.1f} ms' - ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() * 1.05, - txt, ha='center', va='bottom', fontsize=14, fontweight='bold') - -# Speedup annotations -fwd_speedup = t_fwd_scan / t_fwd_csda -grad_speedup = t_grad_scan / t_grad_csda -mid_fwd = np.sqrt(t_fwd_scan * t_fwd_csda) -mid_grad = np.sqrt(t_grad_scan * t_grad_csda) -ax.text(0.5, mid_fwd, f'{fwd_speedup:.0f}x', - fontsize=22, fontweight='bold', color='#4DAF4A', ha='center', va='center') -ax.text(2.5, mid_grad, f'{grad_speedup:.0f}x', - fontsize=22, fontweight='bold', color='#4DAF4A', ha='center', va='center') - -ax.set_ylabel('Runtime (ms)') -ax.set_title('Sequential Scan vs Parallel CSDA') -ax.set_yscale('log') -ax.grid(True, axis='y', alpha=0.25, which='both') - -# Legend for scan/csda -from matplotlib.patches import Patch -legend_elements = [Patch(facecolor='#2166AC', edgecolor='0.2', label='Sequential scan'), - Patch(facecolor='#D6604D', edgecolor='0.2', label='Parallel CSDA')] -ax.legend(handles=legend_elements, loc='upper right', framealpha=0.9, edgecolor='0.7') - -fig.subplots_adjust(left=0.12, right=0.95, bottom=0.12, top=0.92) -out = os.path.join(os.path.dirname(__file__), 'slide7_speed.png') -fig.savefig(out, dpi=200) -plt.close(fig) -print(f'Saved {out}') diff --git a/closure/mcs/check_mcs_amount.py b/closure/mcs/check_mcs_amount.py deleted file mode 100644 index 3598a9b..0000000 --- a/closure/mcs/check_mcs_amount.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Sanity-check the MCS scattering amount in the truth generator. - -Compares the reconstructed Highland theta0 + the cumsum-model net deflection -against the textbook single-thickness Highland expectation, and shows the -seed-to-seed spread (is seed 42 a low realization?). -""" -import jax -import jax.numpy as jnp -import numpy as np - -from closure.mcs.mcs_physics import _ke_to_beta_p, highland_theta0, X0_LAR_CM, MUON_MASS_MEV -from closure.mcs.forward import generate_mcs_truth -from tools.particle_generator import ( - load_dedx_table_jax, _get_consistent_csda, _csda_energy_deposits, -) - -log_T, dedx = load_dedx_table_jax() -N, step_mm = 2000, 0.5 -step_cm = step_mm / 10.0 -E0 = 500.0 -L_cm = N * step_cm - -print(f"muon mass={MUON_MASS_MEV} MeV, X0(LAr)={X0_LAR_CM} cm, " - f"track L={L_cm} cm ({N} x {step_mm} mm)") - -# --- per-step theta0 at 500 MeV --- -b, p, bp = _ke_to_beta_p(jnp.float32(E0)) -th0_step = float(highland_theta0(bp, step_cm)) -print(f"\n500 MeV: beta={float(b):.4f}, p={float(p):.1f} MeV, beta*p={float(bp):.1f} MeV") -print(f" Highland theta0 per 0.5mm step = {th0_step*1000:.3f} mrad (per plane)") - -# --- textbook single-thickness Highland over the full 100 cm (fixed E=500) --- -th_full = float(highland_theta0(bp, L_cm)) -print(f" single-thickness Highland (100cm, fixed 500 MeV) = {th_full*1000:.1f} mrad (plane RMS)") - -# --- energy-correct prediction: sqrt(sum theta0(E_k)^2) over the track --- -R_cm, T_MeV = _get_consistent_csda(log_T, dedx) -R0 = float(jnp.interp(jnp.log(E0), jnp.log(T_MeV), R_cm)) -idx = np.arange(N) -R_mid = np.maximum(R0 - (idx + 0.5) * step_cm, float(R_cm[0])) -E_mid = np.interp(R_mid, np.asarray(R_cm), np.asarray(T_MeV)) -_, _, bp_mid = _ke_to_beta_p(jnp.asarray(E_mid)) -th0_prof = np.asarray(highland_theta0(bp_mid, step_cm)) -pred_plane_rms = np.sqrt(np.sum(th0_prof ** 2)) -print(f" E loss: {E0:.0f} -> {E_mid[-1]:.0f} MeV over the track") -print(f" theta0/step: start {th0_prof[0]*1000:.2f} -> end {th0_prof[-1]*1000:.2f} mrad") -print(f" predicted NET plane RMS = sqrt(sum theta0^2) = {pred_plane_rms*1000:.1f} mrad") -print(f" predicted |net| (2D, =plane_rms*sqrt(2)) RMS = {pred_plane_rms*np.sqrt(2)*1000:.1f} mrad") - -# --- realized net deflection across seeds --- -nets, segrms = [], [] -for s in range(40): - pos, de, dt1, dt2 = generate_mcs_truth( - jnp.float32(E0), jnp.zeros(3, jnp.float32), - jnp.float32(np.pi/4), jnp.float32(np.pi/6), - step_mm, N, log_T, dedx, jax.random.PRNGKey(s)) - nets.append(float(jnp.sqrt(jnp.sum(dt1)**2 + jnp.sum(dt2)**2)) * 1000) - segrms.append(float(jnp.sqrt(jnp.mean(dt1**2 + dt2**2))) * 1000) -nets = np.array(nets) -print(f"\nrealized per-seg RMS (combined 2 planes): {np.mean(segrms):.2f} mrad") -print(f"realized |net| deflection over 40 seeds: " - f"mean={nets.mean():.1f}, median={np.median(nets):.1f}, " - f"min={nets.min():.1f}, max={nets.max():.1f} mrad") -print(f" seed 42 |net| = {nets[42] if len(nets)>42 else 'n/a'}", end='') -# seed 42 specifically -_, _, d1_42, d2_42 = generate_mcs_truth( - jnp.float32(E0), jnp.zeros(3, jnp.float32), - jnp.float32(np.pi/4), jnp.float32(np.pi/6), - step_mm, N, log_T, dedx, jax.random.PRNGKey(42)) -net42 = float(jnp.sqrt(jnp.sum(d1_42)**2 + jnp.sum(d2_42)**2)) * 1000 -pct = 100 * np.mean(nets <= net42) -print(f"\n seed 42 |net| = {net42:.1f} mrad (~{pct:.0f}th percentile of the 40 seeds)") - -# --- lateral displacement of the track from a straight line (seed 42) --- -pos42, _, _, _ = generate_mcs_truth( - jnp.float32(E0), jnp.zeros(3, jnp.float32), - jnp.float32(np.pi/4), jnp.float32(np.pi/6), - step_mm, N, log_T, dedx, jax.random.PRNGKey(42)) -pos42 = np.asarray(pos42) -straight = pos42[0] + (pos42[-1] - pos42[0]) * (np.arange(N)[:, None] / (N - 1)) -lateral = np.linalg.norm(pos42 - straight, axis=1) -print(f"\nseed 42 lateral deviation from straight line: " - f"max={lateral.max():.1f} mm, rms={np.sqrt(np.mean(lateral**2)):.1f} mm " - f"(wire pitch = 3 mm)") diff --git a/closure/mcs/coarse2fine.py b/closure/mcs/coarse2fine.py deleted file mode 100644 index 96371bd..0000000 --- a/closure/mcs/coarse2fine.py +++ /dev/null @@ -1,147 +0,0 @@ -"""Coarse-to-fine Sobolev schedule: can we beat the ~6.7 mm converged crossover? - -§7 of FINDINGS_MCS.md showed the wire fine-angle floor is optimization-limited: -the Sobolev 1/k^{2s} weight starves the high-frequency gradients that drive the -fine angles, so they converge very slowly. Hypothesis: lock the coarse -trajectory at s=1.5, then SHARPEN at a smaller s (flatter spectral weight -> -stronger high-frequency gradients) once the coarse solution is in place. Lower s -overfits *from zero* (resolve_scan.py), but starting from a converged coarse -solution it should sharpen the fine angles without global wandering (globals are -fixed at truth here anyway). - -Compares single-s=1.5 (8000 steps) vs coarse-to-fine (3000 @ s=1.5, then 5000 -@ s=0.75). - - python3 -m closure.mcs.coarse2fine -""" - -import time -import jax -import jax.numpy as jnp -import numpy as np -import optax - -from closure.mcs.forward import ( - mcs_cumsum_forward, generate_mcs_truth, highland_prior, build_mcs_forward, - mask_outside_volume, -) -from closure.mcs.study import ( - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, TRUTH_X, TRUTH_Y, TRUTH_Z, - TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, ANGLE_SCALE, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight - - -def wcorr(f1, f2, t1, t2, W): - def agg(x): - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - at = np.concatenate([agg(t1), agg(t2)]) - af = np.concatenate([agg(f1), agg(f2)]) - return np.corrcoef(af, at)[0, 1] if len(at) > 1 else float('nan') - - -def crossover(scales_mm, corrs, thr=0.5): - for i in range(len(corrs) - 1): - if corrs[i] < thr <= corrs[i + 1]: - t = (thr - corrs[i]) / (corrs[i + 1] - corrs[i]) - return float(np.exp(np.log(scales_mm[i]) + - t * (np.log(scales_mm[i+1]) - np.log(scales_mm[i])))) - return None - - -def main(): - print("=" * 72) - print("Coarse-to-fine Sobolev schedule for MCS fine-angle resolution") - print("=" * 72, flush=True) - - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - key = jax.random.PRNGKey(42) - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - de_tm = mask_outside_volume(pos_t, de_t, half_ext) - t0 = time.time() - truth_sig = jax.jit(forward)(pos_t, de_tm) - for s in truth_sig: - jax.block_until_ready(s) - print(f"compiled ({time.time()-t0:.1f}s)", flush=True) - start = jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32) - t1, t2 = np.asarray(dt1_t), np.asarray(dt2_t) - - def make_lg(weights, lam): - def loss(params): - dt1 = params[:N_SEGMENTS] * ANGLE_SCALE - dt2 = params[N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward( - jnp.float32(TRUTH_ENERGY), start, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_sig, weights) - pr = highland_prior(dt1, dt2, jnp.float32(TRUTH_ENERGY), - STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + lam * pr / N_SEGMENTS - return jax.jit(jax.value_and_grad(loss)) - - w15 = tuple(make_sobolev_weight(*truth_sig[p].shape, s=1.5) for p in range(6)) - w075 = tuple(make_sobolev_weight(*truth_sig[p].shape, s=0.75) for p in range(6)) - - Wsc = [(6, 3.0), (12, 6.0), (25, 12.5), (50, 25.0), (100, 50.0)] - - def run(steps, lg, params, opt, state): - for _ in range(steps): - l, g = lg(params) - upd, state = opt.update(g, state, params) - params = optax.apply_updates(params, upd) - return params, state, float(l) - - def report(tag, params): - f1 = np.asarray(params[:N_SEGMENTS]) * ANGLE_SCALE - f2 = np.asarray(params[N_SEGMENTS:]) * ANGLE_SCALE - cs = [wcorr(f1, f2, t1, t2, W) for W, _ in Wsc] - cross = crossover([m for _, m in Wsc], cs) - cum = np.sqrt(np.sum(f1)**2 + np.sum(f2)**2) / \ - (np.sqrt(np.sum(t1)**2 + np.sum(t2)**2) + 1e-12) - print(f"{tag:>22} | " + " ".join(f"{c:>6.3f}" for c in cs) + - f" | L@0.5={cross:.1f}mm cum={cum:.2f}" if cross else - f"{tag:>22} | " + " ".join(f"{c:>6.3f}" for c in cs) + - f" | L@0.5=>50mm cum={cum:.2f}", flush=True) - return cs - - print(f"\n{'config':>22} | " + " ".join(f"{m:>5.1f}mm" for _, m in Wsc) + " | crossover") - print("-" * 86, flush=True) - - # Baseline for reference (from a prior run): single s=1.5 @ 8000 steps gives - # crossover ~7.0 mm, cum 0.63. Here we test whether sharpening beats it. - - # --- coarse-to-fine: converge stage-1 @ s=1.5, then sharpen @ s=0.75 --- - lg15 = make_lg(w15, 3e-2) - opt = optax.adam(optax.exponential_decay(0.02, 1, 0.99975)) - p = jnp.zeros(2 * N_SEGMENTS) - st = opt.init(p) - p, st, _ = run(5000, lg15, p, opt, st) - report(" after 5000 @ s=1.5", p) # should reproduce ~6.7 mm crossover - lg075 = make_lg(w075, 3e-2) - opt2 = optax.adam(optax.exponential_decay(0.008, 1, 0.9997)) - st2 = opt2.init(p) - p, st2, _ = run(4000, lg075, p, opt2, st2) - report(" +4000 @ s=0.75 (C2F)", p) - - print("\nDone.") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/coarse_direct.py b/closure/mcs/coarse_direct.py deleted file mode 100644 index ffae0ca..0000000 --- a/closure/mcs/coarse_direct.py +++ /dev/null @@ -1,120 +0,0 @@ -"""Direct coarse-scale fit vs fine-fit-then-aggregate for MCS angles. - -The ~13 mm aggregate-angle crossover is invariant to loss order and drift depth. -One untested lever remains: so far we fit 2000 free per-segment angles and then -*sum* them into windows — summing noisy per-segment estimates loses coherence. -Fitting ONE angle per window directly (M = N/G DOF) is far better conditioned -(no fine null-space to wander in). This compares, at each scale G: - - direct : fit 2M coarse angles, correlate vs truth aggregated at G - aggregate: fit 2N fine angles (s=1.5 best), sum to windows of G, correlate - -If `direct` beats `aggregate` at small G, we *can* resolve finer than the -fine-fit crossover by matching the parameterization to the scale. - - python3 -m closure.mcs.coarse_direct -""" - -import time -import jax -import jax.numpy as jnp -import numpy as np - -from closure.mcs.forward import ( - mcs_cumsum_forward, generate_mcs_truth, highland_prior, build_mcs_forward, - mask_outside_volume, -) -from closure.mcs.study import ( - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, TRUTH_X, TRUTH_Y, TRUTH_Z, - TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, ANGLE_SCALE, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - run_adam, expand_coarse, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight - - -def agg(x, W): - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - - -def main(): - print("=" * 70) - print("Direct coarse fit vs fine-then-aggregate (scattering-only)") - print("=" * 70, flush=True) - - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - key = jax.random.PRNGKey(42) - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - de_tm = mask_outside_volume(pos_t, de_t, half_ext) - t0 = time.time() - truth_sig = jax.jit(forward)(pos_t, de_tm) - for s in truth_sig: - jax.block_until_ready(s) - print(f"compiled ({time.time()-t0:.1f}s)", flush=True) - weights = tuple(make_sobolev_weight(*truth_sig[p].shape, s=1.5) for p in range(6)) - start = jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32) - dt1_t, dt2_t = np.asarray(dt1_t), np.asarray(dt2_t) - - def make_loss(G, M): - def loss(params, lam_): - dt1, dt2 = expand_coarse(params, G, M) # constant within block - pos, de = mcs_cumsum_forward( - jnp.float32(TRUTH_ENERGY), start, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_sig, weights) - pr = highland_prior(dt1, dt2, jnp.float32(TRUTH_ENERGY), - STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + lam_ * pr / N_SEGMENTS - return loss - - # fine baseline (G=1) - lg_fine = jax.jit(jax.value_and_grad(make_loss(1, N_SEGMENTS))) - best_fine, _ = run_adam(lg_fine, jnp.zeros(2 * N_SEGMENTS), 350, 0.01, - jnp.float32(3e-2), decay=0.99, early_stop=True) - f1 = np.asarray(best_fine[:N_SEGMENTS]) * ANGLE_SCALE - f2 = np.asarray(best_fine[N_SEGMENTS:]) * ANGLE_SCALE - - print(f"\n{'G':>4} {'L_mm':>6} | {'direct_corr':>11} | {'aggregate_corr':>14}") - print("-" * 44, flush=True) - for G in [5, 10, 25, 50, 100]: # must divide N_SEGMENTS=2000 - M = N_SEGMENTS // G - # direct coarse fit - lg = jax.jit(jax.value_and_grad(make_loss(G, M))) - best, _ = run_adam(lg, jnp.zeros(2 * M), 350, 0.01, - jnp.float32(3e-2), decay=0.99, early_stop=True) - # coarse fit angle per block = sum over block of expanded constant value - c1 = np.asarray(best[:M]) * ANGLE_SCALE * G # block-summed deflection - c2 = np.asarray(best[M:]) * ANGLE_SCALE * G - at1, at2 = agg(dt1_t, G), agg(dt2_t, G) - # match lengths - n = min(len(c1), len(at1)) - direct = np.corrcoef(np.concatenate([c1[:n], c2[:n]]), - np.concatenate([at1[:n], at2[:n]]))[0, 1] - # aggregate fine fit - af1, af2 = agg(f1, G), agg(f2, G) - aggc = np.corrcoef(np.concatenate([af1, af2]), - np.concatenate([at1, at2]))[0, 1] - print(f"{G:>4} {G*STEP_SIZE_MM:>6.1f} | {direct:>11.3f} | {aggc:>14.3f}", - flush=True) - - print("\nDone.") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/convergence.py b/closure/mcs/convergence.py deleted file mode 100644 index d456a5c..0000000 --- a/closure/mcs/convergence.py +++ /dev/null @@ -1,157 +0,0 @@ -"""Save + plot the MCS joint-fit convergence history (why it takes many steps). - -Runs the converged joint fit (angle_lr=0.01, seed-32 median event) and records, -per step, the loss, the global errors, and the angle correlation at several -spatial scales. Saves the history to .npz and plots it. The point is to show the -MULTI-TIMESCALE convergence: the coarse/trajectory modes converge in a few -hundred steps while the fine-angle modes crawl for thousands — the signature of -the ill-conditioned double-integral forward (dtheta -> direction -> position). - - python3 -m closure.mcs.convergence -""" -import os -import jax -import jax.numpy as jnp -import numpy as np -import optax -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt - -import closure.mcs.run as R -from closure.mcs.run import ( - build_globals_only_loss, run_optimization, project_unit_circle, - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, SCALES, ANGLE_SCALE, - TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, -) -from closure.mcs.forward import ( - generate_mcs_truth, mcs_cumsum_forward, build_mcs_forward, mask_outside_volume, - highland_prior, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p - -OUT = os.path.dirname(os.path.abspath(__file__)) -SCj = jnp.array(SCALES, jnp.float32) -N_STEPS = 2500 -ANGLE_LR, GLOBAL_LR, DECAY = 0.01, 0.003, 0.9995 -LOG_EVERY = 25 -SCALES_SEG = [(6, 3.0), (12, 6.0), (25, 12.5), (50, 25.0), (100, 50.0), (400, 200.0)] - - -def main(): - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - fwd_j = jax.jit(forward) - - key = jax.random.PRNGKey(32) - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - truth_signals = fwd_j(pos_t, mask_outside_volume(pos_t, de_t, half_ext)) - for s in truth_signals: - jax.block_until_ready(s) - weights = tuple(make_sobolev_weight(*truth_signals[p].shape, s=1.5) for p in range(6)) - t1n, t2n = np.asarray(dt1_t), np.asarray(dt2_t) - - R.LAMBDA_PRIOR = 0.03 - init_g = np.array([TRUTH_X + 100, TRUTH_Y + 100, TRUTH_Z - 100, - np.sin(TRUTH_THETA + 0.5), np.cos(TRUTH_THETA + 0.5), - np.sin(TRUTH_PHI + 0.5), np.cos(TRUTH_PHI + 0.5), - TRUTH_ENERGY + 100]) - loss_g = build_globals_only_loss(forward, log_T, dedx, truth_signals, weights, - dt1_t, dt2_t, half_ext) - params_g, *_ = run_optimization(loss_g, jnp.array(init_g / SCALES, jnp.float32), - 250, 0.015, 'stage1', project_fn=project_unit_circle) - - def full_loss(p): - g = p[:8] * SCj - dt1 = p[8:8 + N_SEGMENTS] * ANGLE_SCALE - dt2 = p[8 + N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward(g[7], jnp.array([g[0], g[1], g[2]]), - g[3], g[4], g[5], g[6], - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_signals, weights) - pr = highland_prior(dt1, dt2, g[7], STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + R.LAMBDA_PRIOR * pr / N_SEGMENTS - - vg = jax.jit(jax.value_and_grad(full_loss)) - - def corr(p, W): - a1 = np.asarray(p[8:8 + N_SEGMENTS]) * ANGLE_SCALE - a2 = np.asarray(p[8 + N_SEGMENTS:]) * ANGLE_SCALE - def agg(x): - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - at = np.concatenate([agg(t1n), agg(t2n)]); af = np.concatenate([agg(a1), agg(a2)]) - return float(np.corrcoef(af, at)[0, 1]) if len(at) > 1 else np.nan - - opt = optax.adam(optax.exponential_decay(ANGLE_LR, 1, DECAY)) - p = jnp.concatenate([params_g, jnp.zeros(2 * N_SEGMENTS)]) - state = opt.init(p) - - loss_hist = np.zeros(N_STEPS) - log_steps, corr_hist, dE_hist, dph_hist = [], [], [], [] - print(f"joint fit: angle_lr={ANGLE_LR}, global_lr={GLOBAL_LR}, {N_STEPS} steps", flush=True) - for step in range(N_STEPS): - loss, grad = vg(p) - loss_hist[step] = float(loss) - upd, state = opt.update(grad, state, p) - upd = upd.at[:8].multiply(GLOBAL_LR / ANGLE_LR) - p = optax.apply_updates(p, upd) - p = p.at[:8].set(project_unit_circle(p[:8])) - if step % LOG_EVERY == 0 or step == N_STEPS - 1: - log_steps.append(step) - corr_hist.append([corr(p, W) for W, _ in SCALES_SEG]) - g = np.asarray(p[:8] * SCj) - dE_hist.append(g[7] - TRUTH_ENERGY) - dph_hist.append(np.degrees(np.arctan2(g[5], g[6])) - np.degrees(TRUTH_PHI)) - corr_hist = np.array(corr_hist) - log_steps = np.array(log_steps) - - npz = os.path.join(OUT, 'mcs_convergence_history.npz') - np.savez(npz, loss=loss_hist, log_steps=log_steps, corr=corr_hist, - scales_mm=np.array([mm for _, mm in SCALES_SEG]), - dE=np.array(dE_hist), dphi=np.array(dph_hist)) - print(f"saved history -> {npz}") - - # report the per-scale step-to-reach-0.5 (or 0.8) to quantify the timescales - for j, (_, mm) in enumerate(SCALES_SEG): - c = corr_hist[:, j] - s50 = log_steps[np.argmax(c >= 0.5)] if (c >= 0.5).any() else None - s80 = log_steps[np.argmax(c >= 0.8)] if (c >= 0.8).any() else None - print(f" scale {mm:>5.1f} mm: corr_final={c[-1]:.3f}, " - f"steps->0.5={s50}, steps->0.8={s80}") - - fig, ax = plt.subplots(1, 2, figsize=(13, 4.8)) - ax[0].semilogy(np.arange(N_STEPS), loss_hist, lw=0.8, color='#3d6aa6') - ax[0].set_xlabel('Adam step'); ax[0].set_ylabel('loss (Sobolev + prior)') - ax[0].set_title('Loss vs step'); ax[0].grid(True, alpha=0.3) - cmap = plt.cm.viridis(np.linspace(0, 0.9, len(SCALES_SEG))) - for j, (_, mm) in enumerate(SCALES_SEG): - ax[1].plot(log_steps, corr_hist[:, j], color=cmap[j], lw=1.6, - label=f'{mm:.0f} mm') - ax[1].axhline(0.5, color='grey', ls=':') - ax[1].set_xlabel('Adam step'); ax[1].set_ylabel('angle corr (learned vs truth)') - ax[1].set_title('Angle recovery by scale — coarse fast, fine slow') - ax[1].legend(title='aggregation', fontsize=8, ncol=2); ax[1].grid(True, alpha=0.3) - fig.suptitle('MCS joint-fit convergence (angle_lr=0.01): the fine scales are ' - 'slow because the forward double-integrates angles -> positions', - fontsize=12) - fig.tight_layout(rect=[0, 0, 1, 0.95]) - fn = os.path.join(OUT, 'mcs_convergence.png') - fig.savefig(fn, dpi=140, bbox_inches='tight') - print(f"saved plot -> {fn}") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/decompose_sweep.py b/closure/mcs/decompose_sweep.py deleted file mode 100644 index cd02246..0000000 --- a/closure/mcs/decompose_sweep.py +++ /dev/null @@ -1,187 +0,0 @@ -"""Decompose the MCS loss (wire vs Highland prior) across the stage transition, -and sweep the prior weight lambda. - -Part A: log the wire term and prior term separately, per iteration, across -stage-1 (wire-only, scattering=truth) -> stage-2 (wire + lambda*prior, scattering -free from 0). Shows what actually jumps when stage 2 turns on. - -Part B: sweep lambda; report the converged wire term, prior term, angle recovery -by scale, net-deflection ratio, and energy error -> what lambda to use. - - python3 -m closure.mcs.decompose_sweep -""" -import os -import jax -import jax.numpy as jnp -import numpy as np -import optax -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt - -import closure.mcs.run as R -from closure.mcs.run import ( - build_globals_only_loss, project_unit_circle, - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, SCALES, ANGLE_SCALE, SOBOLEV_S, - TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, -) -from closure.mcs.forward import ( - generate_mcs_truth, mcs_cumsum_forward, build_mcs_forward, mask_outside_volume, - highland_prior, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p - -OUT = os.path.dirname(os.path.abspath(__file__)) -SCj = jnp.array(SCALES, jnp.float32) -STAGE1, STAGE2 = 250, 1000 -LAMBDAS = [0.0, 1e-3, 1e-2, 3e-2, 1e-1, 3e-1] -DECOMP_LAMBDA = 3e-2 - - -def main(): - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - fwd_j = jax.jit(forward) - - key = jax.random.PRNGKey(32) - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - truth_signals = fwd_j(pos_t, mask_outside_volume(pos_t, de_t, half_ext)) - for s in truth_signals: - jax.block_until_ready(s) - weights = tuple(make_sobolev_weight(*truth_signals[p].shape, s=SOBOLEV_S) for p in range(6)) - t1n, t2n = np.asarray(dt1_t), np.asarray(dt2_t) - cum_truth = np.sqrt(np.sum(t1n) ** 2 + np.sum(t2n) ** 2) * 1000 - - # ---- stage 1 (globals-only, wire-only loss, scattering=truth) ---- - R.LAMBDA_PRIOR = DECOMP_LAMBDA - init_g = np.array([TRUTH_X + 100, TRUTH_Y + 100, TRUTH_Z - 100, - np.sin(TRUTH_THETA + 0.5), np.cos(TRUTH_THETA + 0.5), - np.sin(TRUTH_PHI + 0.5), np.cos(TRUTH_PHI + 0.5), - TRUTH_ENERGY + 100]) - loss_g = build_globals_only_loss(forward, log_T, dedx, truth_signals, weights, - dt1_t, dt2_t, half_ext) - vg_g = jax.jit(jax.value_and_grad(loss_g)) - opt1 = optax.adam(0.015) - pg = jnp.array(init_g / SCALES, jnp.float32) - st1 = opt1.init(pg) - wire1 = [] - print("--- stage 1 (wire-only) ---", flush=True) - for _ in range(STAGE1): - l, gr = vg_g(pg) - wire1.append(float(l)) # stage-1 loss IS the wire term - u, st1 = opt1.update(gr, st1, pg) - pg = project_unit_circle(optax.apply_updates(pg, u)) - - # ---- stage 2: wire + lambda*prior, traced lambda ---- - def terms(p): - g = p[:8] * SCj - dt1 = p[8:8 + N_SEGMENTS] * ANGLE_SCALE - dt2 = p[8 + N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward(g[7], jnp.array([g[0], g[1], g[2]]), - g[3], g[4], g[5], g[6], - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_signals, weights) - pr = highland_prior(dt1, dt2, g[7], STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) / N_SEGMENTS - return wl, pr - - def full(p, lam): - wl, pr = terms(p) - return wl + lam * pr - vg = jax.jit(jax.value_and_grad(full)) - terms_j = jax.jit(terms) - - def corr(p, W): - a1 = np.asarray(p[8:8 + N_SEGMENTS]) * ANGLE_SCALE - a2 = np.asarray(p[8 + N_SEGMENTS:]) * ANGLE_SCALE - def agg(x): - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - at = np.concatenate([agg(t1n), agg(t2n)]); af = np.concatenate([agg(a1), agg(a2)]) - return float(np.corrcoef(af, at)[0, 1]) if len(at) > 1 else np.nan - - def run_stage2(lam, log=False): - opt = optax.adam(optax.exponential_decay(0.003, 1, 0.9995)) - p = jnp.concatenate([pg, jnp.zeros(2 * N_SEGMENTS)]) - st = opt.init(p) - W, P = [], [] - for _ in range(STAGE2): - l, gr = vg(p, jnp.float32(lam)) - if log: - wl, pr = terms_j(p) - W.append(float(wl)); P.append(float(pr)) - u, st = opt.update(gr, st, p) - u = u.at[8:].multiply(0.01 / 0.003) - p = p.at[:8].set(project_unit_circle(p[:8])) - p = optax.apply_updates(p, u) - p = p.at[:8].set(project_unit_circle(p[:8])) - return p, W, P - - # Part A: decomposition history at lambda=DECOMP_LAMBDA - print(f"--- stage 2 decomposition (lambda={DECOMP_LAMBDA}) ---", flush=True) - p_dec, W2, P2 = run_stage2(DECOMP_LAMBDA, log=True) - - # Part B: sweep - print(f"\n{'lambda':>8} {'wire':>9} {'prior_w':>9} {'total':>9} {'dE':>6} " - f"{'cum/tru':>8} {'c@12.5':>7} {'c@50':>7} {'c@200':>7}") - sweep = [] - for lam in LAMBDAS: - p, _, _ = run_stage2(lam, log=False) - wl, pr = terms_j(p) - wl, pr = float(wl), float(pr) - g = np.asarray(p[:8] * SCj) - a1 = np.asarray(p[8:8 + N_SEGMENTS]); a2 = np.asarray(p[8 + N_SEGMENTS:]) - cum = np.sqrt(np.sum(a1 * ANGLE_SCALE) ** 2 + np.sum(a2 * ANGLE_SCALE) ** 2) * 1000 - row = (lam, wl, lam * pr, wl + lam * pr, g[7] - TRUTH_ENERGY, - cum / cum_truth, corr(p, 25), corr(p, 100), corr(p, 400)) - sweep.append(row) - print(f"{lam:>8.0e} {wl:>9.5f} {lam*pr:>9.5f} {wl+lam*pr:>9.5f} {g[7]-TRUTH_ENERGY:>+6.1f} " - f"{cum/cum_truth:>8.2f} {corr(p,25):>7.3f} {corr(p,100):>7.3f} {corr(p,400):>7.3f}", - flush=True) - - # ---- decomposition plot ---- - total1 = np.array(wire1) # stage-1: prior=0, loss=wire - it1 = np.arange(STAGE1) - it2 = STAGE1 + np.arange(len(W2)) - W2 = np.array(W2); P2 = np.array(P2) * DECOMP_LAMBDA # weighted prior - fig, ax = plt.subplots(1, 2, figsize=(15, 5)) - ax[0].semilogy(it1, total1, color='grey', lw=1.0, label='stage1 loss (=wire)') - ax[0].semilogy(it2, W2, color='#3d6aa6', lw=1.0, label='wire term') - ax[0].semilogy(it2, np.maximum(P2, 1e-9), color='#d9772a', lw=1.0, - label=f'prior term (x{DECOMP_LAMBDA:g})') - ax[0].semilogy(it2, W2 + P2, color='k', lw=0.8, alpha=0.6, label='total') - ax[0].axvline(STAGE1, color='crimson', ls='--', lw=1.5) - ax[0].text(STAGE1, ax[0].get_ylim()[1], ' stage 2 on', color='crimson', - va='top', fontsize=9) - ax[0].set_xlabel('iteration'); ax[0].set_ylabel('loss term'); ax[0].grid(True, alpha=0.3) - ax[0].set_title('Loss decomposition across the stage transition') - ax[0].legend(fontsize=9) - - lams = np.array([max(r[0], 1e-4) for r in sweep]) - ax[1].semilogx(lams, [r[6] for r in sweep], 'o-', label='corr@12.5mm') - ax[1].semilogx(lams, [r[7] for r in sweep], 's-', label='corr@50mm') - ax[1].semilogx(lams, [r[8] for r in sweep], '^-', label='corr@200mm') - ax[1].semilogx(lams, [r[5] for r in sweep], 'd--', color='grey', label='net defl ratio') - ax[1].axhline(1.0, color='grey', ls=':', lw=0.8) - ax[1].set_xlabel('lambda (prior weight)'); ax[1].set_ylabel('recovery') - ax[1].set_title('Prior-weight sweep'); ax[1].grid(True, alpha=0.3); ax[1].legend(fontsize=9) - fig.suptitle(f'MCS loss decomposition + prior sweep (s={SOBOLEV_S})', fontsize=13) - fig.tight_layout(rect=[0, 0, 1, 0.95]) - fn = os.path.join(OUT, 'mcs_decompose_sweep.png') - fig.savefig(fn, dpi=140, bbox_inches='tight') - print(f"\nsaved {fn}") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/depth_scan.py b/closure/mcs/depth_scan.py deleted file mode 100644 index c906f46..0000000 --- a/closure/mcs/depth_scan.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Is the MCS fine-scale resolution limited by charge diffusion (drift depth)? - -The Sobolev-order sweep (resolve_scan.py) showed the ~13 mm aggregate-angle -crossover is NOT set by the loss smoothing (reducing s overfits and does worse). -The remaining suspect is physical: transverse/longitudinal diffusion blurs the -fine track structure before it reaches the wires, and diffusion grows with drift -distance. If that is the limiter, a track near the anode (small drift, sharp) -should resolve scattering at a finer scale than one near the cathode. - -This runs the same scattering-only closure at several truth drift depths and -reports the aggregate-angle correlation vs window length + the corr=0.5 -crossover for each. - - python3 -m closure.mcs.depth_scan -""" - -import time -import os -import jax -import jax.numpy as jnp -import numpy as np - -from closure.mcs.forward import ( - mcs_cumsum_forward, generate_mcs_truth, highland_prior, build_mcs_forward, - mask_outside_volume, -) -from closure.mcs.study import ( - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, TRUTH_Y, TRUTH_Z, - TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, ANGLE_SCALE, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - run_adam, OUT_DIR, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight - - -def fit_at_depth(forward, half_ext, log_T, dedx, truth_x, weights): - """Run scattering-only closure for a truth track whose vertex x = truth_x.""" - start = jnp.array([truth_x, TRUTH_Y, TRUTH_Z], jnp.float32) - key = jax.random.PRNGKey(42) - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), start, - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - de_tm = mask_outside_volume(pos_t, de_t, half_ext) - truth_sig = forward(pos_t, de_tm) - for s in truth_sig: - jax.block_until_ready(s) - - def loss(params, lam_): - dt1 = params[:N_SEGMENTS] * ANGLE_SCALE - dt2 = params[N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward( - jnp.float32(TRUTH_ENERGY), start, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_sig, weights) - pr = highland_prior(dt1, dt2, jnp.float32(TRUTH_ENERGY), - STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + lam_ * pr / N_SEGMENTS - - lg = jax.jit(jax.value_and_grad(loss)) - best, bl = run_adam(lg, jnp.zeros(2 * N_SEGMENTS), 350, 0.01, - jnp.float32(3e-2), decay=0.99, early_stop=True) - dt1_f = np.asarray(best[:N_SEGMENTS]) * ANGLE_SCALE - dt2_f = np.asarray(best[N_SEGMENTS:]) * ANGLE_SCALE - return np.asarray(dt1_t), np.asarray(dt2_t), dt1_f, dt2_f, bl - - -def window_corr(dt1_f, dt2_f, dt1_t, dt2_t, W): - def agg(x): - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - at = np.concatenate([agg(dt1_t), agg(dt2_t)]) - af = np.concatenate([agg(dt1_f), agg(dt2_f)]) - return np.corrcoef(af, at)[0, 1] if len(at) > 1 else float('nan') - - -def crossover(Lmm, cs, thr=0.5): - for i in range(len(cs) - 1): - if cs[i] < thr <= cs[i + 1]: - t = (thr - cs[i]) / (cs[i + 1] - cs[i]) - return float(np.exp(np.log(Lmm[i]) + t * (np.log(Lmm[i+1]) - np.log(Lmm[i])))) - return None - - -def main(): - print("=" * 78) - print("MCS fine-scale resolution vs drift depth (diffusion test)") - print("=" * 78, flush=True) - - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward_raw = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - forward = jax.jit(forward_raw) - - # need weights sized to the signal shape; shapes are depth-independent - # (same detector), so build once from a probe. - probe_start = jnp.array([-100., TRUTH_Y, TRUTH_Z], jnp.float32) - pp, pde, *_ = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), probe_start, - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, jax.random.PRNGKey(0)) - t0 = time.time() - ps = forward(pp, mask_outside_volume(pp, pde, half_ext)) - for s in ps: - jax.block_until_ready(s) - print(f"compiled ({time.time()-t0:.1f}s)", flush=True) - weights = tuple(make_sobolev_weight(*ps[p].shape, s=1.5) for p in range(6)) - - # anode is at x=0, drift_direction=-1 -> drift distance = |x|. Max ~216 mm. - depths_x = [-20.0, -60.0, -120.0, -200.0] - W_report = [2, 6, 12, 25, 50, 100] - Lmm = np.array([W * STEP_SIZE_MM for W in W_report]) - - hdr = (f"{'drift_mm':>8} {'wloss':>8} | " + - " | ".join(f"{L:>5.1f}mm" for L in Lmm) + f" | {'L@0.5':>7}") - print("\n" + hdr) - print("-" * len(hdr), flush=True) - - rows = [] - for x in depths_x: - dt1_t, dt2_t, dt1_f, dt2_f, bl = fit_at_depth( - forward, half_ext, log_T, dedx, x, weights) - cs = [window_corr(dt1_f, dt2_f, dt1_t, dt2_t, W) for W in W_report] - cross = crossover(Lmm, cs) - rows.append((abs(x), cs, cross)) - print(f"{abs(x):>8.0f} {bl:>8.4f} | " + - " | ".join(f"{c:>6.3f}" for c in cs) + - f" | {(f'{cross:.1f}mm' if cross else '>50mm'):>7}", flush=True) - - print("\nInterpretation: if L@0.5 shrinks as drift -> 0, the fine-scale") - print("resolution is diffusion-limited (sharper signal near the anode).") - print("\nDone.") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/diagnose_fit.py b/closure/mcs/diagnose_fit.py deleted file mode 100644 index cd3497b..0000000 --- a/closure/mcs/diagnose_fit.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Systematic diagnosis of the JOINT MCS full fit (globals + 2N angles). - -Studies how the loss, global errors, and angle-recovery actually evolve over -steps, scanning the scattering-angle learning rate. Globals move at a gentle -fixed rate; only the angle LR is scanned. The point is to SEE whether each -setting descends smoothly (loss moving-average trending down, angle correlation -climbing) or oscillates (LR too high), instead of guessing. - - python3 -m closure.mcs.diagnose_fit -""" -import time -import jax -import jax.numpy as jnp -import numpy as np -import optax - -import closure.mcs.run as R -from closure.mcs.run import ( - build_globals_only_loss, run_optimization, project_unit_circle, - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, SCALES, ANGLE_SCALE, - TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, -) -from closure.mcs.forward import ( - generate_mcs_truth, mcs_cumsum_forward, build_mcs_forward, mask_outside_volume, - highland_prior, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p - -SCj = jnp.array(SCALES, jnp.float32) -TRUTH = dict(x=TRUTH_X, y=TRUTH_Y, z=TRUTH_Z, - th=np.degrees(TRUTH_THETA), ph=np.degrees(TRUTH_PHI), E=TRUTH_ENERGY) - - -def project_full(p): - return p.at[:8].set(project_unit_circle(p[:8])) - - -def main(): - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - fwd_j = jax.jit(forward) - - # truth (median-scattering seed 32) - key = jax.random.PRNGKey(32) - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - truth_signals = fwd_j(pos_t, mask_outside_volume(pos_t, de_t, half_ext)) - for s in truth_signals: - jax.block_until_ready(s) - weights = tuple(make_sobolev_weight(*truth_signals[p].shape, s=1.5) for p in range(6)) - t1n, t2n = np.asarray(dt1_t), np.asarray(dt2_t) - - # stage 1: lock globals - R.LAMBDA_PRIOR = 0.03 - init_globals = np.array([ - TRUTH_X + 100.0, TRUTH_Y + 100.0, TRUTH_Z - 100.0, - np.sin(TRUTH_THETA + 0.5), np.cos(TRUTH_THETA + 0.5), - np.sin(TRUTH_PHI + 0.5), np.cos(TRUTH_PHI + 0.5), - TRUTH_ENERGY + 100.0]) - loss_g = build_globals_only_loss(forward, log_T, dedx, truth_signals, weights, - dt1_t, dt2_t, half_ext) - print("locking globals (stage 1)...", flush=True) - params_g, *_ = run_optimization(loss_g, jnp.array(init_globals / SCALES, jnp.float32), - 250, 0.015, 'stage1', project_fn=project_unit_circle) - - # joint full loss - def full_loss(p): - g = p[:8] * SCj - dt1 = p[8:8 + N_SEGMENTS] * ANGLE_SCALE - dt2 = p[8 + N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward(g[7], jnp.array([g[0], g[1], g[2]]), - g[3], g[4], g[5], g[6], - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_signals, weights) - pr = highland_prior(dt1, dt2, g[7], STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + R.LAMBDA_PRIOR * pr / N_SEGMENTS - - vg = jax.jit(jax.value_and_grad(full_loss)) - - def angle_corr(p, W): - a1 = np.asarray(p[8:8 + N_SEGMENTS]) * ANGLE_SCALE - a2 = np.asarray(p[8 + N_SEGMENTS:]) * ANGLE_SCALE - def agg(x): - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - at = np.concatenate([agg(t1n), agg(t2n)]); af = np.concatenate([agg(a1), agg(a2)]) - return np.corrcoef(af, at)[0, 1] if len(at) > 1 else float('nan') - - def gstate(p): - g = np.asarray(p[:8] * SCj) - a1 = np.asarray(p[8:8 + N_SEGMENTS]) * ANGLE_SCALE - a2 = np.asarray(p[8 + N_SEGMENTS:]) * ANGLE_SCALE - return dict(dx=g[0]-TRUTH['x'], dE=g[7]-TRUTH['E'], - dth=np.degrees(np.arctan2(g[3], g[4]))-TRUTH['th'], - dph=np.degrees(np.arctan2(g[5], g[6]))-TRUTH['ph'], - arms=np.sqrt(np.mean(a1**2 + a2**2))*1000) - - GLOBAL_LR = 0.003 - DECAY = 0.9995 - N_STEPS = 1000 - print(f"\nJOINT fit diagnosis: global_lr={GLOBAL_LR}, decay={DECAY}, " - f"truth angle RMS={np.sqrt(np.mean(t1n**2+t2n**2))*1000:.2f} mrad") - - for angle_lr in [0.01, 0.02, 0.04]: - opt = optax.adam(optax.exponential_decay(angle_lr, 1, DECAY)) - p = jnp.concatenate([params_g, jnp.zeros(2 * N_SEGMENTS)]) - state = opt.init(p) - losses = [] - print(f"\n=== angle_lr={angle_lr} ===") - print(f"{'step':>5} {'loss_ma50':>9} {'Δma':>8} {'dE':>7} {'dphi':>6} " - f"{'a_rms':>6} {'c@12mm':>7} {'c@50mm':>7}") - prev_ma = None - for step in range(N_STEPS): - loss, grad = vg(p) - losses.append(float(loss)) - upd, state = opt.update(grad, state, p) - upd = upd.at[:8].multiply(GLOBAL_LR / angle_lr) # globals move slower - p = optax.apply_updates(p, upd) - p = project_full(p) - if step % 100 == 0 or step == N_STEPS - 1: - ma = float(np.mean(losses[-50:])) - dma = (ma - prev_ma) if prev_ma is not None else 0.0 - prev_ma = ma - gs = gstate(p) - print(f"{step:>5} {ma:>9.4f} {dma:>+8.4f} {gs['dE']:>7.1f} " - f"{gs['dph']:>+6.2f} {gs['arms']:>6.2f} " - f"{angle_corr(p, 25):>7.3f} {angle_corr(p, 100):>7.3f}", flush=True) - - print("\nDone.") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/diagnose_rise.py b/closure/mcs/diagnose_rise.py deleted file mode 100644 index 849f5af..0000000 --- a/closure/mcs/diagnose_rise.py +++ /dev/null @@ -1,109 +0,0 @@ -"""Why does the loss dip (~step 150) then rise? Decompose wire vs prior + globals. - -Logs, per step, the wire-data term and the Highland-prior term separately, plus -the global errors and the angle RMS, through the dip-and-rise region. Pinpoints -whether the rise is the wire fit worsening (angles/energy transient) or just the -prior penalty growing as angles leave zero. -""" -import jax -import jax.numpy as jnp -import numpy as np -import optax - -import closure.mcs.run as R -from closure.mcs.run import ( - build_globals_only_loss, run_optimization, project_unit_circle, - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, SCALES, ANGLE_SCALE, - TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, -) -from closure.mcs.forward import ( - generate_mcs_truth, mcs_cumsum_forward, build_mcs_forward, mask_outside_volume, - highland_prior, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p - -SCj = jnp.array(SCALES, jnp.float32) - - -def main(): - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - fwd_j = jax.jit(forward) - - key = jax.random.PRNGKey(32) - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - truth_signals = fwd_j(pos_t, mask_outside_volume(pos_t, de_t, half_ext)) - for s in truth_signals: - jax.block_until_ready(s) - weights = tuple(make_sobolev_weight(*truth_signals[p].shape, s=1.5) for p in range(6)) - t1n, t2n = np.asarray(dt1_t), np.asarray(dt2_t) - - R.LAMBDA_PRIOR = 0.03 - init_g = np.array([TRUTH_X + 100, TRUTH_Y + 100, TRUTH_Z - 100, - np.sin(TRUTH_THETA + 0.5), np.cos(TRUTH_THETA + 0.5), - np.sin(TRUTH_PHI + 0.5), np.cos(TRUTH_PHI + 0.5), - TRUTH_ENERGY + 100]) - loss_g = build_globals_only_loss(forward, log_T, dedx, truth_signals, weights, - dt1_t, dt2_t, half_ext) - params_g, *_ = run_optimization(loss_g, jnp.array(init_g / SCALES, jnp.float32), - 250, 0.015, 'stage1', project_fn=project_unit_circle) - - def terms(p): - """Return (wire_term, prior_term) separately.""" - g = p[:8] * SCj - dt1 = p[8:8 + N_SEGMENTS] * ANGLE_SCALE - dt2 = p[8 + N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward(g[7], jnp.array([g[0], g[1], g[2]]), - g[3], g[4], g[5], g[6], - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_signals, weights) - pr = R.LAMBDA_PRIOR * highland_prior(dt1, dt2, g[7], STEP_SIZE_CM, - N_SEGMENTS, log_T, dedx) / N_SEGMENTS - return wl, pr - - full = lambda p: sum(terms(p)) - vg = jax.jit(jax.value_and_grad(full)) - terms_j = jax.jit(terms) - - ANGLE_LR, GLOBAL_LR, DECAY = 0.01, 0.003, 0.9995 - opt = optax.adam(optax.exponential_decay(ANGLE_LR, 1, DECAY)) - p = jnp.concatenate([params_g, jnp.zeros(2 * N_SEGMENTS)]) - state = opt.init(p) - - print(f"\n{'step':>4} {'wire':>8} {'prior':>8} {'total':>8} {'dE':>6} {'dphi':>6} " - f"{'a_rms':>6} {'|grad_g|':>8} {'|grad_a|':>8}") - for step in range(500): - (loss, grad) = vg(p) - if step % 20 == 0 or step in (5, 10, 150, 175): - wl, pr = terms_j(p) - g = np.asarray(p[:8] * SCj) - a1 = np.asarray(p[8:8+N_SEGMENTS]) * ANGLE_SCALE - a2 = np.asarray(p[8+N_SEGMENTS:]) * ANGLE_SCALE - gg = float(jnp.linalg.norm(grad[:8])) - ga = float(jnp.linalg.norm(grad[8:])) - print(f"{step:>4} {float(wl):>8.5f} {float(pr):>8.5f} {float(loss):>8.5f} " - f"{g[7]-TRUTH_ENERGY:>+6.1f} " - f"{np.degrees(np.arctan2(g[5],g[6]))-np.degrees(TRUTH_PHI):>+6.2f} " - f"{np.sqrt(np.mean(a1**2+a2**2))*1000:>6.2f} {gg:>8.4f} {ga:>8.4f}", - flush=True) - upd, state = opt.update(grad, state, p) - upd = upd.at[:8].multiply(GLOBAL_LR / ANGLE_LR) - p = optax.apply_updates(p, upd) - p = p.at[:8].set(project_unit_circle(p[:8])) - print("\nDone.") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/long_fit.py b/closure/mcs/long_fit.py deleted file mode 100644 index b4e2308..0000000 --- a/closure/mcs/long_fit.py +++ /dev/null @@ -1,121 +0,0 @@ -"""Is the wire MCS fine-angle floor optimization-limited? Run long, log corr vs step. - -The oracle test showed the from-zero fit stops at wire-loss ~0.014 while the -TRUTH angles give loss 0.0 — i.e. a strictly better, perfectly-correlated -solution exists that the 350-step fit does not reach. If the fine-scale -correlation keeps climbing as we drive the loss lower with more steps, the -floor is optimization-limited (we CAN resolve finer), not an information limit. - -Logs wire-loss and aggregate-angle correlation at 3 / 12.5 / 25 mm vs step, for -a lightly-regularized (lam=1e-3, near data-only) and a moderately-regularized -(lam=3e-2) long run. - - python3 -m closure.mcs.long_fit -""" - -import time -import jax -import jax.numpy as jnp -import numpy as np -import optax - -from closure.mcs.forward import ( - mcs_cumsum_forward, generate_mcs_truth, highland_prior, build_mcs_forward, - mask_outside_volume, -) -from closure.mcs.study import ( - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, TRUTH_X, TRUTH_Y, TRUTH_Z, - TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, ANGLE_SCALE, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight - - -def wcorr(f1, f2, t1, t2, W): - def agg(x): - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - at = np.concatenate([agg(t1), agg(t2)]) - af = np.concatenate([agg(f1), agg(f2)]) - return np.corrcoef(af, at)[0, 1] if len(at) > 1 else float('nan') - - -def main(): - print("=" * 72) - print("MCS wire fine-angle: is the floor optimization-limited? (long fit)") - print("=" * 72, flush=True) - - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - key = jax.random.PRNGKey(42) - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - de_tm = mask_outside_volume(pos_t, de_t, half_ext) - t0 = time.time() - truth_sig = jax.jit(forward)(pos_t, de_tm) - for s in truth_sig: - jax.block_until_ready(s) - print(f"compiled ({time.time()-t0:.1f}s)", flush=True) - weights = tuple(make_sobolev_weight(*truth_sig[p].shape, s=1.5) for p in range(6)) - start = jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32) - t1, t2 = np.asarray(dt1_t), np.asarray(dt2_t) - - def make_lg(lam): - def loss(params): - dt1 = params[:N_SEGMENTS] * ANGLE_SCALE - dt2 = params[N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward( - jnp.float32(TRUTH_ENERGY), start, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_sig, weights) - pr = highland_prior(dt1, dt2, jnp.float32(TRUTH_ENERGY), - STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + lam * pr / N_SEGMENTS - return jax.jit(jax.value_and_grad(loss)) - - cum_t = np.sqrt(np.sum(t1) ** 2 + np.sum(t2) ** 2) - N_STEPS = 9000 - checkpoints = [350, 1000, 2500, 4000, 6000, 8000, 8999] - for lam in [3e-2]: - lg = make_lg(lam) - opt = optax.adam(optax.exponential_decay(0.02, 1, 0.99975)) - params = jnp.zeros(2 * N_SEGMENTS) - state = opt.init(params) - print(f"\n--- lam={lam:.0e} ---") - print(f"{'step':>5} {'wire+pri':>9} {'c@3mm':>7} {'c@6mm':>7} {'c@12.5':>7} " - f"{'c@25mm':>7} {'cum_ratio':>9}", flush=True) - for step in range(N_STEPS): - l, g = lg(params) - upd, state = opt.update(g, state, params) - params = optax.apply_updates(params, upd) - if step in checkpoints: - f1 = np.asarray(params[:N_SEGMENTS]) * ANGLE_SCALE - f2 = np.asarray(params[N_SEGMENTS:]) * ANGLE_SCALE - cum_f = np.sqrt(np.sum(f1) ** 2 + np.sum(f2) ** 2) - print(f"{step:>5} {float(l):>9.5f} " - f"{wcorr(f1,f2,t1,t2,6):>7.3f} " - f"{wcorr(f1,f2,t1,t2,12):>7.3f} " - f"{wcorr(f1,f2,t1,t2,25):>7.3f} " - f"{wcorr(f1,f2,t1,t2,50):>7.3f} " - f"{cum_f/cum_t:>9.3f}", flush=True) - - print("\nReading: if c@12.5/c@25 keep climbing as wire+pri falls, the floor is") - print("optimization-limited and finer scales are recoverable with more steps.") - print("\nDone.") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/oracle_test.py b/closure/mcs/oracle_test.py deleted file mode 100644 index bc57c55..0000000 --- a/closure/mcs/oracle_test.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Information limit vs optimization limit for the wire MCS fine-angle floor. - -The ~13 mm aggregate-angle crossover is invariant to loss order, drift depth and -parameterization, suggesting it is an information limit of the 3-plane wire -forward rather than an optimization failure. This settles it decisively: - - * Init the scattering angles AT TRUTH (the global-truth point). - * Run the same closure. - * If the fine-window correlation DEGRADES from 1.0 toward the ~0.5@13 mm floor, - the wire signal cannot hold the fine angles -> INFORMATION limit (the loss - has flat/degenerate directions at fine scale). - * If it STAYS ~1.0, the from-zero fit was merely optimization-limited. - -Also reports, as an even cleaner probe, the loss at truth vs the loss the -from-zero fit reaches: if from-zero reaches a LOWER loss than truth while having -worse angles, the forward is provably degenerate at fine scale. - - python3 -m closure.mcs.oracle_test -""" - -import time -import jax -import jax.numpy as jnp -import numpy as np - -from closure.mcs.forward import ( - mcs_cumsum_forward, generate_mcs_truth, highland_prior, build_mcs_forward, - mask_outside_volume, -) -from closure.mcs.study import ( - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, TRUTH_X, TRUTH_Y, TRUTH_Z, - TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, ANGLE_SCALE, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - run_adam, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight - - -def wcorr(f1, f2, t1, t2, W): - def agg(x): - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - at = np.concatenate([agg(t1), agg(t2)]) - af = np.concatenate([agg(f1), agg(f2)]) - return np.corrcoef(af, at)[0, 1] if len(at) > 1 else float('nan') - - -def main(): - print("=" * 70) - print("MCS wire fine-angle: information limit vs optimization limit") - print("=" * 70, flush=True) - - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - key = jax.random.PRNGKey(42) - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - de_tm = mask_outside_volume(pos_t, de_t, half_ext) - t0 = time.time() - truth_sig = jax.jit(forward)(pos_t, de_tm) - for s in truth_sig: - jax.block_until_ready(s) - print(f"compiled ({time.time()-t0:.1f}s)", flush=True) - weights = tuple(make_sobolev_weight(*truth_sig[p].shape, s=1.5) for p in range(6)) - start = jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32) - t1, t2 = np.asarray(dt1_t), np.asarray(dt2_t) - - def loss(params, lam_): - dt1 = params[:N_SEGMENTS] * ANGLE_SCALE - dt2 = params[N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward( - jnp.float32(TRUTH_ENERGY), start, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_sig, weights) - pr = highland_prior(dt1, dt2, jnp.float32(TRUTH_ENERGY), - STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + lam_ * pr / N_SEGMENTS - - lg = jax.jit(jax.value_and_grad(loss)) - - # truth params (normalized) and its loss - truth_params = jnp.concatenate([ - jnp.asarray(t1 / ANGLE_SCALE, jnp.float32), - jnp.asarray(t2 / ANGLE_SCALE, jnp.float32)]) - truth_loss = float(lg(truth_params, jnp.float32(0.0))[0]) # wire-only at truth - print(f"\nwire loss at TRUTH angles = {truth_loss:.6f}") - - Wlist = [6, 25, 50, 100] # 3, 12.5, 25, 50 mm - - # 1) from-zero fit - z, _ = run_adam(lg, jnp.zeros(2 * N_SEGMENTS), 350, 0.01, jnp.float32(3e-2), - decay=0.99, early_stop=True) - z_loss = float(lg(z, jnp.float32(0.0))[0]) - z1 = np.asarray(z[:N_SEGMENTS]) * ANGLE_SCALE - z2 = np.asarray(z[N_SEGMENTS:]) * ANGLE_SCALE - print(f"wire loss reached from ZERO init = {z_loss:.6f}") - - # 2) oracle fit: init AT truth, run the same closure (no prior, pure data, - # to test whether the DATA term alone holds the fine angles). - def loss_data(params, lam_): - dt1 = params[:N_SEGMENTS] * ANGLE_SCALE - dt2 = params[N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward( - jnp.float32(TRUTH_ENERGY), start, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - return sobolev_loss_geomean_log1p(forward(pos, de), truth_sig, weights) - lg_data = jax.jit(jax.value_and_grad(loss_data)) - orc, _ = run_adam(lg_data, truth_params, 350, 0.01, jnp.float32(0.0), - decay=1.0, early_stop=False) - o1 = np.asarray(orc[:N_SEGMENTS]) * ANGLE_SCALE - o2 = np.asarray(orc[N_SEGMENTS:]) * ANGLE_SCALE - orc_loss = float(lg(orc, jnp.float32(0.0))[0]) - print(f"wire loss after ORACLE drift = {orc_loss:.6f}") - - print(f"\n{'window':>8} | {'from-zero':>9} | {'oracle(truth-init,data-only)':>28}") - print("-" * 54) - for W in Wlist: - cz = wcorr(z1, z2, t1, t2, W) - co = wcorr(o1, o2, t1, t2, W) - print(f"{W*STEP_SIZE_MM:>6.1f}mm | {cz:>9.3f} | {co:>28.3f}", flush=True) - - print("\nReading: if the data-only oracle, STARTING at truth, drifts the fine") - print("windows well below 1.0 (toward the from-zero floor) at NO higher wire") - print("loss, the wire forward is degenerate at fine scale -> information limit.") - print("\nDone.") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/render_3d.py b/closure/mcs/render_3d.py deleted file mode 100644 index 0b775d5..0000000 --- a/closure/mcs/render_3d.py +++ /dev/null @@ -1,162 +0,0 @@ -"""3D event display of the MCS closure: truth vs reconstructed track. - -Runs the staged closure (s=SOBOLEV_S=1.0), then visualizes in 3D: - (top) the truth and reconstructed muon tracks overlaid, two view angles - -> confirms the globals + overall trajectory are right. - (bottom) the TRANSVERSE deviation from the straight start->end axis, in the - two perpendicular directions, vs arc length, truth vs reconstruction - -> this is the scattering itself; confirms the recon follows the - coarse bend (and shows the unresolved fine wiggle). - - python3 -m closure.mcs.render_3d -""" -import os -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt -from mpl_toolkits.mplot3d import Axes3D # noqa: F401 - -from closure.mcs.run import ( - build_globals_only_loss, build_full_loss, run_optimization, project_unit_circle, - N_SEGMENTS, STEP_SIZE_MM, SCALES, ANGLE_SCALE, SOBOLEV_S, - TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, -) -from closure.mcs.forward import ( - generate_mcs_truth, mcs_cumsum_forward, build_mcs_forward, mask_outside_volume, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import make_sobolev_weight - -OUT = os.path.dirname(os.path.abspath(__file__)) -SCj = jnp.array(SCALES, jnp.float32) - - -def perp_basis(d): - d = d / np.linalg.norm(d) - sign = 1.0 if d[2] >= 0 else -1.0 - a = -1.0 / (sign + d[2]); b = d[0] * d[1] * a - e1 = np.array([1 + sign * d[0] ** 2 * a, sign * b, -sign * d[0]]) - e2 = np.array([b, sign + d[1] ** 2 * a, -d[1]]) - return e1 / np.linalg.norm(e1), e2 / np.linalg.norm(e2) - - -def transverse(pos, p0, axis, e1, e2): - rel = pos - p0 - along = rel @ axis - dev = rel - np.outer(along, axis) - return along, dev @ e1, dev @ e2 - - -def corr(a1, a2, t1, t2, W): - def agg(x): - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - at = np.concatenate([agg(t1), agg(t2)]); af = np.concatenate([agg(a1), agg(a2)]) - return float(np.corrcoef(af, at)[0, 1]) if len(at) > 1 else np.nan - - -def main(): - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - fwd_j = jax.jit(forward) - - key = jax.random.PRNGKey(32) # median-scattering realization - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - truth_signals = fwd_j(pos_t, mask_outside_volume(pos_t, de_t, half_ext)) - for s in truth_signals: - jax.block_until_ready(s) - weights = tuple(make_sobolev_weight(*truth_signals[p].shape, s=SOBOLEV_S) for p in range(6)) - print(f"using Sobolev s={SOBOLEV_S}", flush=True) - - import closure.mcs.run as R - R.LAMBDA_PRIOR = 1e-3 # optimal at s=1.0 (decompose_sweep.py); was 0.03 - init_g = np.array([TRUTH_X + 100, TRUTH_Y + 100, TRUTH_Z - 100, - np.sin(TRUTH_THETA + 0.5), np.cos(TRUTH_THETA + 0.5), - np.sin(TRUTH_PHI + 0.5), np.cos(TRUTH_PHI + 0.5), - TRUTH_ENERGY + 100]) - print("--- stage 1: globals-only ---", flush=True) - loss_g = build_globals_only_loss(forward, log_T, dedx, truth_signals, weights, - dt1_t, dt2_t, half_ext) - params_g, *_ = run_optimization(loss_g, jnp.array(init_g / SCALES, jnp.float32), - 250, 0.015, 'stage1', project_fn=project_unit_circle) - print("--- stage 2: joint, s=1.0, 1500 steps ---", flush=True) - loss_f = build_full_loss(forward, log_T, dedx, truth_signals, weights, half_ext) - init_full = jnp.concatenate([params_g, jnp.zeros(2 * N_SEGMENTS)]) - params, *_ = run_optimization( - loss_f, init_full, 1500, 0.003, 'stage2', - project_fn=lambda p: p.at[:8].set(project_unit_circle(p[:8])), - lr_scat=0.01, decay=0.9995, early_stop=False) - - # reconstructed track positions - g = params[:8] * SCj - dt1 = params[8:8 + N_SEGMENTS] * ANGLE_SCALE - dt2 = params[8 + N_SEGMENTS:] * ANGLE_SCALE - pos_f, _ = mcs_cumsum_forward(g[7], jnp.array([g[0], g[1], g[2]]), - g[3], g[4], g[5], g[6], - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - P = np.asarray(pos_t) / 10.0 # mm -> cm - Q = np.asarray(pos_f) / 10.0 - gp = np.asarray(g) - a1, a2 = np.asarray(dt1), np.asarray(dt2) - t1, t2 = np.asarray(dt1_t), np.asarray(dt2_t) - print(f"\nrecon globals: x={gp[0]:.1f} y={gp[1]:.1f} z={gp[2]:.1f} " - f"th={np.degrees(np.arctan2(gp[3],gp[4])):.1f} ph={np.degrees(np.arctan2(gp[5],gp[6])):.1f} " - f"E={gp[7]:.1f}") - cum_t = np.sqrt(np.sum(t1)**2 + np.sum(t2)**2) * 1000 - cum_a = np.sqrt(np.sum(a1)**2 + np.sum(a2)**2) * 1000 - print(f"scattering: net deflection truth={cum_t:.1f} mrad, recon={cum_a:.1f} mrad") - print(f"angle corr @12.5mm={corr(a1,a2,t1,t2,25):.3f}, @50mm={corr(a1,a2,t1,t2,100):.3f}, " - f"@200mm={corr(a1,a2,t1,t2,400):.3f}") - - # transverse deviation in the TRUTH start->end frame (shared reference) - p0 = P[0]; axis = P[-1] - P[0]; axis /= np.linalg.norm(axis) - e1, e2 = perp_basis(axis) - sT, d1T, d2T = transverse(P, p0, axis, e1, e2) - sQ, d1Q, d2Q = transverse(Q, p0, axis, e1, e2) - traj_rms = np.sqrt(np.mean(np.sum((P - Q) ** 2, axis=1))) * 10 # cm->mm - print(f"3D track residual (truth vs recon) = {traj_rms:.2f} mm RMS") - - # ---------------- figure ---------------- - fig = plt.figure(figsize=(16, 9)) - for k, azim in enumerate([-60, 30]): - ax = fig.add_subplot(2, 2, k + 1, projection='3d') - ax.plot(P[:, 0], P[:, 1], P[:, 2], color='#3d6aa6', lw=1.6, label='truth') - ax.plot(Q[:, 0], Q[:, 1], Q[:, 2], color='#d9772a', lw=1.2, ls='--', label='reco') - ax.scatter(*P[0], color='k', s=30) - ax.set_xlabel('x (cm)'); ax.set_ylabel('y (cm)'); ax.set_zlabel('z (cm)') - ax.view_init(elev=18, azim=azim) - ax.set_title(f'3D track (azim={azim}°)') - if k == 0: - ax.legend(loc='upper left', fontsize=10) - for j, (dT, dQ, lbl) in enumerate([(d1T, d1Q, 'transverse-1'), (d2T, d2Q, 'transverse-2')]): - ax = fig.add_subplot(2, 2, 3 + j) - ax.plot(sT, dT * 10, color='#3d6aa6', lw=1.2, label='truth') - ax.plot(sQ, dQ * 10, color='#d9772a', lw=1.2, label='reco') - ax.set_xlabel('distance along track (cm)') - ax.set_ylabel(f'{lbl} deviation (mm)') - ax.set_title(f'Scattering: {lbl} deviation from straight line') - ax.grid(True, alpha=0.3); ax.legend(fontsize=9) - fig.suptitle(f'MCS closure 3D — truth vs reconstructed (s={SOBOLEV_S}); ' - f'net deflection {cum_t:.0f}->{cum_a:.0f} mrad, ' - f'3D residual {traj_rms:.1f} mm', fontsize=13) - fig.tight_layout(rect=[0, 0, 1, 0.96]) - fn = os.path.join(OUT, 'mcs_closure_3d.png') - fig.savefig(fn, dpi=140, bbox_inches='tight') - print(f"saved {fn}") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/render_history.py b/closure/mcs/render_history.py deleted file mode 100644 index 1a95961..0000000 --- a/closure/mcs/render_history.py +++ /dev/null @@ -1,165 +0,0 @@ -"""Plot the MCS closure optimization history: loss + parameters vs iteration. - -Logs, per iteration across BOTH stages (globals-only warm-up, then joint), the -loss and every global parameter (x, y, z, theta, phi, E) plus the scattering -angle RMS. A vertical line marks where stage 2 (joint) turns on. Truth values -are dashed. s = SOBOLEV_S (=1.0). - - python3 -m closure.mcs.render_history -""" -import os -import jax -import jax.numpy as jnp -import numpy as np -import optax -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt - -import closure.mcs.run as R -from closure.mcs.run import ( - build_globals_only_loss, build_full_loss, project_unit_circle, - N_SEGMENTS, STEP_SIZE_MM, SCALES, ANGLE_SCALE, SOBOLEV_S, - TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, -) -from closure.mcs.forward import ( - generate_mcs_truth, build_mcs_forward, mask_outside_volume, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import make_sobolev_weight - -OUT = os.path.dirname(os.path.abspath(__file__)) -SCj = jnp.array(SCALES, jnp.float32) -STAGE1_STEPS, STAGE2_STEPS = 250, 800 - - -def globals_phys(p8): - g = np.asarray(p8) * SCALES[:8] - return dict(x=g[0], y=g[1], z=g[2], - th=np.degrees(np.arctan2(g[3], g[4])), - ph=np.degrees(np.arctan2(g[5], g[6])), E=g[7]) - - -def run_stage(loss_fn, init, n_steps, lr, lr_scat, decay, has_angles): - """Manual Adam loop logging per-step loss, globals, angle RMS.""" - sched = optax.exponential_decay(lr, 1, decay) if decay < 1 else lr - opt = optax.adam(sched) - p = init - state = opt.init(p) - vg = jax.jit(jax.value_and_grad(loss_fn)) - L, G, A = [], [], [] - for _ in range(n_steps): - loss, grad = vg(p) - L.append(float(loss)) - G.append(globals_phys(p[:8])) - if has_angles: - a1 = np.asarray(p[8:8 + N_SEGMENTS]) * ANGLE_SCALE - a2 = np.asarray(p[8 + N_SEGMENTS:]) * ANGLE_SCALE - A.append(np.sqrt(np.mean(a1 ** 2 + a2 ** 2)) * 1000) - else: - A.append(np.nan) - upd, state = opt.update(grad, state, p) - if lr_scat is not None: - upd = upd.at[8:].multiply(lr_scat / lr) - p = optax.apply_updates(p, upd) - p = p.at[:8].set(project_unit_circle(p[:8])) - return p, L, G, A - - -def main(): - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - fwd_j = jax.jit(forward) - - key = jax.random.PRNGKey(32) - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - truth_signals = fwd_j(pos_t, mask_outside_volume(pos_t, de_t, half_ext)) - for s in truth_signals: - jax.block_until_ready(s) - weights = tuple(make_sobolev_weight(*truth_signals[p].shape, s=SOBOLEV_S) for p in range(6)) - truth_arms = float(np.sqrt(np.mean(np.asarray(dt1_t) ** 2 + np.asarray(dt2_t) ** 2)) * 1000) - - R.LAMBDA_PRIOR = 1e-3 # optimal at s=1.0 (decompose_sweep.py); was 0.03 - init_g = np.array([TRUTH_X + 100, TRUTH_Y + 100, TRUTH_Z - 100, - np.sin(TRUTH_THETA + 0.5), np.cos(TRUTH_THETA + 0.5), - np.sin(TRUTH_PHI + 0.5), np.cos(TRUTH_PHI + 0.5), - TRUTH_ENERGY + 100]) - - print("--- stage 1: globals-only ---", flush=True) - loss_g = build_globals_only_loss(forward, log_T, dedx, truth_signals, weights, - dt1_t, dt2_t, half_ext) - p1, L1, G1, A1 = run_stage(loss_g, jnp.array(init_g / SCALES, jnp.float32), - STAGE1_STEPS, 0.015, None, 1.0, has_angles=False) - - print("--- stage 2: joint ---", flush=True) - loss_f = build_full_loss(forward, log_T, dedx, truth_signals, weights, half_ext) - init2 = jnp.concatenate([p1, jnp.zeros(2 * N_SEGMENTS)]) - p2, L2, G2, A2 = run_stage(loss_f, init2, STAGE2_STEPS, 0.003, 0.01, 0.9995, - has_angles=True) - - # concatenate (continuous iteration axis); stage-2 begins at STAGE1_STEPS - loss = np.array(L1 + L2) - G = G1 + G2 - arms = np.array(A1 + A2) - it = np.arange(len(loss)) - t2 = STAGE1_STEPS - gf = globals_phys(p2[:8]) - print(f"\nfinal globals: x={gf['x']:.1f} y={gf['y']:.1f} z={gf['z']:.1f} " - f"th={gf['th']:.1f} ph={gf['ph']:.1f} E={gf['E']:.1f}") - - truth = dict(x=TRUTH_X, y=TRUTH_Y, z=TRUTH_Z, - th=np.degrees(TRUTH_THETA), ph=np.degrees(TRUTH_PHI), E=TRUTH_ENERGY) - - fig, axes = plt.subplots(2, 4, figsize=(20, 8)) - def vline(ax): - ax.axvline(t2, color='crimson', ls='--', lw=1.5) - - ax = axes[0, 0] - ax.semilogy(it, loss, color='#3d6aa6', lw=0.8); vline(ax) - ax.set_title('loss'); ax.set_xlabel('iteration'); ax.grid(True, alpha=0.3) - ax.text(t2, ax.get_ylim()[1], ' stage 2 on', color='crimson', va='top', fontsize=9) - - panels = [('x', 'x (mm)'), ('y', 'y (mm)'), ('z', 'z (mm)'), - ('th', 'theta (deg)'), ('ph', 'phi (deg)'), ('E', 'energy (MeV)')] - pos = [(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)] - for (kkey, lbl), (r, c) in zip(panels, pos): - ax = axes[r, c] - ax.plot(it, [g[kkey] for g in G], color='#3d6aa6', lw=1.1) - ax.axhline(truth[kkey], color='green', ls=':', lw=1.5, label='truth') - vline(ax) - ax.set_title(lbl); ax.set_xlabel('iteration'); ax.grid(True, alpha=0.3) - ax.legend(fontsize=8) - - ax = axes[1, 3] - ax.plot(it, arms, color='#8e5572', lw=1.1) - ax.axhline(truth_arms, color='green', ls=':', lw=1.5, label='truth') - vline(ax) - ax.set_title('scattering angle RMS (mrad)'); ax.set_xlabel('iteration') - ax.grid(True, alpha=0.3); ax.legend(fontsize=8) - ax.text(t2, ax.get_ylim()[1], ' angles freed (init 0)', color='crimson', - va='top', fontsize=8) - - fig.suptitle(f'MCS closure optimization history (s={SOBOLEV_S}); ' - f'red dashed = stage 2 (joint) turns on at iter {t2}; ' - f'green dotted = truth', fontsize=13) - fig.tight_layout(rect=[0, 0, 1, 0.96]) - fn = os.path.join(OUT, 'mcs_closure_history.png') - fig.savefig(fn, dpi=140, bbox_inches='tight') - np.savez(os.path.join(OUT, 'mcs_closure_history.npz'), - loss=loss, arms=arms, stage2_start=t2, - **{k: np.array([g[k] for g in G]) for k in truth}) - print(f"saved {fn}") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/resolve_scan.py b/closure/mcs/resolve_scan.py deleted file mode 100644 index 4f58d2f..0000000 --- a/closure/mcs/resolve_scan.py +++ /dev/null @@ -1,147 +0,0 @@ -"""Can a less-smoothing loss resolve MCS scattering at a finer scale? - -The Sobolev weight 1/(k^2+eps)^s suppresses high spatial frequencies as -~k^{-2s}. At s=1.5 the loss is dominated by the coarse trajectory and barely -sees the fine kinks that carry small-scale scattering information — that is what -caps the aggregate-angle crossover at ~13 mm (window_scan.py). - -In scattering-only mode the globals are fixed at truth, so there is no coarse -misalignment to protect: we can use a smaller s (retaining high-frequency -content) to sharpen the fine-scale angle recovery. This sweeps s and reports -the aggregate-angle correlation as a function of window length for each, so we -can see the crossover move. - - python3 -m closure.mcs.resolve_scan -""" - -import time -import os -import jax -import jax.numpy as jnp -import numpy as np - -from closure.mcs.forward import ( - mcs_cumsum_forward, generate_mcs_truth, highland_prior, build_mcs_forward, - mask_outside_volume, -) -from closure.mcs.study import ( - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, TRUTH_X, TRUTH_Y, TRUTH_Z, - TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, ANGLE_SCALE, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - run_adam, OUT_DIR, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight - - -def window_corr(dt1_f, dt2_f, dt1_t, dt2_t, W): - def agg(x): - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - at = np.concatenate([agg(dt1_t), agg(dt2_t)]) - af = np.concatenate([agg(dt1_f), agg(dt2_f)]) - if len(at) < 2: - return float('nan'), float('nan') - corr = np.corrcoef(af, at)[0, 1] - rms_ratio = np.sqrt(np.mean(af ** 2)) / (np.sqrt(np.mean(at ** 2)) + 1e-12) - return corr, rms_ratio - - -def main(): - print("=" * 78) - print("MCS fine-scale resolution vs Sobolev order s (scattering-only)") - print("=" * 78, flush=True) - - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - key = jax.random.PRNGKey(42) - pos_truth, de_truth, dt1_truth, dt2_truth = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - de_truth_m = mask_outside_volume(pos_truth, de_truth, half_ext) - t0 = time.time() - truth_signals = jax.jit(forward)(pos_truth, de_truth_m) - for s in truth_signals: - jax.block_until_ready(s) - print(f"truth signals compiled ({time.time()-t0:.1f}s)", flush=True) - - truth_start = jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32) - dt1_t, dt2_t = np.asarray(dt1_truth), np.asarray(dt2_truth) - - # windows to report (segments) -> mm - W_report = [2, 6, 12, 25, 50, 100] - s_list = [1.5, 1.0, 0.5, 0.25] - # lower s sees more high-freq -> use smaller LR and a stronger prior to - # keep the now-sharper-but-noisier gradient from injecting spurious wiggle. - cfg = {1.5: (0.01, 3e-2), 1.0: (0.01, 3e-2), - 0.5: (0.008, 1e-1), 0.25: (0.006, 3e-1)} - - print(f"\nwindow lengths (mm): " + - ", ".join(f"{W*STEP_SIZE_MM:.1f}" for W in W_report)) - hdr = f"{'s':>5} {'lr':>6} {'lam':>6} {'wloss':>8} | " + \ - " | ".join(f"{W*STEP_SIZE_MM:>4.1f}mm" for W in W_report) - print("\n" + hdr) - print("-" * len(hdr), flush=True) - - curves = {} - for s in s_list: - weights = tuple(make_sobolev_weight(*truth_signals[p].shape, s=s) - for p in range(6)) - lr, lam = cfg[s] - - def loss(params, lam_): - dt1 = params[:N_SEGMENTS] * ANGLE_SCALE - dt2 = params[N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward( - jnp.float32(TRUTH_ENERGY), truth_start, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_signals, weights) - pr = highland_prior(dt1, dt2, jnp.float32(TRUTH_ENERGY), - STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + lam_ * pr / N_SEGMENTS - - lg = jax.jit(jax.value_and_grad(loss)) - init = jnp.zeros(2 * N_SEGMENTS) - best, bl = run_adam(lg, init, 400, lr, jnp.float32(lam), - decay=0.99, early_stop=True) - dt1_f = np.asarray(best[:N_SEGMENTS]) * ANGLE_SCALE - dt2_f = np.asarray(best[N_SEGMENTS:]) * ANGLE_SCALE - - cs = [] - for W in W_report: - c, _ = window_corr(dt1_f, dt2_f, dt1_t, dt2_t, W) - cs.append(c) - curves[s] = cs - print(f"{s:>5.2f} {lr:>6.3f} {lam:>6.0e} {bl:>8.4f} | " + - " | ".join(f"{c:>6.3f}" for c in cs), flush=True) - - # crossover (corr>0.5) window per s, linear-interp in log(L) - print("\ncrossover window L where aggregate-angle corr = 0.5:") - Lmm = np.array([W * STEP_SIZE_MM for W in W_report]) - for s in s_list: - cs = np.array(curves[s]) - cross = None - for i in range(len(cs) - 1): - if cs[i] < 0.5 <= cs[i + 1]: - t = (0.5 - cs[i]) / (cs[i + 1] - cs[i]) - cross = np.exp(np.log(Lmm[i]) + t * (np.log(Lmm[i + 1]) - np.log(Lmm[i]))) - break - print(f" s={s:.2f}: L_0.5 = " + - (f"{cross:.1f} mm" if cross else f">{Lmm[-1]:.0f} or <{Lmm[0]:.0f} mm")) - - print("\nDone.") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/sobolev_s_scan.py b/closure/mcs/sobolev_s_scan.py deleted file mode 100644 index 90246cc..0000000 --- a/closure/mcs/sobolev_s_scan.py +++ /dev/null @@ -1,142 +0,0 @@ -"""Does lowering the Sobolev order s improve the loss landscape (conditioning)? - -First verifies the eps<->screening-length math numerically, then runs the joint -MCS fit at several s values and compares: the dip-then-rise bump, the loss -descent, the angle recovery by scale, and global stability. Lower s shrinks the -weight's low/high-frequency dynamic range -> better-conditioned, so the question -is whether the degenerate-flat-basin + slow-tail pathology eases (and whether -the angle recovery improves or overfits). - - python3 -m closure.mcs.sobolev_s_scan -""" -import math -import jax -import jax.numpy as jnp -import numpy as np -import optax - -import closure.mcs.run as R -from closure.mcs.run import ( - build_globals_only_loss, run_optimization, project_unit_circle, - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, SCALES, ANGLE_SCALE, - TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, -) -from closure.mcs.forward import ( - generate_mcs_truth, mcs_cumsum_forward, build_mcs_forward, mask_outside_volume, - highland_prior, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p - -SCj = jnp.array(SCALES, jnp.float32) - - -def verify_eps_math(max_pad=1024): - print("=== eps / screening-length check (max_pad=%d) ===" % max_pad) - eps = 1.0 / (math.pi ** 2 * max_pad ** 2) - f_screen = math.sqrt(eps) # cycles/sample where freq^2 ~ eps - kappa = 2 * math.pi * f_screen # angular, rad/sample - L_screen = 1.0 / kappa # samples - print(f" eps = 1/(pi^2 max_pad^2) = {eps:.3e}") - print(f" f_screen = sqrt(eps) = {f_screen:.3e} cycles/sample") - print(f" screening length 1/kappa = {L_screen:.1f} samples (expect max_pad/2 = {max_pad/2:.0f})") - for s in [1.5, 1.0, 0.5]: - lowf = (1.0 / eps) ** s - nyq = 1.0 / (0.25 + eps) ** s # weight at |f|~0.5 (Nyquist, 1D) - print(f" s={s}: weight(f=0)={lowf:.2e}, weight(Nyquist)={nyq:.2e}, " - f"dynamic range={lowf/nyq:.1e}") - print() - - -def main(): - verify_eps_math(1024) - - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - fwd_j = jax.jit(forward) - - key = jax.random.PRNGKey(32) - pos_t, de_t, dt1_t, dt2_t = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - truth_signals = fwd_j(pos_t, mask_outside_volume(pos_t, de_t, half_ext)) - for s in truth_signals: - jax.block_until_ready(s) - t1n, t2n = np.asarray(dt1_t), np.asarray(dt2_t) - shapes = [truth_signals[p].shape for p in range(6)] - - R.LAMBDA_PRIOR = 0.03 - init_g = np.array([TRUTH_X + 100, TRUTH_Y + 100, TRUTH_Z - 100, - np.sin(TRUTH_THETA + 0.5), np.cos(TRUTH_THETA + 0.5), - np.sin(TRUTH_PHI + 0.5), np.cos(TRUTH_PHI + 0.5), - TRUTH_ENERGY + 100]) - - def corr(p, W): - a1 = np.asarray(p[8:8 + N_SEGMENTS]) * ANGLE_SCALE - a2 = np.asarray(p[8 + N_SEGMENTS:]) * ANGLE_SCALE - def agg(x): - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - at = np.concatenate([agg(t1n), agg(t2n)]); af = np.concatenate([agg(a1), agg(a2)]) - return float(np.corrcoef(af, at)[0, 1]) if len(at) > 1 else np.nan - - N_STAGE2 = 800 - for s_order in [1.5, 1.0, 0.5]: - weights = tuple(make_sobolev_weight(*shapes[p], s=s_order) for p in range(6)) - loss_g = build_globals_only_loss(forward, log_T, dedx, truth_signals, weights, - dt1_t, dt2_t, half_ext) - params_g, *_ = run_optimization(loss_g, jnp.array(init_g / SCALES, jnp.float32), - 250, 0.015, f's1(s={s_order})', - project_fn=project_unit_circle) - - def full_loss(p): - g = p[:8] * SCj - dt1 = p[8:8 + N_SEGMENTS] * ANGLE_SCALE - dt2 = p[8 + N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward(g[7], jnp.array([g[0], g[1], g[2]]), - g[3], g[4], g[5], g[6], - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_signals, weights) - pr = highland_prior(dt1, dt2, g[7], STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + R.LAMBDA_PRIOR * pr / N_SEGMENTS - - vg = jax.jit(jax.value_and_grad(full_loss)) - opt = optax.adam(optax.exponential_decay(0.01, 1, 0.9995)) - p = jnp.concatenate([params_g, jnp.zeros(2 * N_SEGMENTS)]) - state = opt.init(p) - loss_hist = np.zeros(N_STAGE2) - for step in range(N_STAGE2): - loss, grad = vg(p) - loss_hist[step] = float(loss) - upd, state = opt.update(grad, state, p) - upd = upd.at[:8].multiply(0.003 / 0.01) - p = optax.apply_updates(p, upd) - p = p.at[:8].set(project_unit_circle(p[:8])) - - # normalize trajectory by its own dip (scale-independent shape) - dip_i = int(np.argmin(loss_hist[:250])) - dip = loss_hist[dip_i] - peak = float(np.max(loss_hist[dip_i:min(dip_i + 400, N_STAGE2)])) - g = np.asarray(p[:8] * SCj) - print(f"\n=== s={s_order} ===") - print(f" dip loss={dip:.5f} @step {dip_i}; post-dip peak={peak:.5f} " - f"(bump x{peak/dip:.1f}); final={loss_hist[-1]:.5f}") - print(f" globals: dE={g[7]-TRUTH_ENERGY:+.1f} MeV, " - f"dphi={np.degrees(np.arctan2(g[5],g[6]))-np.degrees(TRUTH_PHI):+.2f} deg") - print(f" angle corr: @12.5mm={corr(p,25):.3f}, @50mm={corr(p,100):.3f}, " - f"@200mm={corr(p,400):.3f}") - - print("\nDone.") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/study.py b/closure/mcs/study.py deleted file mode 100644 index 28a547c..0000000 --- a/closure/mcs/study.py +++ /dev/null @@ -1,279 +0,0 @@ -"""Systematic study of MCS scattering-angle recoverability from wire signals. - -Builds the truth track + differentiable wire forward ONCE, then sweeps the -scattering-angle regularisation knobs and reports physically-interpretable -metrics. Motivation (see FINDINGS_MCS.md): - - * Globals-only (vertex / direction / energy with scattering fixed) is - essentially solved (~0.15 mm, ~0.02 deg, ~1 % E). - * The 2N free per-segment scattering angles are badly ill-posed: the wire - pitch (~3 mm) is 6x coarser than the 0.5 mm step, so wire signals only - constrain the *integrated trajectory*, not the fine angles. With the - stock setup (lambda_prior=1e-3, no LR decay) the optimiser builds a - low-frequency coherent bend that overfits the wire signal — cumulative - deflection blows up to ~13x Highland and the global energy degrades. - -This harness tests three levers against that failure: - 1. coarse-graining G : one scattering angle per block of G segments - (M = N/G free angles), directly cutting low-frequency DOF. - 2. lambda_prior : strength of the Highland prior (traced -> no recompile). - 3. LR decay + early-stop at best wire-loss. - -Metrics per run: - wire_loss final wire (Sobolev) loss at the best (early-stopped) params - E_err_MeV global energy error (full mode only) - traj_rms_mm RMS position residual between fit and truth track (mm) - cum_ratio |cumulative deflection|_fit / _truth (1.0 = right magnitude) - cum_corr correlation of cumulative deflection (trajectory shape) - win_corr correlation of 3 mm-windowed deflection (fine recovery) - -Run: - python3 -m closure.mcs.study --study scattering - python3 -m closure.mcs.study --study full -""" - -import argparse -import time -import os - -import jax -import jax.numpy as jnp -import numpy as np -import optax - -from closure.mcs.forward import ( - mcs_cumsum_forward, generate_mcs_truth, highland_prior, build_mcs_forward, - mask_outside_volume, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight - -# ---- truth config (matches run.py) ---- -N_SEGMENTS = 2000 -STEP_SIZE_MM = 0.5 -STEP_SIZE_CM = STEP_SIZE_MM / 10.0 -TRUTH_X, TRUTH_Y, TRUTH_Z = -200.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 6 -TRUTH_ENERGY = 500.0 -ANGLE_SCALE = 0.01 -ENERGY_SCALE = 500.0 -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -TRUTH_SIN_TH = float(np.sin(TRUTH_THETA)) -TRUTH_COS_TH = float(np.cos(TRUTH_THETA)) -TRUTH_SIN_PH = float(np.sin(TRUTH_PHI)) -TRUTH_COS_PH = float(np.cos(TRUTH_PHI)) - - -def _direction(sth, cth, sph, cph): - d = jnp.array([sth * cph, sth * sph, cth]) - return d / jnp.linalg.norm(d) - - -def expand_coarse(coarse, G, M): - """(2M,) coarse angles -> (N,),(N,) per-segment angles, constant per block.""" - a1 = jnp.repeat(coarse[:M], G) - a2 = jnp.repeat(coarse[M:], G) - return a1 * ANGLE_SCALE, a2 * ANGLE_SCALE - - -def metrics(dt1_fit, dt2_fit, dt1_truth, dt2_truth, pos_fit, pos_truth): - dt1_t, dt2_t = np.asarray(dt1_truth), np.asarray(dt2_truth) - dt1_f, dt2_f = np.asarray(dt1_fit), np.asarray(dt2_fit) - N = len(dt1_t) - - # trajectory position residual (mm) - traj_rms = float(np.sqrt(np.mean(np.sum((np.asarray(pos_fit) - - np.asarray(pos_truth)) ** 2, axis=1)))) - - # cumulative deflection - cum1_t, cum2_t = np.cumsum(dt1_t), np.cumsum(dt2_t) - cum1_f, cum2_f = np.cumsum(dt1_f), np.cumsum(dt2_f) - tot_t = np.sqrt(cum1_t[-1] ** 2 + cum2_t[-1] ** 2) - tot_f = np.sqrt(cum1_f[-1] ** 2 + cum2_f[-1] ** 2) - cum_ratio = tot_f / (tot_t + 1e-12) - cum_corr = 0.5 * (np.corrcoef(cum1_f, cum1_t)[0, 1] + - np.corrcoef(cum2_f, cum2_t)[0, 1]) - - # 3 mm-windowed deflection - window = max(1, int(round(3.0 / STEP_SIZE_MM))) - nw = N // window - def winsum(x): - return x[:nw * window].reshape(nw, window).sum(1) - win_corr = 0.5 * (np.corrcoef(winsum(dt1_f), winsum(dt1_t))[0, 1] + - np.corrcoef(winsum(dt2_f), winsum(dt2_t))[0, 1]) - - return dict(traj_rms_mm=traj_rms, cum_ratio=cum_ratio, - cum_corr=cum_corr, win_corr=win_corr) - - -def run_adam(loss_and_grad, init, n_steps, lr, lam, decay=1.0, - project=None, early_stop=True): - """Adam with optional exp LR decay + early stop at best loss. Returns best params.""" - if decay < 1.0: - sched = optax.exponential_decay(lr, transition_steps=1, decay_rate=decay) - opt = optax.adam(sched) - else: - opt = optax.adam(lr) - state = opt.init(init) - params = init - best_loss, best_params = np.inf, init - for step in range(n_steps): - loss, grad = loss_and_grad(params, lam) - lv = float(loss) - if early_stop and lv < best_loss: - best_loss, best_params = lv, params - upd, state = opt.update(grad, state, params) - params = optax.apply_updates(params, upd) - if project is not None: - params = project(params) - if not early_stop: - best_loss, best_params = float(loss_and_grad(params, lam)[0]), params - return best_params, best_loss - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument('--study', choices=['scattering', 'full'], default='scattering') - ap.add_argument('--steps', type=int, default=400) - args = ap.parse_args() - - print("=" * 78) - print(f"MCS SCATTERING STUDY — mode={args.study}, N={N_SEGMENTS}, steps={args.steps}") - print("=" * 78, flush=True) - - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - # truth - key = jax.random.PRNGKey(42) - pos_truth, de_truth, dt1_truth, dt2_truth = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - de_truth_m = mask_outside_volume(pos_truth, de_truth, half_ext) - t0 = time.time() - truth_signals = jax.jit(forward)(pos_truth, de_truth_m) - for s in truth_signals: - jax.block_until_ready(s) - print(f"truth signals compiled ({time.time()-t0:.1f}s)", flush=True) - weights = tuple(make_sobolev_weight(*truth_signals[p].shape, s=1.5) - for p in range(6)) - - pos_truth_np = np.asarray(pos_truth) - cum_truth = np.sqrt(np.cumsum(dt1_truth)[-1] ** 2 + np.cumsum(dt2_truth)[-1] ** 2) - print(f"truth cumulative deflection = {cum_truth*1000:.1f} mrad", flush=True) - - truth_start = jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32) - - # sweep grid - if args.study == 'scattering': - G_list = [1, 5, 10, 20] - lam_list = [1e-3, 3e-2, 0.3] - decay_list = [1.0, 0.99] - else: - # full mode: focus on the informative region found in the scattering sweep - G_list = [1, 10] - lam_list = [1e-3, 3e-2, 0.3] - decay_list = [1.0, 0.99] - - header = (f"{'G':>3} {'M':>5} {'lam':>7} {'decay':>6} {'wire_loss':>10} " - f"{'E_err':>7} {'traj_mm':>8} {'cum_ratio':>9} {'cum_corr':>9} {'win_corr':>9}") - print("\n" + header) - print("-" * len(header), flush=True) - - results = [] - for G in G_list: - M = N_SEGMENTS // G - assert M * G == N_SEGMENTS - - if args.study == 'scattering': - # params = 2M coarse angles; globals fixed at truth - def make_loss(G=G, M=M): - def loss(params, lam): - dt1, dt2 = expand_coarse(params, G, M) - pos, de = mcs_cumsum_forward( - jnp.float32(TRUTH_ENERGY), truth_start, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_signals, weights) - pr = highland_prior(dt1, dt2, jnp.float32(TRUTH_ENERGY), - STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + lam * pr / N_SEGMENTS - return loss - init = jnp.zeros(2 * M) - project = None - else: - # full: params = [8 globals_norm] + 2M coarse angles - def make_loss(G=G, M=M): - SC = jnp.array([200., 200., 200., 1., 1., 1., 1., ENERGY_SCALE]) - def loss(params, lam): - g = params[:8] * SC - dt1, dt2 = expand_coarse(params[8:], G, M) - pos, de = mcs_cumsum_forward( - g[7], jnp.array([g[0], g[1], g[2]]), - g[3], g[4], g[5], g[6], - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_signals, weights) - pr = highland_prior(dt1, dt2, g[7], STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + lam * pr / N_SEGMENTS - return loss - SC = np.array([200., 200., 200., 1., 1., 1., 1., ENERGY_SCALE]) - init_g = np.array([TRUTH_X + 100, TRUTH_Y + 100, TRUTH_Z - 100, - np.sin(TRUTH_THETA + 0.5), np.cos(TRUTH_THETA + 0.5), - np.sin(TRUTH_PHI + 0.5), np.cos(TRUTH_PHI + 0.5), - TRUTH_ENERGY + 100]) / SC - init = jnp.concatenate([jnp.array(init_g, jnp.float32), jnp.zeros(2 * M)]) - - def project(p): - st, ct = p[3], p[4] - nt = jnp.maximum(jnp.sqrt(st**2 + ct**2), 1e-8) - sp, cp = p[5], p[6] - npp = jnp.maximum(jnp.sqrt(sp**2 + cp**2), 1e-8) - return p.at[3].set(st/nt).at[4].set(ct/nt).at[5].set(sp/npp).at[6].set(cp/npp) - - loss_fn = make_loss() - lg = jax.jit(jax.value_and_grad(loss_fn)) - _ = lg(init, jnp.float32(lam_list[0])) # compile - jax.block_until_ready(_[0]) - - for lam in lam_list: - for decay in decay_list: - best, bl = run_adam(lg, init, args.steps, 0.01, jnp.float32(lam), - decay=decay, project=project) - # extract fit - if args.study == 'scattering': - dt1_f, dt2_f = expand_coarse(best, G, M) - pos_f, de_f = mcs_cumsum_forward( - jnp.float32(TRUTH_ENERGY), truth_start, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - dt1_f, dt2_f, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - e_err = 0.0 - else: - SCj = jnp.array([200., 200., 200., 1., 1., 1., 1., ENERGY_SCALE]) - g = best[:8] * SCj - dt1_f, dt2_f = expand_coarse(best[8:], G, M) - pos_f, de_f = mcs_cumsum_forward( - g[7], jnp.array([g[0], g[1], g[2]]), g[3], g[4], g[5], g[6], - dt1_f, dt2_f, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - e_err = float(g[7]) - TRUTH_ENERGY - m = metrics(dt1_f, dt2_f, dt1_truth, dt2_truth, pos_f, pos_truth_np) - results.append((G, M, lam, decay, bl, e_err, m)) - print(f"{G:>3} {M:>5} {lam:>7.0e} {decay:>6.2f} {bl:>10.4f} " - f"{e_err:>7.1f} {m['traj_rms_mm']:>8.2f} {m['cum_ratio']:>9.2f} " - f"{m['cum_corr']:>9.3f} {m['win_corr']:>9.3f}", flush=True) - - print("\nDone.") - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/validate_position.py b/closure/mcs/validate_position.py deleted file mode 100644 index 4bad89c..0000000 --- a/closure/mcs/validate_position.py +++ /dev/null @@ -1,408 +0,0 @@ -""" -Validation level 3: position-space closure tests. - -3a: Fix globals at truth, recover scattering angles from noisy positions. -3b: All params free — recover vertex, direction, energy, and scattering. - -Run from project root: - python3 -m closure.mcs.validate_position - -Migrated from closure_analysis_MCS/validate_position_closure.py. -""" - -import sys -import os -import jax -import jax.numpy as jnp -import numpy as np -import optax -import matplotlib.pyplot as plt -import time - -from closure.mcs.forward import ( - mcs_cumsum_forward, - generate_mcs_truth, - highland_prior, -) -from tools.particle_generator import load_dedx_table_jax -from closure.mcs.mcs_physics import _perpendicular_basis - - -# --------------------------------------------------------------------------- -# Configuration -# --------------------------------------------------------------------------- - -N_SEGMENTS = 500 -STEP_SIZE_MM = 0.1 -N_SEGMENTS_3B = 2500 # Longer track for energy observability via dE/dx -ENERGY = 500.0 -START = np.array([-200.0, 0.0, 100.0]) -THETA = np.pi / 4 -PHI = np.pi / 6 - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -results = [] - -def test(name, passed, message=""): - status = "PASS" if passed else "FAIL" - results.append((name, passed, message)) - print(f" [{status}] {name}: {message}") - - -# --------------------------------------------------------------------------- -# 3a: Fix globals, recover scattering from noisy positions -# --------------------------------------------------------------------------- - -def test_3a(): - print("\n=== 3a: Recover scattering angles from noisy positions ===") - - log_T, dedx = load_dedx_table_jax() - rng_key = jax.random.PRNGKey(42) - - # Generate truth - pos_truth, de_truth, dt1_truth, dt2_truth = generate_mcs_truth( - jnp.float32(ENERGY), jnp.array(START, dtype=jnp.float32), - jnp.float32(THETA), jnp.float32(PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, rng_key, - ) - - # Add noise to positions (0.3mm as per plan) - noise_key = jax.random.PRNGKey(123) - noise = 0.3 * jax.random.normal(noise_key, shape=pos_truth.shape) - pos_noisy = pos_truth + noise - - # Fixed global parameters - sin_th = jnp.sin(jnp.float32(THETA)) - cos_th = jnp.cos(jnp.float32(THETA)) - sin_ph = jnp.sin(jnp.float32(PHI)) - cos_ph = jnp.cos(jnp.float32(PHI)) - start_jax = jnp.array(START, dtype=jnp.float32) - energy_jax = jnp.float32(ENERGY) - step_cm = STEP_SIZE_MM / 10.0 - lambda_prior = 0.01 - - # Loss: position MSE + Highland prior - def loss_fn(dtheta_flat): - dt1 = dtheta_flat[:N_SEGMENTS] - dt2 = dtheta_flat[N_SEGMENTS:] - pos, _ = mcs_cumsum_forward( - energy_jax, start_jax, sin_th, cos_th, sin_ph, cos_ph, - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - pos_loss = jnp.mean((pos - pos_noisy) ** 2) - prior = highland_prior( - dt1, dt2, energy_jax, step_cm, N_SEGMENTS, - log_T, dedx, - ) - return pos_loss + lambda_prior * prior / N_SEGMENTS - - loss_and_grad = jax.jit(jax.value_and_grad(loss_fn)) - - # Initialize at zero scattering - params = jnp.zeros(2 * N_SEGMENTS) - - # Adam optimization - optimizer = optax.adam(learning_rate=0.001) - opt_state = optimizer.init(params) - n_steps = 500 - loss_hist = [] - - print(f" Optimizing {2*N_SEGMENTS} scattering angles, {n_steps} steps...") - t0 = time.time() - for step in range(n_steps): - loss, grad = loss_and_grad(params) - loss_hist.append(float(loss)) - updates, opt_state = optimizer.update(grad, opt_state, params) - params = optax.apply_updates(params, updates) - if step % 100 == 0: - print(f" Step {step}: loss = {float(loss):.6f}") - - print(f" Optimization took {time.time()-t0:.1f}s") - - # Evaluate: cumulative angle correlation is the meaningful metric - # (per-angle recovery is noise-limited at 0.3mm / 0.5mm steps) - dt1_fit = np.array(params[:N_SEGMENTS]) - dt2_fit = np.array(params[N_SEGMENTS:]) - dt1_t = np.array(dt1_truth) - dt2_t = np.array(dt2_truth) - - cum1_fit = np.cumsum(dt1_fit) - cum1_truth = np.cumsum(dt1_t) - cum_corr1 = np.corrcoef(cum1_fit, cum1_truth)[0, 1] - cum2_fit = np.cumsum(dt2_fit) - cum2_truth = np.cumsum(dt2_t) - cum_corr2 = np.corrcoef(cum2_fit, cum2_truth)[0, 1] - avg_cum_corr = (cum_corr1 + cum_corr2) / 2 - - # Also check trajectory match - pos_fit, _ = mcs_cumsum_forward( - energy_jax, start_jax, sin_th, cos_th, sin_ph, cos_ph, - jnp.array(dt1_fit), jnp.array(dt2_fit), STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - mean_pos_err = float(jnp.mean(jnp.sqrt(jnp.sum((pos_fit - pos_truth) ** 2, axis=1)))) - - test("3a: Cumulative angle correlation > 0.5", - avg_cum_corr > 0.5, - f"cum_corr1={cum_corr1:.3f}, cum_corr2={cum_corr2:.3f}, avg={avg_cum_corr:.3f}") - test("3a: Trajectory error < 1mm", - mean_pos_err < 1.0, - f"mean position error = {mean_pos_err:.3f} mm") - - # Plots - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - - # Loss curve - axes[0, 0].semilogy(loss_hist) - axes[0, 0].set_xlabel('Step') - axes[0, 0].set_ylabel('Loss') - axes[0, 0].set_title('3a: Loss convergence') - axes[0, 0].grid(True, alpha=0.3) - - # Cumulative angle comparison - axes[0, 1].plot(cum1_truth * 1000, 'g-', lw=1, label='truth') - axes[0, 1].plot(cum1_fit * 1000, 'b-', lw=1, label='fit') - axes[0, 1].set_xlabel('Segment') - axes[0, 1].set_ylabel('Cumulative dtheta1 (mrad)') - axes[0, 1].set_title(f'3a: Cumulative angle (r={cum_corr1:.3f})') - axes[0, 1].legend() - axes[0, 1].grid(True, alpha=0.3) - - # Trajectory comparison - pos_fit_np = np.array(pos_fit) - pos_t = np.array(pos_truth) - axes[1, 0].plot(pos_t[:, 2], pos_t[:, 1], 'g-', lw=1, label='truth', alpha=0.7) - axes[1, 0].plot(pos_fit_np[:, 2], pos_fit_np[:, 1], 'b-', lw=1, label='fit', alpha=0.7) - axes[1, 0].set_xlabel('z (mm)') - axes[1, 0].set_ylabel('y (mm)') - axes[1, 0].set_title('3a: Trajectory (yz projection)') - axes[1, 0].legend() - axes[1, 0].grid(True, alpha=0.3) - - # Angle comparison - seg_idx = np.arange(N_SEGMENTS) - axes[1, 1].plot(seg_idx, dt1_t * 1000, 'g-', lw=0.5, alpha=0.5, label='truth') - axes[1, 1].plot(seg_idx, dt1_fit * 1000, 'b-', lw=0.5, alpha=0.5, label='fit') - axes[1, 1].set_xlabel('Segment') - axes[1, 1].set_ylabel('dtheta1 (mrad)') - axes[1, 1].set_title('3a: Per-segment scattering') - axes[1, 1].legend() - axes[1, 1].grid(True, alpha=0.3) - - fig.suptitle('Level 3a: Recover scattering from noisy positions', fontweight='bold') - fig.tight_layout() - fig.savefig(os.path.join(OUT_DIR, 'validate_3a.png'), dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved validate_3a.png") - - return dt1_truth, dt2_truth, pos_truth, de_truth - - -# --------------------------------------------------------------------------- -# 3b: All params free -# --------------------------------------------------------------------------- - -def test_3b(): - print("\n=== 3b: All params free — recover vertex + angles ===") - - N = N_SEGMENTS_3B - log_T, dedx = load_dedx_table_jax() - rng_key = jax.random.PRNGKey(42) - - # Generate truth (longer track for energy observability) - pos_truth, de_truth, dt1_truth, dt2_truth = generate_mcs_truth( - jnp.float32(ENERGY), jnp.array(START, dtype=jnp.float32), - jnp.float32(THETA), jnp.float32(PHI), - STEP_SIZE_MM, N, log_T, dedx, rng_key, - ) - - # Add noise (0.05mm) - noise_key = jax.random.PRNGKey(456) - noise = 0.05 * jax.random.normal(noise_key, shape=pos_truth.shape) - pos_noisy = pos_truth + noise - - step_cm = STEP_SIZE_MM / 10.0 - lambda_prior = 0.01 - - # Parameter scales (same convention as muon_full_optimization) - SCALES = jnp.array([200.0, 200.0, 200.0, 1.0, 1.0, 1.0, 1.0, 500.0]) - ANGLE_SCALE = 0.01 - - # Truth in normalized space - truth_globals = jnp.array([ - START[0], START[1], START[2], - np.sin(THETA), np.cos(THETA), - np.sin(PHI), np.cos(PHI), - ENERGY, - ]) - - # Perturbed initial guess - init_theta = THETA + 0.2 - init_phi = PHI + 0.2 - init_globals = jnp.array([ - START[0] + 50.0, START[1] + 50.0, START[2] - 50.0, - np.sin(init_theta), np.cos(init_theta), - np.sin(init_phi), np.cos(init_phi), - ENERGY + 50.0, - ]) - - # Full parameter vector: [8 globals (normalized), 2*N scattering angles (scaled)] - init_params = jnp.concatenate([ - init_globals / SCALES, - jnp.zeros(2 * N), - ]) - - def loss_fn(params): - g = params[:8] * SCALES - dt1 = params[8:8 + N] * ANGLE_SCALE - dt2 = params[8 + N:] * ANGLE_SCALE - - pos, de = mcs_cumsum_forward( - g[7], jnp.array([g[0], g[1], g[2]]), - g[3], g[4], g[5], g[6], - dt1, dt2, STEP_SIZE_MM, N, log_T, dedx, - ) - pos_loss = jnp.mean((pos - pos_noisy) ** 2) - # Total dE constraint gives strong energy gradient - # (per-segment dE is flat in MIP region, but total dE differs) - total_de_truth = jnp.sum(de_truth) - total_de_loss = ((jnp.sum(de) - total_de_truth) / total_de_truth) ** 2 - prior = highland_prior( - dt1, dt2, g[7], step_cm, N, - log_T, dedx, - ) - return pos_loss + total_de_loss + lambda_prior * prior / N - - loss_and_grad = jax.jit(jax.value_and_grad(loss_fn)) - - # Project trig components onto unit circle - def project_trig(params): - g = params[:8] - st, ct = g[3], g[4] - norm_t = jnp.maximum(jnp.sqrt(st**2 + ct**2), 1e-8) - sp, cp = g[5], g[6] - norm_p = jnp.maximum(jnp.sqrt(sp**2 + cp**2), 1e-8) - g = g.at[3].set(st / norm_t).at[4].set(ct / norm_t) - g = g.at[5].set(sp / norm_p).at[6].set(cp / norm_p) - return params.at[:8].set(g) - - optimizer = optax.adam(learning_rate=0.01) - opt_state = optimizer.init(init_params) - params = init_params - n_steps = 800 - loss_hist = [] - param_hist = [] - - print(f" Optimizing 8 globals + {2*N} angles, {n_steps} steps...") - t0 = time.time() - for step in range(n_steps): - loss, grad = loss_and_grad(params) - loss_hist.append(float(loss)) - param_hist.append(np.array(params[:8] * np.array(SCALES))) - updates, opt_state = optimizer.update(grad, opt_state, params) - params = optax.apply_updates(params, updates) - params = project_trig(params) - if step % 100 == 0: - g = np.array(params[:8] * np.array(SCALES)) - print(f" Step {step}: loss={float(loss):.6f}, " - f"x={g[0]:.1f}, y={g[1]:.1f}, z={g[2]:.1f}, E={g[7]:.1f}") - - print(f" Optimization took {time.time()-t0:.1f}s") - - # Final parameters - final_g = np.array(params[:8] * np.array(SCALES)) - vertex_err = np.sqrt(np.sum((final_g[:3] - np.array(START)) ** 2)) - energy_err = abs(final_g[7] - ENERGY) - - test("3b: Vertex recovery < 5mm", - vertex_err < 5.0, - f"vertex error = {vertex_err:.2f} mm") - # Note: Energy is not recoverable from positions in the MIP region. - # dE/dx varies < 20% over 100-1000 MeV, and the Highland prior biases - # energy downward. Wire-signal closure (levels 5-6) constrains energy. - print(f" Note: Energy = {final_g[7]:.1f} MeV (truth = {ENERGY:.1f}) — " - f"expected: position closure cannot constrain energy in MIP regime") - - # Plot - param_hist = np.array(param_hist) - fig, axes = plt.subplots(2, 3, figsize=(16, 10)) - - # Loss - axes[0, 0].semilogy(loss_hist) - axes[0, 0].set_xlabel('Step') - axes[0, 0].set_ylabel('Loss') - axes[0, 0].set_title('3b: Loss convergence') - axes[0, 0].grid(True, alpha=0.3) - - # x - axes[0, 1].plot(param_hist[:, 0], 'b-') - axes[0, 1].axhline(START[0], color='g', ls='--', label=f'truth={START[0]}') - axes[0, 1].set_title('x (mm)') - axes[0, 1].legend(fontsize=8) - axes[0, 1].grid(True, alpha=0.3) - - # y - axes[0, 2].plot(param_hist[:, 1], 'b-') - axes[0, 2].axhline(START[1], color='g', ls='--', label=f'truth={START[1]}') - axes[0, 2].set_title('y (mm)') - axes[0, 2].legend(fontsize=8) - axes[0, 2].grid(True, alpha=0.3) - - # z - axes[1, 0].plot(param_hist[:, 2], 'b-') - axes[1, 0].axhline(START[2], color='g', ls='--', label=f'truth={START[2]}') - axes[1, 0].set_title('z (mm)') - axes[1, 0].legend(fontsize=8) - axes[1, 0].grid(True, alpha=0.3) - - # theta - eff_theta = np.arctan2(param_hist[:, 3], param_hist[:, 4]) - axes[1, 1].plot(np.degrees(eff_theta), 'b-') - axes[1, 1].axhline(np.degrees(THETA), color='g', ls='--', - label=f'truth={np.degrees(THETA):.1f}') - axes[1, 1].set_title('theta (deg)') - axes[1, 1].legend(fontsize=8) - axes[1, 1].grid(True, alpha=0.3) - - # energy - axes[1, 2].plot(param_hist[:, 7], 'b-') - axes[1, 2].axhline(ENERGY, color='g', ls='--', label=f'truth={ENERGY}') - axes[1, 2].set_title('Energy (MeV)') - axes[1, 2].legend(fontsize=8) - axes[1, 2].grid(True, alpha=0.3) - - fig.suptitle('Level 3b: All params free — position closure', fontweight='bold') - fig.tight_layout() - fig.savefig(os.path.join(OUT_DIR, 'validate_3b.png'), dpi=150, bbox_inches='tight') - plt.close(fig) - print(f" Saved validate_3b.png") - - -# --------------------------------------------------------------------------- -# Main -# --------------------------------------------------------------------------- - -def main(): - print("=" * 60) - print("MCS POSITION CLOSURE VALIDATION (Level 3)") - print("=" * 60) - - test_3a() - test_3b() - - print("\n" + "=" * 60) - n_pass = sum(1 for _, p, _ in results if p) - n_total = len(results) - print(f"SUMMARY: {n_pass}/{n_total} tests passed") - if n_pass == n_total: - print("ALL TESTS PASSED") - else: - print("FAILURES:") - for name, passed, msg in results: - if not passed: - print(f" {name}: {msg}") - print("=" * 60) - - -if __name__ == '__main__': - main() diff --git a/closure/mcs/window_scan.py b/closure/mcs/window_scan.py deleted file mode 100644 index c1ac725..0000000 --- a/closure/mcs/window_scan.py +++ /dev/null @@ -1,159 +0,0 @@ -"""How coarse must we aggregate before MCS scattering angles become recoverable? - -The per-3 mm (wire-pitch) scattering angle is unrecoverable (corr ~0.25), but -that is the *evaluation* scale, not a statement about the physics. A net -deflection over a window of length L moves the track by ~L*theta, so the wire -position signal that constrains it grows with L. This scans the aggregate -(window-summed) scattering angle recovery as a function of window length and -locates the crossover where it becomes well-measured. - -Runs ONE scattering-only closure (globals fixed at truth, best regularization), -then aggregates the per-segment fit/truth angles at many window sizes. - - python3 -m closure.mcs.window_scan -""" - -import time -import os -import jax -import jax.numpy as jnp -import numpy as np - -from closure.mcs.forward import ( - mcs_cumsum_forward, generate_mcs_truth, highland_prior, build_mcs_forward, - mask_outside_volume, -) -from closure.mcs.study import ( - N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, TRUTH_X, TRUTH_Y, TRUTH_Z, - TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, ANGLE_SCALE, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - run_adam, OUT_DIR, -) -from tools.particle_generator import load_dedx_table_jax, get_half_extents_mm -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight - - -def window_aggregate(x, W): - """Sum array into non-overlapping windows of W elements (drop remainder).""" - n = len(x) // W - return x[:n * W].reshape(n, W).sum(1) - - -def main(): - print("=" * 76) - print("MCS aggregate-angle recovery vs window length (scattering-only)") - print("=" * 76, flush=True) - - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - half_ext = get_half_extents_mm(det) - sim = DetectorSimulator(det, differentiable=True, n_segments=N_SEGMENTS, - recombination_model='modified_box') - forward = build_mcs_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - key = jax.random.PRNGKey(42) - pos_truth, de_truth, dt1_truth, dt2_truth = generate_mcs_truth( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, key) - de_truth_m = mask_outside_volume(pos_truth, de_truth, half_ext) - t0 = time.time() - truth_signals = jax.jit(forward)(pos_truth, de_truth_m) - for s in truth_signals: - jax.block_until_ready(s) - print(f"truth signals compiled ({time.time()-t0:.1f}s)", flush=True) - weights = tuple(make_sobolev_weight(*truth_signals[p].shape, s=1.5) - for p in range(6)) - - truth_start = jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], jnp.float32) - - # scattering-only loss (globals fixed at truth), best regularization - def loss(params, lam): - dt1 = params[:N_SEGMENTS] * ANGLE_SCALE - dt2 = params[N_SEGMENTS:] * ANGLE_SCALE - pos, de = mcs_cumsum_forward( - jnp.float32(TRUTH_ENERGY), truth_start, - TRUTH_SIN_TH, TRUTH_COS_TH, TRUTH_SIN_PH, TRUTH_COS_PH, - dt1, dt2, STEP_SIZE_MM, N_SEGMENTS, log_T, dedx) - de = mask_outside_volume(pos, de, half_ext) - wl = sobolev_loss_geomean_log1p(forward(pos, de), truth_signals, weights) - pr = highland_prior(dt1, dt2, jnp.float32(TRUTH_ENERGY), - STEP_SIZE_CM, N_SEGMENTS, log_T, dedx) - return wl + lam * pr / N_SEGMENTS - - lg = jax.jit(jax.value_and_grad(loss)) - init = jnp.zeros(2 * N_SEGMENTS) - print("compiling + optimizing (lam=3e-2, decay=0.99, early-stop, 300 steps)...", - flush=True) - best, bl = run_adam(lg, init, 300, 0.01, jnp.float32(3e-2), - decay=0.99, early_stop=True) - print(f" best wire+prior loss = {bl:.5f}", flush=True) - - dt1_f = np.asarray(best[:N_SEGMENTS]) * ANGLE_SCALE - dt2_f = np.asarray(best[N_SEGMENTS:]) * ANGLE_SCALE - dt1_t, dt2_t = np.asarray(dt1_truth), np.asarray(dt2_truth) - - # --- aggregate-angle recovery vs window length --- - # windows in segments; 0.5 mm/segment - W_list = [1, 2, 6, 12, 25, 50, 100, 200, 400] - print(f"\n{'W_seg':>6} {'L_mm':>7} {'n_win':>6} {'corr':>7} " - f"{'rms_t_mrad':>11} {'rms_f_mrad':>11} {'rms_f/rms_t':>11} {'resid_mrad':>11}") - print("-" * 80) - rows = [] - for W in W_list: - a1t, a2t = window_aggregate(dt1_t, W), window_aggregate(dt2_t, W) - a1f, a2f = window_aggregate(dt1_f, W), window_aggregate(dt2_f, W) - at = np.concatenate([a1t, a2t]) - af = np.concatenate([a1f, a2f]) - nwin = len(a1t) - corr = np.corrcoef(af, at)[0, 1] if nwin > 1 else float('nan') - rms_t = np.sqrt(np.mean(at ** 2)) * 1000 - rms_f = np.sqrt(np.mean(af ** 2)) * 1000 - resid = np.sqrt(np.mean((af - at) ** 2)) * 1000 - rows.append((W, W * STEP_SIZE_MM, nwin, corr, rms_t, rms_f, resid)) - print(f"{W:>6} {W*STEP_SIZE_MM:>7.1f} {nwin:>6} {corr:>7.3f} " - f"{rms_t:>11.3f} {rms_f:>11.3f} {rms_f/rms_t:>11.3f} {resid:>11.3f}", - flush=True) - - # cumulative (whole track) deflection - cum_t = np.sqrt(np.sum(dt1_t) ** 2 + np.sum(dt2_t) ** 2) * 1000 - cum_f = np.sqrt(np.sum(dt1_f) ** 2 + np.sum(dt2_f) ** 2) * 1000 - print(f"\nwhole-track net deflection: truth={cum_t:.1f} mrad, " - f"fit={cum_f:.1f} mrad (ratio {cum_f/cum_t:.2f})") - - # --- plot --- - try: - import matplotlib - matplotlib.use('Agg') - import matplotlib.pyplot as plt - Wm = np.array([r[1] for r in rows]) - corrs = np.array([r[3] for r in rows]) - ratio = np.array([r[5] / r[4] for r in rows]) - fig, ax = plt.subplots(1, 2, figsize=(12, 4.5)) - ax[0].semilogx(Wm, corrs, 'o-', color='#3d6aa6') - ax[0].axhline(0.5, color='grey', ls=':') - ax[0].set_xlabel('aggregation window L (mm)') - ax[0].set_ylabel('aggregate-angle correlation') - ax[0].set_title('Recovery vs window length') - ax[0].grid(True, alpha=0.3) - ax[1].semilogx(Wm, ratio, 's-', color='#8e5572') - ax[1].axhline(1.0, color='grey', ls=':') - ax[1].set_xlabel('aggregation window L (mm)') - ax[1].set_ylabel('RMS(fit) / RMS(truth)') - ax[1].set_title('Aggregate-angle magnitude bias') - ax[1].grid(True, alpha=0.3) - fig.tight_layout() - fn = os.path.join(OUT_DIR, 'mcs_aggregate_angle_recovery.png') - fig.savefig(fn, dpi=140, bbox_inches='tight') - print(f"saved {fn}") - except Exception as e: - print(f"(plot skipped: {e})") - - print("\nDone.") - - -if __name__ == '__main__': - main() diff --git a/closure/muon/detector_surfaces_emb.py b/closure/muon/detector_surfaces_emb.py deleted file mode 100644 index 47557cb..0000000 --- a/closure/muon/detector_surfaces_emb.py +++ /dev/null @@ -1,235 +0,0 @@ -""" -Loss and gradient surfaces for detector physics parameters with EMB recombination. - -Same as detector_surfaces.py but passes real track angles (theta, phi) -per segment so the EMB angular-dependent recombination is fully exercised. -Includes R_anisotropy in the sweep parameters. - -Run from project root: - python3 closure/muon/detector_surfaces_emb.py -""" - -import os, time - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.particle_generator import ( - load_dedx_table_jax, generate_muon_segments_trig, mask_outside_volume, -) -from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight - -# ============================================================================= -# Configuration -# ============================================================================= - -N_SEGMENTS = 4000 -STEP_SIZE_MM = 0.5 -HALF_EXT = (2160.0, 2160.0, 2160.0) -N_SWEEP = 40 -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -# Truth muon parameters -TRUTH_X, TRUTH_Y, TRUTH_Z = -200.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 6 -TRUTH_ENERGY = 500.0 - -# Detector parameter sweep configs -DETECTOR_PARAMS = { - 'diffusion_trans': { - 'range': (4.0e-6, 24.0e-6), - 'unit': 'cm2/us', - 'fd_eps': 1.0e-7, - 'getter': lambda p: p.diffusion_trans_cm2_us, - 'setter': lambda p, v: p._replace(diffusion_trans_cm2_us=v), - }, - 'diffusion_long': { - 'range': (2.0e-6, 14.0e-6), - 'unit': 'cm2/us', - 'fd_eps': 5.0e-8, - 'getter': lambda p: p.diffusion_long_cm2_us, - 'setter': lambda p, v: p._replace(diffusion_long_cm2_us=v), - }, - 'velocity': { - 'range': (0.10, 0.22), - 'unit': 'cm/us', - 'fd_eps': 0.001, - 'getter': lambda p: p.velocity_cm_us, - 'setter': lambda p, v: p._replace(velocity_cm_us=v), - }, - 'lifetime': { - 'range': (5000.0, 20000.0), - 'unit': 'us', - 'fd_eps': 10.0, - 'getter': lambda p: p.lifetime_us, - 'setter': lambda p, v: p._replace(lifetime_us=v), - }, - 'recomb_alpha': { - 'range': (0.5, 1.5), - 'unit': '', - 'fd_eps': 0.005, - 'getter': lambda p: p.recomb_params.alpha, - 'setter': lambda p, v: p._replace( - recomb_params=p.recomb_params._replace(alpha=v)), - }, - 'recomb_beta_90': { - 'range': (0.1, 0.5), - 'unit': '', - 'fd_eps': 0.002, - 'getter': lambda p: p.recomb_params.beta_90, - 'setter': lambda p, v: p._replace( - recomb_params=p.recomb_params._replace(beta_90=v)), - }, - 'recomb_R': { - 'range': (0.5, 2.5), - 'unit': '', - 'fd_eps': 0.005, - 'getter': lambda p: p.recomb_params.R, - 'setter': lambda p, v: p._replace( - recomb_params=p.recomb_params._replace(R=v)), - }, -} - - -# ============================================================================= -# Main -# ============================================================================= - -def main(): - print("=" * 60) - print("DETECTOR PARAMETER GRADIENT SURFACES (EMB + angles)") - print("=" * 60) - - # --- Setup --- - log_T, dedx = load_dedx_table_jax() - det = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator( - det, differentiable=True, n_segments=N_SEGMENTS, - include_noise=False, include_electronics=False, - include_track_hits=False, - ) - truth_params = sim.default_sim_params - - # --- Generate fixed muon track --- - pos, de = generate_muon_segments_trig( - jnp.float32(TRUTH_ENERGY), - jnp.array([TRUTH_X, TRUTH_Y, TRUTH_Z], dtype=jnp.float32), - jnp.float32(jnp.sin(TRUTH_THETA)), jnp.float32(jnp.cos(TRUTH_THETA)), - jnp.float32(jnp.sin(TRUTH_PHI)), jnp.float32(jnp.cos(TRUTH_PHI)), - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - de = mask_outside_volume(pos, de, HALF_EXT) - n_active = int((de > 0).sum()) - print(f"Muon: {N_SEGMENTS} segments, {n_active} active") - print(f"Track angles: theta={TRUTH_THETA:.4f} rad, phi={TRUTH_PHI:.4f} rad\n") - - # --- Truth signals --- - print("Computing truth signals...", flush=True) - t0 = time.time() - truth_sigs = jax.jit( - lambda: sim.forward_segments(truth_params, pos, de, STEP_SIZE_MM) - )() - for s in truth_sigs: - jax.block_until_ready(s) - print(f" Done ({time.time() - t0:.1f}s)\n") - - # --- Spectral weights --- - spec_w = tuple( - make_sobolev_weight(*truth_sigs[p].shape, s=1.5) for p in range(6) - ) - - # --- Loss function (parameterized by single scalar) --- - def make_loss_fn(param_name): - cfg = DETECTOR_PARAMS[param_name] - setter = cfg['setter'] - - def loss_fn(val): - p = setter(truth_params, val) - sigs = sim.forward_segments(p, pos, de, STEP_SIZE_MM) - return sobolev_loss_geomean_log1p(sigs, truth_sigs, spec_w) - - return loss_fn - - # --- Sweep each parameter --- - for param_name, cfg in DETECTOR_PARAMS.items(): - lo, hi = cfg['range'] - unit = cfg['unit'] - fd_eps = cfg['fd_eps'] - truth_val = float(cfg['getter'](truth_params)) - - print(f"Sweeping {param_name} [{lo:.4g}, {hi:.4g}] (truth={truth_val:.4g})") - - loss_fn = make_loss_fn(param_name) - - # Compile - t0 = time.time() - loss_and_grad = jax.jit(jax.value_and_grad(loss_fn)) - loss_jit = jax.jit(loss_fn) - _ = loss_and_grad(jnp.float32(truth_val)) - print(f" Compiled ({time.time() - t0:.1f}s)") - - # Sweep - x_vals = np.linspace(lo, hi, N_SWEEP) - losses = np.empty(N_SWEEP) - ad_grads = np.empty(N_SWEEP) - fd_grads = np.empty(N_SWEEP) - - t0 = time.time() - for i, v in enumerate(x_vals): - val = jnp.float32(v) - loss, grad = loss_and_grad(val) - losses[i] = float(loss) - ad_grads[i] = float(grad) - - fd = (float(loss_jit(jnp.float32(v + fd_eps))) - - float(loss_jit(jnp.float32(v - fd_eps)))) / (2 * fd_eps) - fd_grads[i] = fd - - print(f" Sweep done ({time.time() - t0:.1f}s)") - - # --- Plot --- - unit_str = f' ({unit})' if unit else '' - truth_label = f'Truth = {truth_val:.4g}' - fig, axes = plt.subplots(1, 2, figsize=(13, 5)) - - axes[0].plot(x_vals, losses, 'b-', lw=1.5) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, - label=truth_label) - axes[0].set_xlabel(f'{param_name}{unit_str}', fontsize=12) - axes[0].set_ylabel('Sobolev Geomean Log1p Loss', fontsize=12) - axes[0].set_title('Loss Landscape', fontsize=13) - axes[0].legend(fontsize=10) - axes[0].grid(True, alpha=0.3) - - axes[1].plot(x_vals, ad_grads, 'r-', lw=1.5, label='Autodiff') - axes[1].plot(x_vals, fd_grads, 'b--', lw=1.5, alpha=0.7, - label=f'FD (eps={fd_eps:.2g})') - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, - label=truth_label) - axes[1].set_xlabel(f'{param_name}{unit_str}', fontsize=12) - axes[1].set_ylabel(f'dLoss/d({param_name})', fontsize=12) - axes[1].set_title('Gradient (Autodiff vs FD)', fontsize=13) - axes[1].legend(fontsize=10) - axes[1].grid(True, alpha=0.3) - - fig.suptitle( - f'Detector param: {param_name} — muon {N_SEGMENTS} seg, ' - f'EMB recomb, Sobolev geomean log1p', - fontsize=14, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'detector_emb_surface_{param_name}.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f" Saved {fname}\n") - - print("Done!") - - -if __name__ == '__main__': - main() diff --git a/closure/muon/optimization_A.npz b/closure/muon/optimization_A.npz deleted file mode 100644 index 390f88e..0000000 Binary files a/closure/muon/optimization_A.npz and /dev/null differ diff --git a/closure/muon/surfaces.py b/closure/muon/surfaces.py deleted file mode 100644 index 08ddce5..0000000 --- a/closure/muon/surfaces.py +++ /dev/null @@ -1,350 +0,0 @@ -""" -Loss and gradient surface plots for differentiable muon simulation. - -For each of 6 muon parameters (x, y, z, theta, phi, energy), sweeps the -parameter while holding the others fixed at truth and plots: - - Loss landscape - - Gradient comparison (autodiff vs finite-difference) - -Supports loss types: MSE, Blur MSE, Sobolev Sum, Sobolev Geomean, -Sobolev Geomean Log1p. - -Run from project root: - python3 closure/muon/surfaces.py --loss mse - python3 closure/muon/surfaces.py --loss blur - python3 closure/muon/surfaces.py --loss all -""" - -import os, argparse - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import ( - blur_mse_loss, make_spectral_weight, DEFAULT_BLUR_SIGMAS, - sobolev_loss, sobolev_loss_geomean, sobolev_loss_geomean_log1p, - make_sobolev_weight, -) - -from tools.particle_generator import ( - load_dedx_table_jax, - generate_muon_segments, - build_muon_forward, -) - -# ============================================================================= -# Configuration -# ============================================================================= - -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 - -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 2 -TRUTH_ENERGY = 200.0 - -PLANES = [0, 1, 2] -N_SWEEP = 120 - -FD_EPS_POS = 0.5 -FD_EPS_ANGLE = 0.01 -FD_EPS_ENERGY = 0.5 - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -PARAM_ORDER = ['x', 'y', 'z', 'theta', 'phi', 'energy'] -PARAM_IDX = {n: i for i, n in enumerate(PARAM_ORDER)} - -SWEEP_CONFIGS = { - 'energy': {'range': (100.0, 280.0), 'truth': TRUTH_ENERGY, 'unit': 'MeV', 'eps': FD_EPS_ENERGY}, - 'x': {'range': (-700, -300), 'truth': TRUTH_X, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'y': {'range': (-400, 400), 'truth': TRUTH_Y, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'z': {'range': (-200, 400), 'truth': TRUTH_Z, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'theta': {'range': (0.3, 1.2), 'truth': TRUTH_THETA, 'unit': 'rad', 'eps': FD_EPS_ANGLE}, - 'phi': {'range': (0.8, 2.4), 'truth': TRUTH_PHI, 'unit': 'rad', 'eps': FD_EPS_ANGLE}, -} - - -# ============================================================================= -# Main -# ============================================================================= - -def main(loss_types=None): - if loss_types is None: - loss_types = ['mse', 'blur'] - - print("=" * 60, flush=True) - print("MUON GRADIENT SURFACE ANALYSIS", flush=True) - print(f"Loss types: {', '.join(loss_types)}", flush=True) - print("=" * 60, flush=True) - - # --- Setup --- - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - # --- Truth signals --- - truth_args = ( - jnp.float32(TRUTH_X), jnp.float32(TRUTH_Y), jnp.float32(TRUTH_Z), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), jnp.float32(TRUTH_ENERGY), - ) - - def sim_forward(x, y, z, theta, phi, energy): - pos, de = generate_muon_segments( - energy, jnp.array([x, y, z]), theta, phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - return forward(pos, de) - - print("Compiling sim_forward...", flush=True) - t0 = time.time() - sim_jit = jax.jit(sim_forward) - truth_signals = sim_jit(*truth_args) - for s in truth_signals: - jax.block_until_ready(s) - print(f" compiled ({time.time()-t0:.1f}s)", flush=True) - - target_sigs = {p: truth_signals[p] for p in PLANES} - - ALL = (0, 1, 2, 3, 4, 5) - - # --- MSE --- - if 'mse' in loss_types: - def mse_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - loss = 0.0 - for p in PLANES: - loss = loss + jnp.mean((sigs[p] - target_sigs[p]) ** 2) - return loss - - print("\nCompiling MSE loss...", flush=True) - t0 = time.time() - mse_jit = jax.jit(mse_loss) - _ = mse_jit(*truth_args) - print(f" MSE fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - mse_vg = jax.jit(jax.value_and_grad(mse_loss, argnums=ALL)) - _ = mse_vg(*truth_args) - print(f" MSE fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('MSE', mse_jit, mse_vg, truth_args) - - # --- Blur MSE (spectral) --- - if 'blur' in loss_types: - planes_tuple = tuple(PLANES) - - # Precompute spectral weights for each plane shape - print("\nPrecomputing spectral weights...", flush=True) - spec_weights = {} - for p in PLANES: - H, W = truth_signals[p].shape - spec_weights[p] = make_spectral_weight(H, W, DEFAULT_BLUR_SIGMAS) - # Build full 6-element tuple (only PLANES entries used) - sw_tuple = tuple( - spec_weights[i] if i in spec_weights - else jnp.zeros((1, 1)) - for i in range(6) - ) - - def blur_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - return blur_mse_loss(sigs, truth_signals, sw_tuple, planes=planes_tuple) - - print("Compiling Blur MSE loss...", flush=True) - t0 = time.time() - blur_jit = jax.jit(blur_loss) - _ = blur_jit(*truth_args) - print(f" Blur fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - blur_vg = jax.jit(jax.value_and_grad(blur_loss, argnums=ALL)) - _ = blur_vg(*truth_args) - print(f" Blur fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('Blur', blur_jit, blur_vg, truth_args) - - # --- Sobolev: shared spectral weights for sum and geomean (s=2.0) --- - if 'sobolev_sum' in loss_types or 'sobolev_geomean' in loss_types: - planes_tuple = tuple(PLANES) - - print("\nPrecomputing Sobolev spectral weights (s=2.0)...", flush=True) - sob_weights = {} - for p in PLANES: - H, W = truth_signals[p].shape - sob_weights[p] = make_sobolev_weight(H, W, s=2.0) - sob_tuple = tuple( - sob_weights[i] if i in sob_weights - else jnp.zeros((1, 1)) - for i in range(6) - ) - - # --- Sobolev Sum --- - if 'sobolev_sum' in loss_types: - def sob_sum_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - return sobolev_loss(sigs, truth_signals, sob_tuple, planes=planes_tuple) - - print("\nCompiling Sobolev Sum loss...", flush=True) - t0 = time.time() - sob_sum_jit = jax.jit(sob_sum_loss) - _ = sob_sum_jit(*truth_args) - print(f" Sobolev Sum fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - sob_sum_vg = jax.jit(jax.value_and_grad(sob_sum_loss, argnums=ALL)) - _ = sob_sum_vg(*truth_args) - print(f" Sobolev Sum fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('Sobolev_Sum', sob_sum_jit, sob_sum_vg, truth_args) - - # --- Sobolev Geomean --- - if 'sobolev_geomean' in loss_types: - def sob_geo_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - return sobolev_loss_geomean(sigs, truth_signals, sob_tuple, planes=planes_tuple) - - print("\nCompiling Sobolev Geomean loss...", flush=True) - t0 = time.time() - sob_geo_jit = jax.jit(sob_geo_loss) - _ = sob_geo_jit(*truth_args) - print(f" Sobolev Geomean fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - sob_geo_vg = jax.jit(jax.value_and_grad(sob_geo_loss, argnums=ALL)) - _ = sob_geo_vg(*truth_args) - print(f" Sobolev Geomean fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('Sobolev_Geomean', sob_geo_jit, sob_geo_vg, truth_args) - - # --- Sobolev Geomean Log1p (s=1.5, matching optimization settings) --- - if 'sobolev_geomean_log1p' in loss_types: - planes_tuple = tuple(PLANES) - - print("\nPrecomputing Sobolev spectral weights (s=1.5)...", flush=True) - sob15_weights = {} - for p in PLANES: - H, W = truth_signals[p].shape - sob15_weights[p] = make_sobolev_weight(H, W, s=1.5) - sob15_tuple = tuple( - sob15_weights[i] if i in sob15_weights - else jnp.zeros((1, 1)) - for i in range(6) - ) - - def sob_log1p_loss(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - return sobolev_loss_geomean_log1p(sigs, truth_signals, sob15_tuple, - planes=planes_tuple) - - print("Compiling Sobolev Geomean Log1p loss...", flush=True) - t0 = time.time() - sob_log1p_jit = jax.jit(sob_log1p_loss) - _ = sob_log1p_jit(*truth_args) - print(f" Sobolev Geomean Log1p fwd ({time.time()-t0:.1f}s)", flush=True) - - t0 = time.time() - sob_log1p_vg = jax.jit(jax.value_and_grad(sob_log1p_loss, argnums=ALL)) - _ = sob_log1p_vg(*truth_args) - print(f" Sobolev Geomean Log1p fwd+bwd ({time.time()-t0:.1f}s)", flush=True) - - _run_sweeps('Sobolev_Geomean_Log1p', sob_log1p_jit, sob_log1p_vg, truth_args) - - print("\nDone!", flush=True) - - -def _run_sweeps(loss_name, loss_jit, loss_vg, truth_args): - """Run parameter sweeps and save plots for one loss type.""" - - prefix = { - 'MSE': 'mse', 'Blur': 'blur', - 'Sobolev_Sum': 'sobolev_sum_s2.0_smooth0.2', - 'Sobolev_Geomean': 'sobolev_geomean_s2.0_smooth0.2', - 'Sobolev_Geomean_Log1p': 'sobolev_geomean_log1p_s1.5_smooth0.2', - }[loss_name] - - for pname, cfg in SWEEP_CONFIGS.items(): - lo, hi = cfg['range'] - truth_val = cfg['truth'] - unit = cfg['unit'] - eps = cfg['eps'] - pidx = PARAM_IDX[pname] - - x_vals = np.linspace(lo, hi, N_SWEEP) - print(f"\n {loss_name} — {pname} [{lo}, {hi}] {unit}", flush=True) - - def _args(val): - a = list(truth_args) - a[pidx] = jnp.float32(val) - return tuple(a) - - # Loss + autodiff gradient - t0 = time.time() - losses = np.empty(N_SWEEP) - ad_grads = np.empty(N_SWEEP) - for i, v in enumerate(x_vals): - loss, grads = loss_vg(*_args(v)) - losses[i] = float(loss) - ad_grads[i] = float(grads[pidx]) - - # Finite-diff gradient - fd_grads = np.array([ - (float(loss_jit(*_args(v + eps))) - - float(loss_jit(*_args(v - eps)))) / (2 * eps) - for v in x_vals - ]) - print(f" done ({time.time()-t0:.1f}s)", flush=True) - - # --- Plot --- - truth_label = f'Truth {pname}={truth_val:.2f}' - fig, axes = plt.subplots(1, 2, figsize=(12, 5)) - - axes[0].plot(x_vals, losses, 'b-', lw=1.5) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, label=truth_label) - axes[0].set_xlabel(f'{pname} ({unit})') - axes[0].set_ylabel(f'{loss_name} Loss') - axes[0].set_title('Loss Landscape') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - - axes[1].plot(x_vals, ad_grads, 'r-', lw=1.5, label='Autodiff') - axes[1].plot(x_vals, fd_grads, 'b--', lw=1.5, alpha=0.7, label=f'FD (eps={eps})') - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, label=truth_label) - axes[1].set_xlabel(f'{pname} ({unit})') - axes[1].set_ylabel(f'd{loss_name}/d{pname}') - axes[1].set_title('Gradient (Autodiff vs FD)') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - - fig.suptitle( - f'{loss_name} — varying {pname} (muon, {N_SEGMENTS} seg, summed U+V+Y)', - fontsize=14, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'{prefix}_surface_{pname}.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f" Saved {fname}", flush=True) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='Muon gradient surface analysis') - parser.add_argument( - '--loss', type=str, default='all', - choices=['mse', 'blur', 'sobolev_sum', 'sobolev_geomean', - 'sobolev_geomean_log1p', 'all'], - help='Which loss to run (default: all)', - ) - args = parser.parse_args() - if args.loss == 'all': - main(['mse', 'blur', 'sobolev_sum', 'sobolev_geomean', - 'sobolev_geomean_log1p']) - else: - main([args.loss]) diff --git a/closure/muon/surfaces_perplane.py b/closure/muon/surfaces_perplane.py deleted file mode 100644 index 9460782..0000000 --- a/closure/muon/surfaces_perplane.py +++ /dev/null @@ -1,219 +0,0 @@ -"""Per-plane Sobolev gradient surfaces. - -Shows loss and gradient for each plane (U, V, Y) individually plus the sum. -Sim is compiled once; per-plane losses are thin wrappers. - -Run from project root: - python3 closure/muon/surfaces_perplane.py -""" - -import os - -import jax -import jax.numpy as jnp -import numpy as np -import matplotlib.pyplot as plt -import time - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.losses import sobolev_loss, make_sobolev_weight - -from tools.particle_generator import ( - load_dedx_table_jax, - generate_muon_segments, - build_muon_forward, -) - -# ============================================================================= -# Configuration -# ============================================================================= - -N_SEGMENTS = 2800 -STEP_SIZE_MM = 0.5 - -TRUTH_X, TRUTH_Y, TRUTH_Z = -500.0, 0.0, 100.0 -TRUTH_THETA, TRUTH_PHI = np.pi / 4, np.pi / 2 -TRUTH_ENERGY = 200.0 - -PLANES = [0, 1, 2] -PLANE_NAMES = {0: 'U', 1: 'V', 2: 'Y'} -PLANE_COLORS = {0: 'C0', 1: 'C1', 2: 'C2'} -N_SWEEP = 40 -FD_EPS_POS = 0.5 -FD_EPS_ANGLE = 0.01 -FD_EPS_ENERGY = 0.5 - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -PARAM_ORDER = ['x', 'y', 'z', 'theta', 'phi', 'energy'] -PARAM_IDX = {n: i for i, n in enumerate(PARAM_ORDER)} - -SWEEP_CONFIGS = { - 'x': {'range': (-700, -300), 'truth': TRUTH_X, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'y': {'range': (-400, 400), 'truth': TRUTH_Y, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'z': {'range': (-200, 400), 'truth': TRUTH_Z, 'unit': 'mm', 'eps': FD_EPS_POS}, - 'theta': {'range': (0.3, 1.2), 'truth': TRUTH_THETA, 'unit': 'rad', 'eps': FD_EPS_ANGLE}, - 'phi': {'range': (0.8, 2.4), 'truth': TRUTH_PHI, 'unit': 'rad', 'eps': FD_EPS_ANGLE}, - 'energy': {'range': (100.0, 280.0), 'truth': TRUTH_ENERGY, 'unit': 'MeV', 'eps': FD_EPS_ENERGY}, -} - -ALL = (0, 1, 2, 3, 4, 5) - - -def main(): - print("=" * 60, flush=True) - print("PER-PLANE SOBOLEV GRADIENT SURFACES", flush=True) - print("=" * 60, flush=True) - - # --- Setup --- - log_T, dedx = load_dedx_table_jax() - detector_config = generate_detector('config/cubic_wireplane_config.yaml') - sim = DetectorSimulator(detector_config, differentiable=True, n_segments=N_SEGMENTS) - forward = build_muon_forward(sim, N_SEGMENTS, STEP_SIZE_MM) - - # --- Truth signals --- - truth_args = ( - jnp.float32(TRUTH_X), jnp.float32(TRUTH_Y), jnp.float32(TRUTH_Z), - jnp.float32(TRUTH_THETA), jnp.float32(TRUTH_PHI), jnp.float32(TRUTH_ENERGY), - ) - - def sim_forward(x, y, z, theta, phi, energy): - pos, de = generate_muon_segments( - energy, jnp.array([x, y, z]), theta, phi, - STEP_SIZE_MM, N_SEGMENTS, log_T, dedx, - ) - return forward(pos, de) - - print("Compiling sim_forward...", flush=True) - t0 = time.time() - sim_jit = jax.jit(sim_forward) - truth_signals = sim_jit(*truth_args) - for s in truth_signals: - jax.block_until_ready(s) - print(f" sim compiled ({time.time()-t0:.1f}s)", flush=True) - - # --- Sobolev weights --- - print("\nPrecomputing Sobolev weights...", flush=True) - sob_weights = {} - for p in PLANES: - H, W = truth_signals[p].shape - sob_weights[p] = make_sobolev_weight(H, W) - sob_tuple = tuple( - sob_weights[i] if i in sob_weights else jnp.zeros((1, 1)) - for i in range(6) - ) - - # --- Per-plane loss functions (thin wrappers over same sim) --- - def make_loss(plane_tuple): - def loss_fn(x, y, z, theta, phi, energy): - sigs = sim_forward(x, y, z, theta, phi, energy) - return sobolev_loss(sigs, truth_signals, sob_tuple, planes=plane_tuple) - return loss_fn - - # Compile per-plane and sum - print("Compiling per-plane losses...", flush=True) - loss_fns = {} # name -> (jit_loss, jit_vg) - for p in PLANES: - name = PLANE_NAMES[p] - fn = make_loss((p,)) - t0 = time.time() - fn_jit = jax.jit(fn) - vg_jit = jax.jit(jax.value_and_grad(fn, argnums=ALL)) - _ = fn_jit(*truth_args) - _ = vg_jit(*truth_args) - loss_fns[name] = (fn_jit, vg_jit) - print(f" {name} compiled ({time.time()-t0:.1f}s)", flush=True) - - # Sum - fn_sum = make_loss(tuple(PLANES)) - t0 = time.time() - fn_sum_jit = jax.jit(fn_sum) - vg_sum_jit = jax.jit(jax.value_and_grad(fn_sum, argnums=ALL)) - _ = fn_sum_jit(*truth_args) - _ = vg_sum_jit(*truth_args) - loss_fns['Sum'] = (fn_sum_jit, vg_sum_jit) - print(f" Sum compiled ({time.time()-t0:.1f}s)", flush=True) - - # --- Sweeps --- - ordered = ['U', 'V', 'Y', 'Sum'] - colors = {'U': 'C0', 'V': 'C1', 'Y': 'C2', 'Sum': 'k'} - lws = {'U': 1.5, 'V': 1.5, 'Y': 1.5, 'Sum': 2.5} - - for pname, cfg in SWEEP_CONFIGS.items(): - lo, hi = cfg['range'] - truth_val = cfg['truth'] - unit = cfg['unit'] - eps = cfg['eps'] - pidx = PARAM_IDX[pname] - - x_vals = np.linspace(lo, hi, N_SWEEP) - print(f"\n {pname} [{lo}, {hi}] {unit}", flush=True) - - def _args(val): - a = list(truth_args) - a[pidx] = jnp.float32(val) - return tuple(a) - - # Collect per-plane data - t0 = time.time() - data = {} - for name in ordered: - fn_jit, vg_jit = loss_fns[name] - losses = np.empty(N_SWEEP) - ad_grads = np.empty(N_SWEEP) - for i, v in enumerate(x_vals): - loss, grads = vg_jit(*_args(v)) - losses[i] = float(loss) - ad_grads[i] = float(grads[pidx]) - data[name] = (losses, ad_grads) - print(f" done ({time.time()-t0:.1f}s)", flush=True) - - # --- Plot: 2 panels --- - fig, axes = plt.subplots(1, 2, figsize=(14, 5.5)) - - # Left: loss per plane - for name in ordered: - losses, _ = data[name] - axes[0].plot(x_vals, losses, color=colors[name], lw=lws[name], - ls='-' if name != 'Sum' else '-', - alpha=0.8 if name != 'Sum' else 1.0, - label=name) - axes[0].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth={truth_val:.2f}') - axes[0].set_xlabel(f'{pname} ({unit})') - axes[0].set_ylabel('Sobolev Loss') - axes[0].set_title('Loss per Plane') - axes[0].legend() - axes[0].grid(True, alpha=0.3) - - # Right: gradient per plane - for name in ordered: - _, ad_grads = data[name] - axes[1].plot(x_vals, ad_grads, color=colors[name], lw=lws[name], - alpha=0.8 if name != 'Sum' else 1.0, - label=name) - axes[1].axhline(0, color='k', ls='-', lw=0.5) - axes[1].axvline(truth_val, color='green', ls='--', lw=2, - label=f'Truth={truth_val:.2f}') - axes[1].set_xlabel(f'{pname} ({unit})') - axes[1].set_ylabel(f'dLoss/d{pname}') - axes[1].set_title('Gradient per Plane') - axes[1].legend() - axes[1].grid(True, alpha=0.3) - - fig.suptitle( - f'Sobolev per-plane — varying {pname} (U, V, Y + Sum)', - fontsize=14, fontweight='bold', - ) - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'sobolev_perplane_{pname}.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f" Saved {fname}", flush=True) - - print("\nDone!", flush=True) - - -if __name__ == '__main__': - main() diff --git a/closure/segments/SWEEP_RESULTS.md b/closure/segments/SWEEP_RESULTS.md deleted file mode 100644 index 3c2d4fb..0000000 --- a/closure/segments/SWEEP_RESULTS.md +++ /dev/null @@ -1,202 +0,0 @@ -# Full Closure Sweep Results - -Event: `mpvmpr_20.h5`, event 0 (39,890 truth segments, 926.44 MeV total dE) -Optimizer: 10,000 segments, Sobolev geomean log1p loss (s=1.5) -Recombination: `modified_box` (consistent between truth sim, optimizer, relocation) -Optimizer dx: 0.5mm (build_forward default in sweep.py) -Truth dx: variable (~0.1mm from HDF5, NOT forced) - -## 1. lr_e_mult Sweep — Baseline (no relocation, no L1, no noise) - -Fixed: lr=0.5, decay_rate=0.9995, 1000 steps, baseline mode - -| lr_e_mult | Final Loss | dE_ratio | Dead | Notes | -|-----------|-----------|----------|------|-------| -| 0.005 | 0.157 | 1.123 | 4551 | Best baseline | -| 0.018 | 0.308 | 1.206 | 5418 | | -| 0.05 | 0.475 | 1.350 | 6354 | Energy overshoots badly | - -**Finding:** Smaller lr_e_mult consistently better in baseline. Energy step at 0.005 = 0.0025 MeV/step (2.7% of mean dE). All show energy drift upward (dE_ratio > 1) without L1. - -## 2. lr_e_mult Sweep — Full Mode (relocation, no L1, no noise) - -Fixed: lr=0.5, decay_rate=0.9995, reloc_every=25, max_reloc=100, 1500 steps - -| lr_e_mult | Final Loss | dE_ratio | Dead | Steps to die (~) | -|-----------|-----------|----------|------|-----------------| -| 0.001 | 0.073 | 1.008 | 225 | ~160 | -| 0.002 | 0.048 | 1.021 | 941 | ~80 | -| 0.003 | **0.038** | 1.035 | 1382 | ~53 | -| 0.005 | 0.039 | 1.055 | 1944 | ~33 | -| 0.01 | 0.042 | 1.084 | 2448 | ~16 | -| 0.018 | 0.067 | 1.104 | 2930 | ~9 | - -**Finding:** Minimum at lr_e_mult=0.003-0.005. Below 0.003, relocation starves (segments die too slowly). Above 0.005, energy convergence degrades. The optimal balances energy convergence speed vs relocation throughput. - -**"Steps to die"** = mean_dE / (lr * lr_e_mult) = 0.093 / (0.5 * lr_e_mult). This is how many steps a useless segment takes to reach death_thresh=0.012 from mean dE, assuming the gradient consistently says "decrease energy." - -## 3. Ad-hoc Runs (earlier in session, less controlled) - -These used various settings before the systematic sweep. Truth dx was variable (~0.1mm), optimizer dx=0.5mm, some used EMB recombination (mismatch). - -### Baseline runs (no reloc, no L1, no noise) -| lr | decay | lr_e_mult | Steps | Loss | dE_ratio | Notes | -|----|-------|-----------|-------|------|----------|-------| -| 0.3 | 0.9999 | 1.0 | 1000 | 1.92 | 3.492 | Energy blowup — lr_e_mult=1.0 catastrophic | -| 0.3 | 0.9999 | 1.0 | 2000 | 0.86 | 3.492 | Same, more steps | -| 0.3 | 0.9999 | 0.03 | 1000 | 0.34 | 1.215 | First fix — energy controlled | - -### Full mode runs (reloc + L1 + noise, various settings) -| lr | decay | e_mult | noise | L1 | reloc | Steps | Loss | dE_ratio | Notes | -|----|-------|--------|-------|-----|-------|-------|------|----------|-------| -| 0.3 | 0.9999 | 0.03 | 0.05 | 0.001 | 50/10k | 1000 | 85.1 | 5.349 | Reloc spikes + energy chaos | -| 0.3 | 0.9999 | 0.03 | 0.1 | 0.0002 | 300/10k | 2000 | 0.027 | 0.953 | Large spikes every 300 steps | -| 0.5 | 0.9995 | 0.018 | 0.1 | 0.0002 | 300/10k | 2000 | 0.017 | 0.949 | Higher lr helps | -| 0.5 | 0.9995 | 0.018 | 0.1 | 0.0002 | 25/100 | 2000 | 0.024 | 0.993 | Smooth curve, slow recycling | -| 0.5 | 0.9995 | 0.018 | 0.0 | 0.0002 | 25/100 | 2000 | 0.023 | 1.005 | No noise = slightly better | -| 0.5 | 0.9995 | 0.018 | 1.0 | 0.0002 | 25/100 | 2000 | 0.040 | 0.991 | High noise hurts | -| 0.5 | 0.9995 | 0.018 | 0.3 | 0.0002 | 25/100 | 2000 | 0.024 | 0.993 | Mid noise ≈ no noise | -| 0.5 | 0.9995 | 0.018 | 0.3 | 0.0001 | 25/100 | 3000 | 0.015 | 0.958 | More steps helps, L1 over-drains | -| 0.5 | 0.9995 | 0.018 | 0.3 | 0.0001 | 25/100 | 3000 | 0.010 | 0.981 | + recomb=modified_box (consistency fix) | - -### Energy-weighted donor experiments (reverted — random is better) -| Weighting | lr_e_mult | L1 | Steps | Loss | dE_ratio | Notes | -|-----------|-----------|-----|-------|------|----------|-------| -| linear | 0.018 | 0.0001 | 2000 | 0.016 | 0.895 | Over-drains, fights optimizer | -| sqrt | 0.018 | 0.00005 | 2000 | 0.044 | 0.897 | Still over-drains | - -## 4. Key Findings - -### Recombination model consistency -- Default recomb_model=None gives EMB for DetectorSimulator but modified_box for relocation split -- EMB is angular-dependent but SegmentData has no angles — systematic mismatch -- Fix: always pass `--recomb modified_box` -- Impact: 33% loss improvement (0.015 → 0.010) when fixed - -### dx mismatch -- Truth HDF5 has variable dx (mean=0.098mm, median=0.1mm, 131 segments with dx=0) -- Optimizer uses fixed dx (0.5mm default in build_forward, changed to 0.1mm in full_closure.py) -- With matched dx, forward passes are identical (loss=0.000000) -- dE scaling does NOT preserve Q through nonlinear recombination: e_scale=3.99 gives signal ratio 0.69 (dx=0.1mm) or 1.48 (dx=0.5mm) -- sweep.py uses dx=0.5mm (build_forward default), full_closure.py uses dx=0.1mm - -### Noise -- Tested noise_lr = 0, 0.1, 0.3, 1.0 -- No benefit at any scale for closure test -- Sobolev loss provides smooth gradients — no local minima to escape - -### Relocation spikes -- Spike magnitude scales linearly with max_reloc count -- max_reloc=100 gives ~1x spike (invisible), 500 gives 2.5x, 10000 gives 54x -- NOT correlated with which donors are selected -- Cause: energy split disrupts many segments simultaneously -- Adam moment zeroing contributes to recovery time but not spike magnitude - -### L1 drain -- Purpose: push near-dead segments below death_thresh for relocation -- Global drain is harmful — over-drains at long runs -- With relocation + proper lr_e_mult, L1=0 works (sweep results above) -- If needed, L1 ≈ death_thresh / (reloc_every * 2) to target near-dead only - -### Physical scales -- Wire pitch: 3mm -- Position step at lr=0.5: 0.5mm/step (17% of wire pitch) -- Mean dE: 0.093 MeV (with e_scale=3.99) -- Energy step at lr_e_mult=0.003: 0.0015 MeV/step (1.6% of mean dE) -- Death threshold: 0.012 MeV -- Init position jitter: 100mm -- Response kernel width: ~5-10 wires (~15-30mm) - -## 5. Current Best Settings - -From systematic sweep (Section 2): -``` -lr=0.5, decay_rate=0.9995, lr_e_mult=0.003 -noise_lr=0.0, l1=0.0 -reloc_every=25, max_reloc=100 -warmup=300, recomb=modified_box -``` -Loss=0.038 at 1500 steps, dE_ratio=1.035, 1382 dead. - -## 6. LR x Decay Sweep (systematic, sweep script) - -Fixed: lr_e_mult=0.003, n_seg=10000, reloc 25/100, no noise/L1, warmup=300, 1500 steps, full mode - -| Config | Loss | dE_ratio | Dead | -|--------|------|----------|------| -| lr=0.3, d=0.9995 | 0.058 | 1.039 | 1659 | -| lr=0.5, d=0.9995 | 0.038 | 1.035 | 1393 | -| lr=0.7, d=0.999 | 0.040 | 1.034 | 1207 | -| **lr=1.0, d=0.999** | **0.030** | 1.031 | 1138 | -| lr=0.7, d=0.9995 | 0.031 | 1.035 | 1277 | -| lr=1.0, d=0.9995 | 0.033 | 1.031 | 1422 | - -**Finding:** Higher initial lr with faster decay wins. lr=1.0/d=0.999 best (0.030). The fast initial convergence more than compensates for aggressive cooling. - -## 7. Warmup Sweep (systematic) - -Fixed: lr=0.5, d=0.9995, lr_e_mult=0.003, n_seg=10000, 1500 steps, full mode - -| Warmup | Loss | dE_ratio | Dead | Relocs | -|--------|------|----------|------|--------| -| **100** | **0.034** | 1.026 | 1020 | 5600 | -| 200 | 0.035 | 1.024 | 1178 | 5200 | -| 300 | 0.038 | 1.034 | 1351 | 4800 | -| 500 | 0.051 | 1.037 | 1796 | 4000 | - -**Finding:** Shorter warmup is better. warmup=100 wins. Earlier relocation = more total redistribution time. - -## 8. Step Count Sweep (best config) - -Config: lr=1.0, d=0.999, lr_e_mult=0.003, warmup=100, reloc 25/100, no noise/L1, full mode - -| Steps | Loss | dE_ratio | Dead | Time | -|-------|------|----------|------|------| -| 500 | 0.177 | 1.068 | 3038 | 121s | -| 1000 | 0.045 | 1.051 | 2085 | 234s | -| 1500 | 0.026 | 1.030 | 744 | 355s | -| 2000 | 0.015 | 1.020 | 25 | 479s | -| 3000 | **0.012** | 1.015 | 6 | 729s | - -**Finding:** Loss scales roughly as 1/steps. No plateau at 3000 steps — still improving. All dead segments recycled by step ~1700. - -## 9. Current Best Configuration - -``` -lr=1.0, decay_rate=0.999, lr_e_mult=0.003 -warmup=100, noise_lr=0.0, l1=0.0 -reloc_every=25, max_reloc=100 -recomb=modified_box -``` -At 3000 steps: loss=0.012, dE_ratio=1.015, dead=6. - -## 10. Noise Sweep (best config: lr=1.0, d=0.999) - -Fixed: lr_e_mult=0.003, warmup=100, reloc 25/100, no L1, 1500 steps, full mode - -| noise_lr | Loss | dE_ratio | Dead | -|----------|------|----------|------| -| 0.0 | 0.027 | 1.032 | 744 | -| 0.1 | 0.024 | 1.024 | 657 | -| **0.3** | **0.022** | 1.013 | 386 | - -**Finding:** Noise HELPS at lr=1.0 (unlike at lr=0.5 where it didn't). The fast lr decay (0.999) annihilates noise by step 1500 (noise=0.07mm), so it only affects early exploration. Noise helps segments explore neighboring wires during the high-lr phase. - -## 11. Updated Best Configuration - -``` -lr=1.0, decay=0.999, lr_e_mult=0.003 -warmup=100, noise_lr=0.3, l1=0.0 -reloc_every=25, max_reloc=100 -recomb=modified_box -``` -At 1500 steps: loss=0.022, dE_ratio=1.013. -At 3000 steps (noise=0, previous best): loss=0.012, dE_ratio=1.015. -Expected at 3000 steps with noise=0.3: likely <0.012. - -## 12. Not Yet Tested -- n_seg other than 10000 -- Sobolev s parameter (always 1.5) -- Forced truth dx (to eliminate dx mismatch) -- Different events (always event 0) -- reloc_every / max_reloc at best lr/decay diff --git a/closure/segments/diff_step_0009.png b/closure/segments/diff_step_0009.png deleted file mode 100644 index 50e6bc3..0000000 Binary files a/closure/segments/diff_step_0009.png and /dev/null differ diff --git a/closure/segments/diff_step_0049.png b/closure/segments/diff_step_0049.png deleted file mode 100644 index d60f3bd..0000000 Binary files a/closure/segments/diff_step_0049.png and /dev/null differ diff --git a/closure/segments/diff_step_0099.png b/closure/segments/diff_step_0099.png deleted file mode 100644 index b8fbafd..0000000 Binary files a/closure/segments/diff_step_0099.png and /dev/null differ diff --git a/closure/segments/diff_step_0100.png b/closure/segments/diff_step_0100.png deleted file mode 100644 index 42c37fa..0000000 Binary files a/closure/segments/diff_step_0100.png and /dev/null differ diff --git a/closure/segments/diff_step_0199.png b/closure/segments/diff_step_0199.png deleted file mode 100644 index 7019909..0000000 Binary files a/closure/segments/diff_step_0199.png and /dev/null differ diff --git a/closure/segments/diff_step_0500.png b/closure/segments/diff_step_0500.png deleted file mode 100644 index a2c1383..0000000 Binary files a/closure/segments/diff_step_0500.png and /dev/null differ diff --git a/closure/segments/diff_step_0999.png b/closure/segments/diff_step_0999.png deleted file mode 100644 index b494e79..0000000 Binary files a/closure/segments/diff_step_0999.png and /dev/null differ diff --git a/closure/segments/diff_step_1000.png b/closure/segments/diff_step_1000.png deleted file mode 100644 index f0ffc94..0000000 Binary files a/closure/segments/diff_step_1000.png and /dev/null differ diff --git a/closure/segments/diff_step_1500.png b/closure/segments/diff_step_1500.png deleted file mode 100644 index ea89850..0000000 Binary files a/closure/segments/diff_step_1500.png and /dev/null differ diff --git a/closure/segments/diff_step_1999.png b/closure/segments/diff_step_1999.png deleted file mode 100644 index 915dafd..0000000 Binary files a/closure/segments/diff_step_1999.png and /dev/null differ diff --git a/closure/segments/full_closure_50000seg_baseline_progress.png b/closure/segments/full_closure_50000seg_baseline_progress.png deleted file mode 100644 index 20813a4..0000000 Binary files a/closure/segments/full_closure_50000seg_baseline_progress.png and /dev/null differ diff --git a/closure/segments/full_closure_50000seg_full_progress.png b/closure/segments/full_closure_50000seg_full_progress.png deleted file mode 100644 index 823e0c0..0000000 Binary files a/closure/segments/full_closure_50000seg_full_progress.png and /dev/null differ diff --git a/closure/segments/full_closure_5000seg_baseline_progress.png b/closure/segments/full_closure_5000seg_baseline_progress.png deleted file mode 100644 index dbc2bcc..0000000 Binary files a/closure/segments/full_closure_5000seg_baseline_progress.png and /dev/null differ diff --git a/closure/segments/plot_progression.py b/closure/segments/plot_progression.py deleted file mode 100644 index f019318..0000000 --- a/closure/segments/plot_progression.py +++ /dev/null @@ -1,195 +0,0 @@ -""" -Progression plot v3: loss, Q ratio, U/V/Y signals, dE waterfall with dead row. - -Waterfall: x=step, y=dE bins with bottom row = dead count, properly labeled. - -Usage: - python3 closure_analysis_full/sweeps/plot_progression_v3.py -""" - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib.colors as mcolors -from matplotlib.gridspec import GridSpec -import os - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -DATA_PATH = os.path.join(OUT_DIR, 'best_final.npz') -PLANE_NAMES = ['east_U', 'east_V', 'east_Y', 'west_U', 'west_V', 'west_Y'] -DEATH_THRESH = 0.012 # MeV -ALPHA_RECOMB = 0.93 -W_ION = 23.6e-6 - - -def main(): - print("Loading data...") - data = np.load(DATA_PATH, allow_pickle=True) - - losses = data['losses'] - active_planes = list(data['active_planes']) - n_de_hist = int(data['n_de_hist']) - de_history_steps = data['de_history_steps'] - n_signal_snapshots = int(data['n_signal_snapshots']) - signal_steps = data['signal_steps'] - truth_total_de = float(data['truth_total_de']) - B_eff = float(data['B_eff']) - dx_cm = float(data['dx_mm']) / 10.0 - - # Reconstruct dE history - de_history = [] - for i in range(n_de_hist): - alive_de = data[f'de_hist_{i}_alive'] - n_dead = int(data[f'de_hist_{i}_dead']) - de_history.append((alive_de, n_dead)) - - # Load profiles - truth_profiles = {} - sim_profiles = {} - for p in active_planes: - truth_profiles[p] = data[f'truth_profile_{p}'] - sim_profiles[p] = [data[f'sig_profile_{p}_{j}'] for j in range(n_signal_snapshots)] - - # Compute Q ratio from checkpoint params - def compute_Q(de_arr): - return (dx_cm / B_eff) * np.log(np.maximum(ALPHA_RECOMB + B_eff * de_arr / dx_cm, 1.0)) - - truth_de_all = data['truth_de'] - truth_total_Q = compute_Q(truth_de_all).sum() - - checkpoint_params = data['checkpoint_params'] - checkpoint_steps = data['checkpoint_steps'] - q_steps, q_vals = [], [] - for i in range(0, len(checkpoint_steps), 10): # every 10th checkpoint - p_np = checkpoint_params[i] - alive = p_np[:, 3] > DEATH_THRESH - sim_Q = compute_Q(p_np[alive, 3]).sum() - q_steps.append(checkpoint_steps[i]) - q_vals.append(sim_Q / truth_total_Q) - - # ===================================================================== - # Waterfall data: rows = dE bins + 1 dead row at bottom - # ===================================================================== - all_alive_kev = np.concatenate([h[0] * 1000 for h in de_history]) - p99_kev = np.percentile(all_alive_kev, 99) - n_bins = 80 - bin_edges_kev = np.linspace(DEATH_THRESH * 1000, p99_kev, n_bins + 1) - - n_steps_hist = len(de_history) - - # Row 0 = dead (bottom), rows 1..n_bins = dE bins low to high, row n_bins+1 = overflow (top) - waterfall = np.zeros((n_bins + 2, n_steps_hist)) - for j, (alive_de, n_dead) in enumerate(de_history): - alive_kev = alive_de * 1000 - hist, _ = np.histogram(alive_kev, bins=bin_edges_kev) - overflow = int(np.sum(alive_kev > p99_kev)) - waterfall[0, j] = n_dead - waterfall[1:n_bins+1, j] = hist - waterfall[n_bins+1, j] = overflow - - # ===================================================================== - # Plot 3x2 - # ===================================================================== - fig, axes = plt.subplots(3, 2, figsize=(18, 20)) - - # (0,0) Loss - ax = axes[0, 0] - ax.semilogy(losses, 'b-', lw=1.0, alpha=0.7) - ax.set_xlabel('Step', fontsize=14); ax.set_ylabel('Loss', fontsize=14) - ax.set_title('Loss', fontsize=15); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # (0,1) Q ratio - ax = axes[0, 1] - ax.plot(q_steps, q_vals, 'b-', lw=2, label='Q ratio (sim/truth)') - ax.axhline(1.0, color='green', ls='--', lw=1.5, alpha=0.5) - ax.set_xlabel('Step', fontsize=14); ax.set_ylabel('Q Ratio', fontsize=14) - ax.set_title('Charge Conservation', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # (1,0) West U - ax = axes[1, 0] - p = 3 - if p in active_planes: - t_prof = truth_profiles[p] - r_prof = sim_profiles[p][-1] - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # (1,1) West V - ax = axes[1, 1] - p = 4 - if p in active_planes: - t_prof = truth_profiles[p] - r_prof = sim_profiles[p][-1] - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # (2,0) West Y - ax = axes[2, 0] - p = 5 - if p in active_planes: - t_prof = truth_profiles[p] - r_prof = sim_profiles[p][-1] - nz = np.where(t_prof > 0)[0] - wl, wh = (max(0, nz[0]-10), min(len(t_prof), nz[-1]+11)) if len(nz) > 0 else (0, len(t_prof)) - w = np.arange(wl, wh) - ax.plot(w, t_prof[wl:wh], 'b-', lw=1.5, label='Truth') - ax.plot(w, r_prof[wl:wh], 'r--', lw=1.5, label='Recon') - ax.set_title(f'Signal ({PLANE_NAMES[p]})', fontsize=15) - ax.legend(fontsize=11); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # (2,1) dE Waterfall - ax = axes[2, 1] - - # Build y-axis tick positions and labels - # Row 0 = dead, rows 1..n_bins = dE - # y extent: 0 to n_bins+1 - step_arr = de_history_steps - - im = ax.imshow(waterfall, aspect='auto', origin='lower', - extent=[step_arr[0], step_arr[-1], 0, n_bins + 2], - cmap='inferno', - norm=mcolors.LogNorm(vmin=1, vmax=max(waterfall.max(), 2)), - interpolation='none') - - # Y-axis labels - de_tick_positions = [0.5] # dead center - de_tick_labels = ['Dead'] - for kev_val in [50, 200, 500, 1000]: - if kev_val <= p99_kev: - bin_pos = 1 + (kev_val - DEATH_THRESH * 1000) / (p99_kev - DEATH_THRESH * 1000) * n_bins - de_tick_positions.append(bin_pos) - de_tick_labels.append(f'{kev_val}') - de_tick_positions.append(n_bins + 1.5) # overflow center - de_tick_labels.append(f'>{p99_kev:.0f}') - - ax.set_yticks(de_tick_positions) - ax.set_yticklabels(de_tick_labels) - ax.set_xlabel('Step', fontsize=14) - ax.set_ylabel('dE (keV)', fontsize=14) - ax.set_title(f'Segment dE Distribution Over Training', fontsize=14) - ax.tick_params(labelsize=11) - - cbar = fig.colorbar(im, ax=ax, label='Segment count') - - fig.suptitle(f'Best Final | 50k segs, s=1.0, lr=1.0, reloc 25/1000\n' - f'loss={losses[-1]:.6f}, Q_ratio={q_vals[-1]:.3f}', - fontsize=15, fontweight='bold') - fig.tight_layout(rect=[0, 0, 1, 0.96]) - fname = os.path.join(OUT_DIR, 'best_final_progression_v3.png') - fig.savefig(fname, dpi=150) - plt.close(fig) - print(f"Saved {fname}") - - -if __name__ == '__main__': - main() diff --git a/closure/segments/plot_q.py b/closure/segments/plot_q.py deleted file mode 100644 index 100d0c4..0000000 --- a/closure/segments/plot_q.py +++ /dev/null @@ -1,166 +0,0 @@ -""" -Plot Q-diff percentile progression over training. - -Shows 68th, 99th percentile and max of |Q_truth - Q_sim| per voxel over steps. -Also shows Q_ratio and dE_ratio trajectories for comparison. - -Usage: - python3 closure_analysis_full/sweeps/plot_q_progression.py --data best_run_out_50k_2000.npz --name out_50k -""" - -import numpy as np -import matplotlib.pyplot as plt -import os, argparse - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -VOXEL_SIZE = 25.0 -MIN_DIFF = 0.0001 -ALPHA = 0.93 -BETA = 0.212 -LAR_DENSITY = 1.396 - - -def de_to_Q(de, dx_cm, B_eff): - return (dx_cm / B_eff) * np.log(ALPHA + B_eff * de / dx_cm) - - -def voxelize_Q(positions, energies, dx_cm, B_eff, voxel_size, origin): - Q = de_to_Q(energies, dx_cm, B_eff) - idx = ((positions - origin) / voxel_size).astype(np.int64) - keys = idx[:, 0] * 1_000_000 + idx[:, 1] * 1_000 + idx[:, 2] - unique_keys, inverse = np.unique(keys, return_inverse=True) - vox_Q = np.zeros(len(unique_keys)) - np.add.at(vox_Q, inverse, Q) - return dict(zip(unique_keys.tolist(), vox_Q.tolist())) - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('--data', required=True) - parser.add_argument('--name', required=True) - args = parser.parse_args() - - data_path = os.path.join(OUT_DIR, args.data) - print(f"Loading {data_path}...") - data = np.load(data_path) - - truth_pos = data['truth_pos'] - truth_de = data['truth_de'] - checkpoint_params = data['checkpoint_params'] - checkpoint_steps = data['checkpoint_steps'] - checkpoint_losses = data['checkpoint_losses'] - n_truth = int(data['n_truth']) - truth_total_de = float(data['truth_total_de']) - - dx_mm = float(data['dx_mm']) if 'dx_mm' in data else 0.5 - dx_cm = dx_mm / 10.0 - - if 'B_eff' in data: - B_eff = float(data['B_eff']) - else: - # Default for modified_box at 500 V/cm - field_kVcm = 0.5 - B_eff = BETA / LAR_DENSITY / field_kVcm # 0.3037 - - n_frames = len(checkpoint_steps) - print(f" {n_frames} frames, dx={dx_mm}mm") - - all_pos_min = np.minimum(truth_pos.min(axis=0), - checkpoint_params[:, :, :3].reshape(-1, 3).min(axis=0)) - origin = all_pos_min - VOXEL_SIZE - - # Truth Q voxels (fixed) - truth_vox = voxelize_Q(truth_pos, truth_de, dx_cm, B_eff, VOXEL_SIZE, origin) - total_truth_Q = de_to_Q(truth_de, dx_cm, B_eff).sum() - - # Compute per-frame stats - steps, p68, p99, maxdiff, mean_diff = [], [], [], [], [] - q_ratios, de_ratios, n_voxels = [], [], [] - - for i in range(n_frames): - params = checkpoint_params[i] - alive = params[:, 3] > 0.001 - sim_de = params[alive, 3] - - # Total Q and dE - total_sim_Q = de_to_Q(sim_de, dx_cm, B_eff).sum() - total_sim_dE = params[:, 3].sum() - - sim_vox = voxelize_Q(params[alive, :3], sim_de, dx_cm, B_eff, VOXEL_SIZE, origin) - - all_keys = set(truth_vox.keys()) | set(sim_vox.keys()) - diffs = [] - for k in all_keys: - t_q = truth_vox.get(k, 0) - s_q = sim_vox.get(k, 0) - d = t_q - s_q - if abs(d) > MIN_DIFF: - diffs.append(d) - - if not diffs: - diffs = [0.0] - da = np.abs(np.array(diffs)) - - steps.append(checkpoint_steps[i]) - p68.append(np.percentile(da, 68)) - p99.append(np.percentile(da, 99)) - maxdiff.append(da.max()) - mean_diff.append(da.mean()) - q_ratios.append(total_sim_Q / total_truth_Q) - de_ratios.append(total_sim_dE / truth_total_de) - n_voxels.append(len(diffs)) - - steps = np.array(steps) - - # Plot - fig, axes = plt.subplots(2, 2, figsize=(16, 12)) - - # Top-left: Q-diff percentiles - ax = axes[0, 0] - ax.semilogy(steps, p99, 'r-', lw=2, label='99th %ile') - ax.semilogy(steps, p68, 'b-', lw=2, label='68th %ile') - ax.semilogy(steps, mean_diff, 'k--', lw=1.5, alpha=0.7, label='Mean') - ax.semilogy(steps, maxdiff, 'gray', lw=1, alpha=0.4, label='Max') - ax.set_xlabel('Step', fontsize=13) - ax.set_ylabel('|Q diff| per voxel', fontsize=13) - ax.set_title('Q-diff Percentiles Over Training', fontsize=14, fontweight='bold') - ax.legend(fontsize=10); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # Top-right: Q ratio vs dE ratio - ax = axes[0, 1] - ax.plot(steps, q_ratios, 'b-', lw=2, label='Q ratio (sim/truth)') - ax.plot(steps, de_ratios, 'r-', lw=2, label='dE ratio (sim/truth)') - ax.axhline(1.0, color='green', ls='--', lw=1.5, alpha=0.5, label='Target=1.0') - ax.set_xlabel('Step', fontsize=13) - ax.set_ylabel('Ratio', fontsize=13) - ax.set_title('Q Ratio vs dE Ratio', fontsize=14, fontweight='bold') - ax.legend(fontsize=10); ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # Bottom-left: N active voxels - ax = axes[1, 0] - ax.plot(steps, n_voxels, 'k-', lw=2) - ax.set_xlabel('Step', fontsize=13) - ax.set_ylabel('Active Q-diff Voxels', fontsize=13) - ax.set_title('Voxel Count (non-zero Q diff)', fontsize=14, fontweight='bold') - ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - # Bottom-right: Loss - ax = axes[1, 1] - ax.semilogy(steps, checkpoint_losses, 'b-', lw=2) - ax.set_xlabel('Step', fontsize=13) - ax.set_ylabel('Loss', fontsize=13) - ax.set_title('Sobolev Loss', fontsize=14, fontweight='bold') - ax.grid(True, alpha=0.3); ax.tick_params(labelsize=11) - - fig.suptitle(f'{args.name} — Q-space Progression ({VOXEL_SIZE:.0f}mm voxels, dx={dx_mm}mm)', - fontsize=15, fontweight='bold') - fig.tight_layout() - fname = os.path.join(OUT_DIR, f'q_progression_{args.name}.png') - fig.savefig(fname, dpi=150, bbox_inches='tight') - plt.close(fig) - print(f"Saved {fname}") - - -if __name__ == '__main__': - main() diff --git a/closure/segments/precompute.py b/closure/segments/precompute.py deleted file mode 100644 index 47eb057..0000000 --- a/closure/segments/precompute.py +++ /dev/null @@ -1,166 +0,0 @@ -""" -Precompute wire signals from saved checkpoint params — sparse storage. -Threshold at half-deadband (400 electrons) for compact storage. -Reads from power-law checkpoint files. - -Usage: - python3 -m closure.segments.precompute --checkpoint best_final_v2.npz --edepsim out.h5 - python3 -m closure.segments.precompute --checkpoint best_final_v2.npz --edepsim out.h5 \ - --config config/cubic_wireplane_config.yaml --event 2 --outdir closure/segments -""" - -import os, time, argparse - -import jax, jax.numpy as jnp, numpy as np - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data, build_deposit_data - -DX_MM = 0.3 -DEADBAND_ENC = 800 -SPARSE_ENC = DEADBAND_ENC // 2 # 400 electrons - - -def to_sparse(arr, threshold_adc): - """Convert dense 2D array to sparse (indices, values) above threshold.""" - mask = np.abs(arr) >= threshold_adc - indices = np.argwhere(mask).astype(np.int32) - values = arr[mask].astype(np.float32) - return indices, values - - -def main(): - parser = argparse.ArgumentParser( - description='Precompute wire signals from checkpoint params (sparse storage)') - parser.add_argument('--checkpoint', required=True, - help='Checkpoint .npz file (e.g. best_final_v2.npz)') - parser.add_argument('--edepsim', required=True, - help='HDF5 file with particle step data') - parser.add_argument('--config', default='config/cubic_wireplane_config.yaml', - help='Detector config YAML (default: config/cubic_wireplane_config.yaml)') - parser.add_argument('--event', type=int, default=2, - help='Event index for truth deposits (default: 2)') - parser.add_argument('--outdir', default=None, - help='Output directory (default: same as checkpoint dir)') - parser.add_argument('--frame-every', type=int, default=1, - help='Use every Nth checkpoint (default: 1 = all)') - args = parser.parse_args() - - out_dir = args.outdir if args.outdir else os.path.dirname(os.path.abspath(args.checkpoint)) - - print(f"Loading {args.checkpoint}...") - data = np.load(args.checkpoint, allow_pickle=True) - checkpoint_params = data['checkpoint_params'] - checkpoint_steps = data['checkpoint_steps'] - checkpoint_losses = data['checkpoint_losses'] - n_seg = int(data['n_seg']) - active_planes = list(data['active_planes']) - - # Subsample frames - frame_indices = list(range(0, len(checkpoint_steps), args.frame_every)) - if frame_indices[-1] != len(checkpoint_steps) - 1: - frame_indices.append(len(checkpoint_steps) - 1) - n_frames = len(frame_indices) - print(f" {len(checkpoint_steps)} checkpoints → {n_frames} frames") - - # Setup - step_data = load_particle_step_data(args.edepsim, args.event) - positions_mm = step_data['positions_mm'] - de = step_data['de'] - n_truth = positions_mm.shape[0] - detector_config = generate_detector(args.config) - electrons_per_adc = float(detector_config['electrons_per_adc']) - sparse_threshold_adc = SPARSE_ENC / electrons_per_adc - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - print(f" Sparse threshold: {SPARSE_ENC} e⁻ = {sparse_threshold_adc:.2f} ADC") - - # Truth signals — build proper DepositData via build_deposit_data - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - - deposits = build_deposit_data( - positions_mm=positions_mm, - de=de, - dx=np.full(n_truth, DX_MM, dtype=np.float32), - sim_config=sim_truth.config, - theta=step_data['theta'], - phi=step_data['phi'], - track_ids=step_data['track_ids'], - ) - - print("Computing truth signals...") - response_signals, _, _ = sim_truth.process_event(deposits) - - # Save truth as sparse - save_data = { - 'n_frames': n_frames, - 'frame_steps': np.array([checkpoint_steps[ci] for ci in frame_indices]), - 'frame_losses': np.array([checkpoint_losses[ci] for ci in frame_indices]), - 'active_planes': np.array(active_planes), - 'sparse_threshold_adc': sparse_threshold_adc, - 'sparse_threshold_enc': SPARSE_ENC, - 'deadband_enc': DEADBAND_ENC, - } - - truth_shapes = {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - arr = np.array(signal) - truth_shapes[pidx] = arr.shape - idx, val = to_sparse(arr, sparse_threshold_adc) - save_data[f'truth_{side}_{plane}_indices'] = idx - save_data[f'truth_{side}_{plane}_values'] = val - save_data[f'truth_{side}_{plane}_shape'] = np.array(arr.shape) - n_total = arr.shape[0] * arr.shape[1] - print(f" truth ({side},{plane}): {len(val):,}/{n_total:,} nonzero " - f"({len(val)/n_total*100:.1f}%)") - - # Optimizer forward — inline wrapper replacing build_forward + SegmentData - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - sim_params = sim_opt.default_sim_params - - def fwd(positions_mm, de): - return sim_opt.forward_segments(sim_params, positions_mm, de, dx=DX_MM) - - # JIT warmup - pos0 = jnp.array(checkpoint_params[0][:, :3]) - de0 = jnp.array(checkpoint_params[0][:, 3]) - _ = fwd(pos0, de0) - for s in fwd(pos0, de0): - jax.block_until_ready(s) - print("JIT ready.\n") - - # Precompute signals at each frame — save sparse - print(f"Computing {n_frames} forward passes (sparse storage)...") - t0 = time.time() - total_stored = 0 - - for fi, ci in enumerate(frame_indices): - params = checkpoint_params[ci] - recon = fwd(jnp.array(params[:, :3]), jnp.array(params[:, 3])) - - for pidx in active_planes: - side, plane = pidx // 3, pidx % 3 - arr = np.array(recon[pidx]) - idx, val = to_sparse(arr, sparse_threshold_adc) - save_data[f'sim_{fi}_{side}_{plane}_indices'] = idx - save_data[f'sim_{fi}_{side}_{plane}_values'] = val - total_stored += idx.nbytes + val.nbytes - - if fi % 10 == 0 or fi == n_frames - 1: - print(f" Frame {fi+1}/{n_frames} (step {checkpoint_steps[ci]}) — " - f"{time.time()-t0:.0f}s, {total_stored/1e6:.0f} MB stored") - - os.makedirs(out_dir, exist_ok=True) - save_path = os.path.join(out_dir, 'precomputed_signals_v2.npz') - np.savez_compressed(save_path, **save_data) - print(f"\nSaved to {save_path} ({os.path.getsize(save_path)/1e6:.1f} MB)") - print(f" vs dense estimate: ~{n_frames * 6 * 1969 * 2701 * 4 / 1e9:.1f} GB") - - -if __name__ == '__main__': - main() diff --git a/closure/segments/recon_step_0009.png b/closure/segments/recon_step_0009.png deleted file mode 100644 index 4c5b9b4..0000000 Binary files a/closure/segments/recon_step_0009.png and /dev/null differ diff --git a/closure/segments/recon_step_0049.png b/closure/segments/recon_step_0049.png deleted file mode 100644 index 45fe593..0000000 Binary files a/closure/segments/recon_step_0049.png and /dev/null differ diff --git a/closure/segments/recon_step_0099.png b/closure/segments/recon_step_0099.png deleted file mode 100644 index 3700ee8..0000000 Binary files a/closure/segments/recon_step_0099.png and /dev/null differ diff --git a/closure/segments/recon_step_0100.png b/closure/segments/recon_step_0100.png deleted file mode 100644 index c4f0ce4..0000000 Binary files a/closure/segments/recon_step_0100.png and /dev/null differ diff --git a/closure/segments/recon_step_0199.png b/closure/segments/recon_step_0199.png deleted file mode 100644 index f5aa6be..0000000 Binary files a/closure/segments/recon_step_0199.png and /dev/null differ diff --git a/closure/segments/recon_step_0500.png b/closure/segments/recon_step_0500.png deleted file mode 100644 index 378accf..0000000 Binary files a/closure/segments/recon_step_0500.png and /dev/null differ diff --git a/closure/segments/recon_step_0999.png b/closure/segments/recon_step_0999.png deleted file mode 100644 index 7a0fc41..0000000 Binary files a/closure/segments/recon_step_0999.png and /dev/null differ diff --git a/closure/segments/recon_step_1000.png b/closure/segments/recon_step_1000.png deleted file mode 100644 index 527dcf1..0000000 Binary files a/closure/segments/recon_step_1000.png and /dev/null differ diff --git a/closure/segments/recon_step_1500.png b/closure/segments/recon_step_1500.png deleted file mode 100644 index e2faf2d..0000000 Binary files a/closure/segments/recon_step_1500.png and /dev/null differ diff --git a/closure/segments/recon_step_1999.png b/closure/segments/recon_step_1999.png deleted file mode 100644 index 61f336b..0000000 Binary files a/closure/segments/recon_step_1999.png and /dev/null differ diff --git a/closure/segments/render_2d.py b/closure/segments/render_2d.py deleted file mode 100644 index beb7f50..0000000 --- a/closure/segments/render_2d.py +++ /dev/null @@ -1,229 +0,0 @@ -""" -Render 2D event display GIFs from sparse precomputed signals (v2). -Loads sparse, densifies per frame, reuses figure with imshow set_data. - -Usage: - python3 closure/segments/render_2d.py --signals closure_analysis_full/sweeps/precomputed_signals_v2.npz - python3 closure/segments/render_2d.py --signals closure_analysis_full/sweeps/precomputed_signals_v2.npz --preview -""" - -import sys, os, time, argparse - -import numpy as np -import matplotlib -matplotlib.use('Agg') -import matplotlib.pyplot as plt -import matplotlib.gridspec as gridspec -from mpl_toolkits.axes_grid1 import make_axes_locatable -from PIL import Image - -from tools.geometry import generate_detector -from tools.visualization import _extract_viz_params, _resolve_cmap, DeadbandNorm - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -GIF_FPS = 25 -FRAME_SKIP = 2 -GAMMA = 0.2 - -TITLE_SIZE = 16 -LABEL_SIZE = 14 -TICK_SIZE = 12 -CBAR_LABEL_SIZE = 12 -CBAR_TICK_SIZE = 10 -SUPTITLE_SIZE = 18 - - -def fig_to_image(fig): - fig.canvas.draw() - w, h = fig.canvas.get_width_height() - buf = fig.canvas.buffer_rgba() - return Image.frombuffer('RGBA', (w, h), buf, 'raw', 'RGBA', 0, 1).convert('RGB').copy() - - -def add_colorbar(fig, ax, mappable, norm): - divider = make_axes_locatable(ax) - cax = divider.append_axes('right', size='3%', pad=0.02) - cbar = fig.colorbar(mappable, cax=cax) - if isinstance(norm, DeadbandNorm): - tick_norm = np.linspace(0, 1, 7) - tick_values = norm.inverse(tick_norm) - cbar.set_ticks(tick_values) - cbar.set_ticklabels([f'{v:.0f}' for v in tick_values]) - cbar.ax.tick_params(labelsize=CBAR_TICK_SIZE, colors='black') - cbar.set_label('Signal (ADC)', fontsize=CBAR_LABEL_SIZE, color='black') - return cbar - - -def sparse_to_dense(indices, values, shape): - arr = np.zeros(shape, dtype=np.float32) - if len(indices) > 0: - arr[indices[:, 0], indices[:, 1]] = values - return arr - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('--signals', required=True, - help='Path to precomputed_signals_v2.npz') - parser.add_argument('--config', default='config/cubic_wireplane_config.yaml', - help='Detector config YAML') - parser.add_argument('--preview', action='store_true') - args = parser.parse_args() - - print("Loading sparse signals...") - data = np.load(args.signals, allow_pickle=True) - n_frames = int(data['n_frames']) - frame_steps = data['frame_steps'] - frame_losses = data['frame_losses'] - active_planes = list(data['active_planes']) - deadband_enc = int(data['deadband_enc']) - - detector_config = generate_detector(args.config) - electrons_per_adc = float(detector_config['electrons_per_adc']) - deadband_adc = deadband_enc / electrons_per_adc - cmap = _resolve_cmap('obsidian') - vp = _extract_viz_params(detector_config) - max_time_axis = vp['num_time_steps'] * vp['time_step_size_us'] - max_abs_indices = vp['max_abs_indices'] - min_abs_indices = vp['min_abs_indices'] - zero_color = cmap(0.5) - - ptype_map = {0: 'U', 1: 'V', 2: 'Y'} - plane_types = ['1st Induction (U)', '2nd Induction (V)', 'Collection (Y)'] - row_labels = ['Truth', 'Sim', 'Diff'] - - truth = {} - truth_shapes = {} - for pidx in active_planes: - s, p = pidx // 3, pidx % 3 - shape = tuple(data[f'truth_{s}_{p}_shape']) - indices = data[f'truth_{s}_{p}_indices'] - values = data[f'truth_{s}_{p}_values'] - truth[(s, p)] = sparse_to_dense(indices, values, shape) - truth_shapes[(s, p)] = shape - - plane_min_max = {'U': {'min': np.inf, 'max': -np.inf}, - 'V': {'min': np.inf, 'max': -np.inf}, - 'Y': {'min': np.inf, 'max': -np.inf}} - for pidx in active_planes: - s, p = pidx // 3, pidx % 3 - arr = truth[(s, p)] - pt = ptype_map[p] - plane_min_max[pt]['min'] = min(plane_min_max[pt]['min'], arr.min()) - plane_min_max[pt]['max'] = max(plane_min_max[pt]['max'], arr.max()) - for pt in plane_min_max: - mm = plane_min_max[pt] - if mm['min'] == np.inf: - mm['min'], mm['max'] = -25, 25 - elif pt == 'Y': - abs_max = max(abs(mm['min']), abs(mm['max'])) - mm['min'], mm['max'] = -abs_max, abs_max - - print(f" {n_frames} frames, deadband={deadband_enc} e-") - - for side_idx, side_name in [(0, 'east'), (1, 'west')]: - side_planes = [(side_idx, p) for p in range(3) - if side_idx * 3 + p in active_planes] - if not side_planes: - continue - n_p = len(side_planes) - - print(f"\n {side_name.upper()} ({n_p} planes)...") - - fig = plt.figure(figsize=(6.5 * n_p, 15), facecolor='white') - gs = gridspec.GridSpec(3, n_p, figure=fig, hspace=0.25, wspace=0.28) - ims = {} - titles = {} - - for row in range(3): - for col, (s, p) in enumerate(side_planes): - ax = fig.add_subplot(gs[row, col]) - ax.set_facecolor(zero_color) - ax.grid(False) - min_idx = int(min_abs_indices[s, p]) - max_idx = int(max_abs_indices[s, p]) - extent = [min_idx, max_idx + 1, 0, max_time_axis] - pt = ptype_map[p] - vmin = plane_min_max[pt]['min'] - vmax = plane_min_max[pt]['max'] - norm = DeadbandNorm(vmin, vmax, deadband_adc, GAMMA) - - im = ax.imshow(truth[(s, p)].T, aspect='auto', origin='lower', - extent=extent, cmap=cmap, norm=norm, - interpolation='nearest') - ims[(row, col)] = im - - cbar = add_colorbar(fig, ax, im, norm) - if col < n_p - 1: - cbar.set_label('') - - ttl = ax.set_title(f'{row_labels[row]} {plane_types[p]}', - fontsize=TITLE_SIZE, pad=8) - titles[(row, col)] = ttl - - if row == 2: - ax.set_xlabel('Absolute Wire Index', fontsize=LABEL_SIZE) - else: - ax.set_xlabel('') - if col == 0: - ax.set_ylabel('Time (us)', fontsize=LABEL_SIZE) - else: - ax.set_ylabel('') - ax.tick_params(labelsize=TICK_SIZE) - ax.set_xlim(min_idx, max_idx + 1) - ax.set_ylim(0, max_time_axis) - - suptitle = fig.suptitle('', fontsize=SUPTITLE_SIZE, fontweight='bold', y=0.995) - fig.subplots_adjust(top=0.94) - - if args.preview: - for fi in [0, n_frames - 1]: - step = frame_steps[fi] - loss = frame_losses[fi] - for col, (s, p) in enumerate(side_planes): - shape = truth_shapes[(s, p)] - r_sig = sparse_to_dense( - data[f'sim_{fi}_{s}_{p}_indices'], - data[f'sim_{fi}_{s}_{p}_values'], shape) - d_sig = truth[(s, p)] - r_sig - ims[(1, col)].set_data(r_sig.T) - ims[(2, col)].set_data(d_sig.T) - suptitle.set_text(f'{side_name.upper()} -- Step {step} | ' - f'Loss: {loss:.6f} | Threshold: {deadband_enc} e-') - fname = os.path.join(OUT_DIR, f'preview_v2_{side_name}_step{step}.png') - fig.savefig(fname, dpi=150, bbox_inches='tight', facecolor='white') - print(f" Saved {fname}") - else: - frames = [] - t0 = time.time() - frame_list = list(range(0, n_frames, FRAME_SKIP)) - if frame_list[-1] != n_frames - 1: - frame_list.append(n_frames - 1) - for fi in frame_list: - step = frame_steps[fi] - loss = frame_losses[fi] - for col, (s, p) in enumerate(side_planes): - shape = truth_shapes[(s, p)] - r_sig = sparse_to_dense( - data[f'sim_{fi}_{s}_{p}_indices'], - data[f'sim_{fi}_{s}_{p}_values'], shape) - d_sig = truth[(s, p)] - r_sig - ims[(1, col)].set_data(r_sig.T) - ims[(2, col)].set_data(d_sig.T) - suptitle.set_text(f'{side_name.upper()} -- Step {step} | ' - f'Loss: {loss:.6f} | Threshold: {deadband_enc} e-') - frames.append(fig_to_image(fig)) - if len(frames) % 25 == 0 or fi == frame_list[-1]: - print(f" Frame {len(frames)}/{len(frame_list)} (step {step}) -- {time.time()-t0:.0f}s") - - out_path = os.path.join(OUT_DIR, f'event_display_2d_v2_{side_name}.gif') - duration_ms = int(1000 / GIF_FPS) - frames[0].save(out_path, save_all=True, append_images=frames[1:], - duration=duration_ms, loop=0) - print(f" Saved {out_path} ({os.path.getsize(out_path)/1e6:.1f} MB)") - - plt.close(fig) - - -if __name__ == '__main__': - main() diff --git a/closure/segments/render_3d.py b/closure/segments/render_3d.py deleted file mode 100644 index 7d4ca84..0000000 --- a/closure/segments/render_3d.py +++ /dev/null @@ -1,232 +0,0 @@ -""" -3D annihilation plot using CHARGE (Q) difference instead of dE. - -Renders for both the 20k mpvmpr run (s=1.5) and the 50k out.h5 run (s=1.0). -Pass --data to select which checkpoint file to use. - -Usage: - python3 closure/segments/render_3d.py --data closure_analysis_full/sweeps/best_run_20k_4000.npz --name 20k_s1.5 - python3 closure/segments/render_3d.py --data closure_analysis_full/sweeps/best_run_out_50k_2000.npz --name out_50k_s1.0 -""" - -import numpy as np -import matplotlib.pyplot as plt -from matplotlib.colors import TwoSlopeNorm -import matplotlib.animation as animation -import os, time, argparse - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) - -VOXEL_SIZE = 50.0 # mm — track-level resolution -W_ION = 23.6e-6 # MeV per electron-ion pair -WIRE_PITCH = 3.0 # mm -TICK_SPATIAL = 0.8 # mm (0.5μs × 1.6 mm/μs) -NOISE_RMS_CELL = 300.0 # electrons per wire×tick cell - -# Floor: computed as 1% of 99th percentile Q-diff (set after frame computation) -MAX_POINT_SIZE = 120 -MIN_POINT_SIZE = 8 -POINT_ALPHA = 0.55 -FPS = 20 -FRAME_SKIP = 2 # use every 2nd checkpoint -DPI = 150 - -# Recombination constants (modified_box) -ALPHA = 0.93 -BETA = 0.212 -LAR_DENSITY = 1.396 - - -def de_to_Q(de, dx_cm, B_eff): - raw = (dx_cm / B_eff) * np.log(np.maximum(ALPHA + B_eff * de / dx_cm, 1.0)) - return raw - - -def voxelize_Q(positions, energies, dx_cm, B_eff, voxel_size, origin): - """Voxelize positions, accumulate Q (not dE) per voxel.""" - Q = de_to_Q(energies, dx_cm, B_eff) - idx = ((positions - origin) / voxel_size).astype(np.int64) - keys = idx[:, 0] * 1_000_000 + idx[:, 1] * 1_000 + idx[:, 2] - unique_keys, inverse = np.unique(keys, return_inverse=True) - vox_Q = np.zeros(len(unique_keys)) - np.add.at(vox_Q, inverse, Q) - vox_idx = np.zeros((len(unique_keys), 3), dtype=np.int64) - for i, k in enumerate(unique_keys): - vox_idx[i] = [k // 1_000_000, (k % 1_000_000) // 1_000, k % 1_000] - centers = origin + (vox_idx + 0.5) * voxel_size - return dict(zip(unique_keys.tolist(), - zip(vox_Q.tolist(), centers[:, 0].tolist(), - centers[:, 1].tolist(), centers[:, 2].tolist()))) - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('--data', required=True, help='Checkpoint NPZ file') - parser.add_argument('--name', required=True, help='Output name suffix') - args = parser.parse_args() - - data_path = os.path.join(OUT_DIR, args.data) - out_path = os.path.join(OUT_DIR, f'annihilation_3d_Q_{args.name}.gif') - - print(f"Loading {data_path}...") - data = np.load(data_path) - truth_pos = data['truth_pos'] - truth_de = data['truth_de'] - checkpoint_params = data['checkpoint_params'] - checkpoint_steps = data['checkpoint_steps'] - checkpoint_losses = data['checkpoint_losses'] - n_seg = int(data['n_seg']) - - # Get dx and B_eff - if 'dx_mm' in data: - dx_mm = float(data['dx_mm']) - else: - dx_mm = 0.5 # default for older runs - dx_cm = dx_mm / 10.0 - - if 'B_eff' in data: - B_eff = float(data['B_eff']) - else: - field_kVcm = 0.5 - B_eff = BETA / LAR_DENSITY / field_kVcm - - n_frames = len(checkpoint_steps) - print(f" {n_frames} checkpoints, {n_seg} segments, dx={dx_mm}mm") - - all_pos_min = np.minimum(truth_pos.min(axis=0), - checkpoint_params[:, :, :3].reshape(-1, 3).min(axis=0)) - origin = all_pos_min - VOXEL_SIZE - - print("Voxelizing truth (Q-space)...") - truth_voxels = voxelize_Q(truth_pos, truth_de, dx_cm, B_eff, VOXEL_SIZE, origin) - total_truth_Q = sum(v[0] for v in truth_voxels.values()) - mean_vox_Q = total_truth_Q / len(truth_voxels) - mean_vox_E = mean_vox_Q / W_ION - print(f" {len(truth_voxels)} truth voxels, total Q={total_truth_Q:.1f}") - print(f" Mean voxel Q={mean_vox_Q:.3f} MeV = {mean_vox_E:.0f} e⁻") - - # Pass 1: compute all diffs unfiltered to find 99th percentile - print("Computing frame data (pass 1: unfiltered)...") - t0 = time.time() - frame_data_raw = [] - - for i in range(n_frames): - params = checkpoint_params[i] - alive = params[:, 3] > 0.012 - sim_voxels = voxelize_Q(params[alive, :3], params[alive, 3], - dx_cm, B_eff, VOXEL_SIZE, origin) - all_keys = set(truth_voxels.keys()) | set(sim_voxels.keys()) - diffs = [] - for k in all_keys: - t_q = truth_voxels.get(k, (0,0,0,0))[0] - s_q = sim_voxels.get(k, (0,0,0,0))[0] - diff_q = t_q - s_q - if abs(diff_q) < 1e-12: # skip truly zero - continue - diff_e = diff_q / W_ION - c = truth_voxels[k] if k in truth_voxels else sim_voxels[k] - diffs.append((c[1], c[2], c[3], diff_e)) - arr = np.array(diffs) if diffs else np.zeros((1, 4)) - frame_data_raw.append(arr) - - # Compute 99th percentile across all frames - all_abs = np.concatenate([np.abs(fd[:, 3]) for fd in frame_data_raw if len(fd) > 1]) - p99 = np.percentile(all_abs, 99) - floor_e = 0.15 * p99 # 15% of 99th percentile — ensures all plotted points have visible color - global_max_diff = all_abs.max() - print(f" 99th percentile: {p99:.0f} e⁻") - print(f" Floor (1% of p99): {floor_e:.0f} e⁻") - print(f" Max: {global_max_diff:.0f} e⁻") - - # Pass 2: filter by floor - frame_data = [] - for arr in frame_data_raw: - mask = np.abs(arr[:, 3]) >= floor_e - filtered = arr[mask] if mask.any() else np.zeros((1, 4)) - frame_data.append(filtered) - - for i in range(0, n_frames, 50): - print(f" Frame {i}/{n_frames}: {len(frame_data[i])} voxels (after floor)") - print(f" Done in {time.time()-t0:.1f}s") - - print("Rendering animation...") - fig = plt.figure(figsize=(11, 9), facecolor='black') - ax = fig.add_subplot(111, projection='3d', facecolor='black') - - # Colorbar: full range up to 99th percentile - vmax = p99 - print(f" Linear colorbar: vmax={vmax:.0f} e⁻ (99th %ile), " - f"floor={floor_e:.0f} e⁻ (5% of p99)") - - norm = TwoSlopeNorm(vmin=-vmax, vcenter=0, vmax=vmax) - cmap = plt.cm.RdBu_r - - sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) - sm.set_array([]) - cbar = fig.colorbar(sm, ax=ax, shrink=0.6, pad=0.08) - cbar.set_label(f'ΔQ (electrons) | floor={floor_e:.0f} e⁻, clip={vmax:.0f} e⁻', - color='white', fontsize=9) - cbar.ax.yaxis.label.set_color('white') - cbar.ax.tick_params(colors='white') - - ax.set_xlabel('X (mm)', color='white', fontsize=10) - ax.set_ylabel('Y (mm)', color='white', fontsize=10) - ax.set_zlabel('Z (mm)', color='white', fontsize=10) - ax.tick_params(colors='white', labelsize=7) - ax.xaxis.pane.fill = False; ax.yaxis.pane.fill = False; ax.zaxis.pane.fill = False - ax.xaxis.pane.set_edgecolor('gray'); ax.yaxis.pane.set_edgecolor('gray') - ax.zaxis.pane.set_edgecolor('gray') - ax.grid(True, alpha=0.2, color='gray') - - margin = 50 - ax.set_xlim(truth_pos[:, 0].min() - margin, truth_pos[:, 0].max() + margin) - ax.set_ylim(truth_pos[:, 1].min() - margin, truth_pos[:, 1].max() + margin) - ax.set_zlim(truth_pos[:, 2].min() - margin, truth_pos[:, 2].max() + margin) - - scatter = [None] - title = ax.set_title('', color='white', fontsize=11, fontweight='bold', pad=20) - - def update(frame_idx): - if scatter[0] is not None: - scatter[0].remove() - - # Gentle rotation: 40° total over 4s (0.2° per frame at 50fps) - azim = -60 + 40.0 * frame_idx / n_frames - ax.view_init(elev=25, azim=azim) - - arr = frame_data[frame_idx] - x, y, z, diff = arr[:, 0], arr[:, 1], arr[:, 2], arr[:, 3] - - # Log-based size - abs_diff = np.abs(diff) - ratio = abs_diff / floor_e - sizes = np.clip(np.log10(ratio + 1) / - np.log10(vmax / floor_e + 1) - * MAX_POINT_SIZE, MIN_POINT_SIZE, MAX_POINT_SIZE) - - scatter[0] = ax.scatter(x, y, z, c=diff, cmap=cmap, norm=norm, - s=sizes, alpha=POINT_ALPHA, - edgecolors='none', depthshade=True) - step = checkpoint_steps[frame_idx] - loss = checkpoint_losses[frame_idx] - max_e = np.abs(diff).max() if len(diff) > 0 else 0 - title.set_text(f'{args.name} | Step {step:4d} | Loss: {loss:.5f} | ' - f'{len(arr)} voxels | max={max_e/1000:.0f}k e⁻') - return scatter[0], - - render_indices = list(range(0, n_frames, FRAME_SKIP)) - if render_indices[-1] != n_frames - 1: - render_indices.append(n_frames - 1) - n_render = len(render_indices) - print(f" Creating {n_render} frames (skip={FRAME_SKIP})...") - t0 = time.time() - anim = animation.FuncAnimation(fig, update, frames=render_indices, blit=False, interval=1000/FPS) - writer = animation.PillowWriter(fps=FPS) - anim.save(out_path, writer=writer, dpi=DPI) - print(f" Done in {time.time()-t0:.0f}s") - print(f" Saved to {out_path} ({os.path.getsize(out_path)/1e6:.1f} MB)") - plt.close(fig) - - -if __name__ == '__main__': - main() diff --git a/closure/segments/run_final.py b/closure/segments/run_final.py deleted file mode 100644 index 23c6acf..0000000 --- a/closure/segments/run_final.py +++ /dev/null @@ -1,254 +0,0 @@ -""" -Final best config run with power-law checkpoint spacing. -alpha=2: quadratic -- more checkpoints early where changes happen. - -Usage: - python3 closure/segments/run_final.py --data out.h5 --event 2 - python3 closure/segments/run_final.py --data out.h5 --event 2 --config-yaml config/sbnd_config.yaml -""" - -import os, time, argparse - -import jax, jax.numpy as jnp, numpy as np, optax -import matplotlib.pyplot as plt -import matplotlib.colors as mcolors - -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data, build_deposit_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from closure.segments.run import DEFAULTS, PLANE_NAMES, build_loss_fn, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -SOBOLEV_S = 1.0 -DX_MM = 0.3 -ALPHA_RECOMB = 0.93 -W_ION = 23.6e-6 - - -def power_law_steps(total_steps, n_checkpoints, alpha=2.0): - """Generate non-uniform checkpoint steps with power-law spacing. - - step_k = total_steps * (k/N)^alpha - alpha=1: uniform, alpha=2: quadratic (4x denser at start) - """ - k = np.linspace(0, 1, n_checkpoints) - steps = np.round(total_steps * k ** alpha).astype(int) - steps = np.unique(np.clip(steps, 0, total_steps - 1)) - return steps - - -def main(): - parser = argparse.ArgumentParser( - description='Final best config run with power-law checkpoint spacing') - parser.add_argument('--data', default='out.h5', - help='Path to HDF5 event file (default: out.h5)') - parser.add_argument('--config-yaml', default='config/cubic_wireplane_config.yaml', - help='Path to detector YAML config (default: config/cubic_wireplane_config.yaml)') - parser.add_argument('--event', type=int, default=2, - help='Event index (default: 2)') - args = parser.parse_args() - - n_seg = 50000 - total_steps = 2000 - n_checkpoints = 400 - alpha = 2.0 - - # Best config - lr, decay_rate, lr_e_mult = 1.0, 0.999, 0.01 - warmup, noise_lr = 100, 0.3 - reloc_every, max_reloc = 25, 1000 - track_jitter_mm = 50.0 - - # Compute checkpoint schedule - checkpoint_schedule = power_law_steps(total_steps, n_checkpoints, alpha) - checkpoint_set = set(checkpoint_schedule.tolist()) - - print(f"Final v2: {n_seg} segs, {total_steps} steps, alpha={alpha}") - print(f" {len(checkpoint_schedule)} checkpoints (power-law)") - print(f" First 10 steps: {checkpoint_schedule[:10]}") - print(f" Last 10 steps: {checkpoint_schedule[-10:]}") - print(f" Steps 0-100: {np.sum(checkpoint_schedule <= 100)} checkpoints") - print(f" Steps 100-500: {np.sum((checkpoint_schedule > 100) & (checkpoint_schedule <= 500))} checkpoints") - print(f" Steps 500+: {np.sum(checkpoint_schedule > 500)} checkpoints") - print(f" lr={lr}, d={decay_rate}, e_mult={lr_e_mult}, reloc {reloc_every}/{max_reloc}\n") - - # Setup - raw = load_particle_step_data(args.data, args.event) - n_truth = raw['positions_mm'].shape[0] - truth_total_de = float(np.sum(raw['de'])) - truth_pos = np.asarray(raw['positions_mm']) - truth_de = np.asarray(raw['de']) - truth_tids = np.asarray(raw['track_ids']) - - detector_config = generate_detector(args.config_yaml) - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model='modified_box') - - # Build DepositData via build_deposit_data (multi-volume aware) - deposits = build_deposit_data( - raw['positions_mm'], raw['de'], - np.full(n_truth, DX_MM, dtype=np.float32), - sim_truth.config, - theta=raw['theta'], phi=raw['phi'], track_ids=raw['track_ids'], - t0_us=raw['t0_us'], interaction_ids=raw.get('interaction_ids'), - root_track_ids=raw.get('root_track_ids'), pdg=raw.get('pdg')) - - t0 = time.time() - response_signals, _, _ = sim_truth.process_event(deposits) - print(f"Truth sim: {time.time()-t0:.1f}s") - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=SOBOLEV_S) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - - truth_profiles = {} - for p in active_planes: - truth_profiles[p] = np.sum(np.abs(np.array(truth_signals[p])), axis=1) - - # Recombination constants from sim params - rp = sim_truth.default_sim_params.recomb_params - dens = float(rp.density) - alpha_r = float(rp.alpha) - beta_r = float(rp.beta) - field_kVcm = float(rp.field_strength_Vcm) / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = DX_MM / 10.0 - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - sim_opt = DetectorSimulator(detector_config, differentiable=True, n_segments=n_seg, - recombination_model='modified_box') - sim_params = sim_opt.default_sim_params - dx_val = DX_MM - def fwd_opt(positions_mm, de): - return sim_opt.forward_segments(sim_params, positions_mm, de, dx=dx_val) - - loss_fn = build_loss_fn(fwd_opt, truth_signals, spectral_weights, active_planes) - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Per-track jitter init - rng = np.random.RandomState(42) - e_scale = n_truth / n_seg - indices = rng.choice(n_truth, size=n_seg, replace=False) - init_pos = truth_pos[indices].copy() - init_de = truth_de[indices].copy() * e_scale - init_tids = truth_tids[indices] - for tid in np.unique(init_tids): - init_pos[init_tids == tid] += rng.normal(0, track_jitter_mm, size=3) - init_de *= rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - print("JIT warmup...") - t0 = time.time() - _ = grad_fn(init_params) - print(f"Done in {time.time()-t0:.1f}s\n") - - def compute_Q(de_arr): - return (dx_cm / B_eff) * np.log(np.maximum(ALPHA_RECOMB + B_eff * de_arr / dx_cm, 1.0)) - truth_total_Q = compute_Q(truth_de).sum() - - # Training - schedule = optax.exponential_decay(init_value=lr, transition_steps=1, decay_rate=decay_rate) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - - # Storage - actual_checkpoint_steps = [] - checkpoint_losses = [] - checkpoint_params_list = [] - de_history = [] - - losses = [] - cumulative_relocs = 0 - t_start = time.time() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(lr_e_mult) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add(lr_cur * noise_lr * jax.random.normal(nk, shape=(n_seg, 3))) - - if step >= warmup and step % reloc_every == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, recomb_constants, max_reloc) - cumulative_relocs += int(n_reloc) - - loss_val = float(total_loss) - losses.append(loss_val) - - # Power-law checkpoints - if step in checkpoint_set: - actual_checkpoint_steps.append(step) - checkpoint_losses.append(loss_val) - checkpoint_params_list.append(np.array(params)) - - # dE histogram - p_np = np.array(params[:, 3]) - alive_de = p_np[p_np > DEFAULTS['death_thresh']] - n_dead = int(np.sum(p_np <= DEFAULTS['death_thresh'])) - de_history.append((alive_de.copy(), n_dead)) - - if step % 50 == 0 or step == total_steps - 1: - p_np = np.array(params) - alive = p_np[:, 3] > 0.012 - sim_Q = compute_Q(p_np[alive, 3]).sum() - q_ratio = sim_Q / truth_total_Q - n_dead = int((~alive).sum()) - n_cp_so_far = len(actual_checkpoint_steps) - print(f" Step {step:5d}: loss={loss_val:.6f} Q={q_ratio:.3f} " - f"dead={n_dead} cp={n_cp_so_far} ({time.time()-t_start:.0f}s)", - flush=True) - - print(f"\nDone in {time.time()-t_start:.0f}s") - print(f"Saved {len(actual_checkpoint_steps)} checkpoints") - - # Stack checkpoint params - checkpoint_params = np.stack(checkpoint_params_list, axis=0) - - # Save - save_path = os.path.join(OUT_DIR, 'best_final_v2.npz') - save_data = { - 'checkpoint_steps': np.array(actual_checkpoint_steps), - 'checkpoint_losses': np.array(checkpoint_losses), - 'checkpoint_params': checkpoint_params, - 'truth_pos': truth_pos, 'truth_de': truth_de, - 'n_truth': n_truth, 'n_seg': n_seg, 'total_steps': total_steps, - 'truth_total_de': truth_total_de, 'dx_mm': DX_MM, - 'B_eff': B_eff, 'alpha': alpha_r, - 'losses': np.array(losses), - 'active_planes': np.array(active_planes), - 'checkpoint_alpha': alpha, - 'de_history_steps': np.array(actual_checkpoint_steps), - 'n_de_hist': len(de_history), - } - for i, (alive_de, n_dead) in enumerate(de_history): - save_data[f'de_hist_{i}_alive'] = alive_de - save_data[f'de_hist_{i}_dead'] = n_dead - for p in active_planes: - save_data[f'truth_profile_{p}'] = truth_profiles[p] - - np.savez_compressed(save_path, **save_data) - print(f"Saved to {save_path} ({os.path.getsize(save_path)/1e6:.1f} MB)") - - -if __name__ == '__main__': - main() diff --git a/closure/segments/sweep.py b/closure/segments/sweep.py deleted file mode 100644 index 1807423..0000000 --- a/closure/segments/sweep.py +++ /dev/null @@ -1,353 +0,0 @@ -""" -Systematic hyperparameter study for Sobolev s=1.0. - -Runs sweeps sequentially, appends results to a findings file. -Each sweep is a set of combos varying one parameter. - -Usage: - python3 closure/segments/sweep.py --data out.h5 --event 2 --sweep lr_emult - python3 closure/segments/sweep.py --data out.h5 --event 2 --sweep lr_decay - python3 closure/segments/sweep.py --data out.h5 --event 2 --sweep noise - python3 closure/segments/sweep.py --data out.h5 --event 2 --sweep reloc - python3 closure/segments/sweep.py --data out.h5 --event 2 --sweep warmup - python3 closure/segments/sweep.py --data out.h5 --event 2 --sweep steps - python3 closure/segments/sweep.py --data out.h5 --event 2 --sweep nseg -""" - -import os, argparse, time, json - -import jax, jax.numpy as jnp, numpy as np, optax -from tools.geometry import generate_detector -from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data, build_deposit_data -from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -from closure.segments.run import DEFAULTS, PLANE_NAMES, relocate_segments - -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) -FINDINGS_FILE = os.path.join(OUT_DIR, 'FINDINGS_S1.md') -SOBOLEV_S = 1.0 - -# Default best config from previous sweeps (adapted for s=1.0) -BEST = { - 'lr': 1.0, 'decay_rate': 0.999, 'lr_e_mult': 0.003, - 'warmup': 100, 'noise_lr': 0.3, 'l1': 0.0, - 'reloc_every': 25, 'max_reloc': 100, - 'n_seg': 10000, 'steps': 1500, -} - -SWEEPS = { - 'lr_emult': { - 'desc': 'lr_e_mult sweep (s=1.0)', - 'vary': 'lr_e_mult', - 'values': [0.001, 0.003, 0.005, 0.01], - }, - 'lr_decay': { - 'desc': 'LR x decay sweep (s=1.0)', - 'vary': ['lr', 'decay_rate'], - 'combos': [ - {'lr': 0.5, 'decay_rate': 0.9995}, - {'lr': 0.7, 'decay_rate': 0.999}, - {'lr': 1.0, 'decay_rate': 0.999}, - {'lr': 1.0, 'decay_rate': 0.9985}, - {'lr': 1.5, 'decay_rate': 0.998}, - {'lr': 2.0, 'decay_rate': 0.997}, - ], - }, - 'noise': { - 'desc': 'Noise sweep (s=1.0)', - 'vary': 'noise_lr', - 'values': [0.0, 0.1, 0.3, 0.5, 1.0], - }, - 'reloc': { - 'desc': 'Relocation config sweep (s=1.0)', - 'vary': ['reloc_every', 'max_reloc'], - 'combos': [ - {'reloc_every': 25, 'max_reloc': 50}, - {'reloc_every': 25, 'max_reloc': 100}, - {'reloc_every': 25, 'max_reloc': 200}, - {'reloc_every': 50, 'max_reloc': 100}, - {'reloc_every': 10, 'max_reloc': 50}, - ], - }, - 'warmup': { - 'desc': 'Warmup sweep (s=1.0)', - 'vary': 'warmup', - 'values': [50, 100, 200, 300], - }, - 'steps': { - 'desc': 'Step count sweep (s=1.0)', - 'vary': 'steps', - 'values': [500, 1000, 1500, 2000, 3000], - }, - 'nseg': { - 'desc': 'Segment count sweep (s=1.0)', - 'vary': 'n_seg', - 'values': [5000, 10000, 20000], - }, -} - - -def setup(h5_path, event_idx, n_seg, dx_mm, config_yaml, recomb_model='modified_box'): - """Setup shared resources.""" - raw = load_particle_step_data(h5_path, event_idx) - n_truth = raw['positions_mm'].shape[0] - truth_total_de = float(np.sum(raw['de'])) - truth_pos = np.asarray(raw['positions_mm']) - truth_de = np.asarray(raw['de']) - print(f"Truth: {n_truth:,} segs, dE={truth_total_de:.1f} MeV, dx_mm={dx_mm}") - - detector_config = generate_detector(config_yaml) - total_pad = ((max(200_000, n_truth + 1000) + 9999) // 10000) * 10000 - - sim_truth = DetectorSimulator(detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, include_electronics=False, - include_track_hits=False, recombination_model=recomb_model) - - # Build DepositData via build_deposit_data (multi-volume aware) - deposits = build_deposit_data( - raw['positions_mm'], raw['de'], - np.full(n_truth, dx_mm, dtype=np.float32), - sim_truth.config, - theta=raw['theta'], phi=raw['phi'], track_ids=raw['track_ids'], - t0_us=raw['t0_us'], interaction_ids=raw.get('interaction_ids'), - root_track_ids=raw.get('root_track_ids'), pdg=raw.get('pdg')) - - response_signals, _, _ = sim_truth.process_event(deposits) - - truth_dict, active_planes, sob_dict = {}, [], {} - for (side, plane), signal in response_signals.items(): - pidx = side * 3 + plane - signal = jnp.asarray(signal) - truth_dict[pidx] = signal - if jnp.any(signal != 0): - active_planes.append(pidx) - sob_dict[pidx] = make_sobolev_weight(*signal.shape, s=SOBOLEV_S) - active_planes.sort() - truth_signals = tuple(truth_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - spectral_weights = tuple(sob_dict.get(i, jnp.zeros((1,1))) for i in range(6)) - planes_tuple = tuple(active_planes) - - # Recombination constants from sim params - rp = sim_truth.default_sim_params.recomb_params - dens = float(rp.density) - alpha_r = float(rp.alpha) - if recomb_model == 'emb': - beta_r = float(rp.beta_90) - else: - beta_r = float(rp.beta) - field_kVcm = float(rp.field_strength_Vcm) / 1000.0 - B_eff = beta_r / dens / field_kVcm - dx_cm = dx_mm / 10.0 - recomb_constants = (DEFAULTS['death_thresh'], alpha_r, B_eff, dx_cm) - - return { - 'detector_config': detector_config, - 'truth_signals': truth_signals, - 'spectral_weights': spectral_weights, - 'planes_tuple': planes_tuple, - 'active_planes': active_planes, - 'recomb_constants': recomb_constants, - 'truth_pos': truth_pos, - 'truth_de': truth_de, - 'truth_total_de': truth_total_de, - 'n_truth': n_truth, - 'dx_mm': dx_mm, - 'recomb_model': recomb_model, - } - - -def run_one(shared, cfg): - """Run one configuration. Returns result dict.""" - n_seg = cfg['n_seg'] - total_steps = cfg['steps'] - - sim_opt = DetectorSimulator( - shared['detector_config'], differentiable=True, n_segments=n_seg, - recombination_model=shared['recomb_model']) - sim_params = sim_opt.default_sim_params - dx_val = shared['dx_mm'] - - def fwd_opt(positions_mm, de): - return sim_opt.forward_segments(sim_params, positions_mm, de, dx=dx_val) - - def loss_fn(params): - positions_mm = params[:, :3] - de = params[:, 3] - sigs = fwd_opt(positions_mm, de) - loss = sobolev_loss_geomean_log1p(sigs, shared['truth_signals'], - shared['spectral_weights'], - planes=shared['planes_tuple']) - return loss, loss - - grad_fn = jax.value_and_grad(loss_fn, has_aux=True) - - # Init - rng = np.random.RandomState(42) - n_truth = shared['n_truth'] - e_scale = n_truth / n_seg - replace = n_seg > n_truth - indices = rng.choice(n_truth, size=n_seg, replace=replace) - init_pos = shared['truth_pos'][indices].copy() + rng.normal(0, 100.0, size=(n_seg, 3)) - init_de = shared['truth_de'][indices].copy() * e_scale * rng.uniform(0.2, 1.8, size=n_seg) - init_de = np.maximum(init_de, 0.001) - init_params = jnp.array(np.column_stack([init_pos, init_de])) - - # JIT warmup - _ = grad_fn(init_params) - - schedule = optax.exponential_decay( - init_value=cfg['lr'], transition_steps=1, decay_rate=cfg['decay_rate']) - optimizer = optax.adam(schedule, b1=0.9, b2=0.999) - params = init_params - opt_state = optimizer.init(params) - rng_key = jax.random.PRNGKey(123) - cumulative_relocs = 0 - - losses = [] - t0 = time.time() - - for step in range(total_steps): - (total_loss, _), grads = grad_fn(params) - updates, opt_state = optimizer.update(grads, opt_state, params) - updates = updates.at[:, 3].multiply(cfg['lr_e_mult']) - params = optax.apply_updates(params, updates) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - if cfg['noise_lr'] > 0: - lr_cur = float(schedule(step)) - rng_key, nk = jax.random.split(rng_key) - params = params.at[:, :3].add( - lr_cur * cfg['noise_lr'] * jax.random.normal(nk, shape=(n_seg, 3))) - - if cfg['l1'] > 0 and step >= cfg['warmup']: - params = params.at[:, 3].add(-cfg['l1']) - params = params.at[:, 3].set(jnp.maximum(params[:, 3], 0.001)) - - if step >= cfg['warmup'] and step % cfg['reloc_every'] == 0: - params, opt_state, rng_key, n_reloc = relocate_segments( - params, opt_state, rng_key, - shared['recomb_constants'], cfg['max_reloc']) - cumulative_relocs += int(n_reloc) - - losses.append(float(total_loss)) - - dt = time.time() - t0 - final_params = np.array(params) - final_de = float(np.sum(final_params[:, 3])) - de_ratio = final_de / shared['truth_total_de'] - n_dead = int(np.sum(final_params[:, 3] <= DEFAULTS['death_thresh'])) - - return { - 'loss': losses[-1], - 'de_ratio': de_ratio, - 'dead': n_dead, - 'relocs': cumulative_relocs, - 'time': dt, - 'ms_per_step': dt / total_steps * 1000, - } - - -def append_findings(sweep_name, desc, h5_file, event_idx, dx_mm, results_table): - """Append results to findings file.""" - with open(FINDINGS_FILE, 'a') as f: - f.write(f"\n## {sweep_name}: {desc}\n") - f.write(f"File: {h5_file}, event={event_idx}, dx={dx_mm}mm, s={SOBOLEV_S}\n\n") - f.write(results_table) - f.write('\n') - - -def main(): - parser = argparse.ArgumentParser( - description='Systematic hyperparameter study for Sobolev s=1.0') - parser.add_argument('--data', required=True, - help='Path to HDF5 event file') - parser.add_argument('--config-yaml', default='config/cubic_wireplane_config.yaml', - help='Path to detector YAML config (default: config/cubic_wireplane_config.yaml)') - parser.add_argument('--event', type=int, default=2) - parser.add_argument('--sweep', required=True, choices=list(SWEEPS.keys())) - parser.add_argument('--dx', type=float, default=0.3, - help='dx_mm for both truth and optimizer (default: 0.3 for out.h5)') - args = parser.parse_args() - - sweep_def = SWEEPS[args.sweep] - print(f"{'='*60}") - print(f"SWEEP: {args.sweep} -- {sweep_def['desc']}") - print(f"File: {args.data}, event={args.event}, dx={args.dx}mm") - print(f"{'='*60}\n") - - # Build combo list - if 'combos' in sweep_def: - combos = sweep_def['combos'] - else: - vary_key = sweep_def['vary'] - combos = [{vary_key: v} for v in sweep_def['values']] - - # For nseg sweep, we need to rebuild sim for each n_seg - # For steps sweep, same sim different step counts - # Handle by rebuilding per-combo if n_seg changes - - all_results = [] - shared = None - last_n_seg = None - - for i, combo in enumerate(combos): - cfg = dict(BEST) - cfg.update(combo) - - # Rebuild shared if n_seg changed or first run - if shared is None or cfg['n_seg'] != last_n_seg: - print(f"Setting up for n_seg={cfg['n_seg']}...") - shared = setup(args.data, args.event, cfg['n_seg'], args.dx, - args.config_yaml) - last_n_seg = cfg['n_seg'] - - combo_name = ', '.join(f'{k}={v}' for k, v in combo.items()) - print(f"\n[{i+1}/{len(combos)}] {combo_name}...") - - t0 = time.time() - try: - result = run_one(shared, cfg) - print(f" loss={result['loss']:.6f} dE_ratio={result['de_ratio']:.3f} " - f"dead={result['dead']} {result['time']:.0f}s") - except Exception as e: - print(f" FAILED: {e}") - result = {'loss': float('nan'), 'de_ratio': 0, 'dead': -1, 'relocs': 0, - 'time': time.time()-t0, 'ms_per_step': 0} - - result['combo'] = combo - all_results.append(result) - - # Summary - print(f"\n{'='*60}") - print(f"SUMMARY -- {args.sweep}") - print(f"{'='*60}") - - header_keys = list(combos[0].keys()) - header = '| ' + ' | '.join(header_keys) + ' | Loss | dE_ratio | Dead | Time |\n' - header += '|' + '|'.join(['---'] * (len(header_keys) + 4)) + '|\n' - rows = '' - for r in all_results: - vals = ' | '.join(str(r['combo'].get(k, '')) for k in header_keys) - rows += f"| {vals} | {r['loss']:.6f} | {r['de_ratio']:.3f} | {r['dead']} | {r['time']:.0f}s |\n" - - table = header + rows - print(table) - - # Save - append_findings(args.sweep, sweep_def['desc'], args.data, args.event, args.dx, table) - print(f"Appended to {FINDINGS_FILE}") - - # Also save NPZ - save_path = os.path.join(OUT_DIR, f'sweep_s1_{args.sweep}_{os.path.basename(args.data)}_ev{args.event}.npz') - save_data = {} - for i, r in enumerate(all_results): - save_data[f'combo_{i}_loss'] = r['loss'] - save_data[f'combo_{i}_de_ratio'] = r['de_ratio'] - save_data[f'combo_{i}_dead'] = r['dead'] - save_data[f'combo_{i}_config'] = json.dumps(r['combo']) - np.savez(save_path, **save_data) - print(f"Saved to {save_path}") - - -if __name__ == '__main__': - main() diff --git a/closure/segments/truth_event.png b/closure/segments/truth_event.png deleted file mode 100644 index c6433bb..0000000 Binary files a/closure/segments/truth_event.png and /dev/null differ diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..cfe73b5 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,22 @@ +# Examples: differentiable reconstruction with JAXTPC + +Each example fits something through the differentiable simulator +(`DetectorSimulator.forward_segments`) against a simulated truth. Run them from +the repository root; outputs go to `examples//outputs/` (git-ignored) or to +`$JAXTPC_EXAMPLES_OUT`. A GPU is recommended. + +| Example | What it fits | Command | Reference result (A100) | +|---|---|---|---| +| `muon/` | a muon track: vertex, direction, energy | `python -m examples.muon.run A --steps 1200` | start A converges to <0.3 mm, <0.05°, 1 MeV of 500 MeV (~80 s). Start B stalls in a local minimum. | +| `muon/detector_surfaces.py` | loss and AD-vs-finite-difference gradient vs drift velocity, lifetime, diffusion, recombination | `python -m examples.muon.detector_surfaces` | lifetime and diffusion: AD = FD to <0.5%. | +| `muon/event_display.py`, `muon/render_3d.py` | plots for the muon example | `python -m examples.muon.event_display` | | +| `segments/` | a whole event as N point charges `[x, y, z, dE]` (Adam + relocation) | `python -m examples.segments.run --data muon.h5 --n-seg 2000 --steps 2000 --mode full` | on `muon.h5`: mean distance to truth 0.8 mm (from 47 mm), charge ratio 1.000 (~6 min). | +| `segments/validate_convergence.py` | gradient direction and loss reduction check | `python -m examples.segments.validate_convergence --data muon.h5 --n-seg 1000` | ~89% of position gradients point toward truth. | +| `mcs/` | a scattering muon: globals, then per-segment scattering angles | `python -m examples.mcs.run --mode staged --steps 1050 --stage1-steps 250 --lr-phase2 0.003 --lr-scat 0.01 --decay 0.9995` | vertex 0.4 ± 0.2 mm, energy −6 ± 8 MeV over 5 seeds; net scattering angle recovered (corr. 0.98), individual 3 mm kinks not (corr. 0.24–0.37). | +| `mcs/validate_forward.py` | MCS forward model: geometry, CSDA, AD vs FD (no detector) | `python -m examples.mcs.validate_forward` | 14/14 checks pass. | + +`FINDINGS_MCS.md` and `segments/FINDINGS_S1.md` record how the recipes were chosen. + +Known limitation: `forward_segments` has no per-deposit start time (t0), so +`segments/validate_pipeline.py` (production vs differentiable consistency) fails on +events with nonzero t0 (loss 0.17 on `muon.h5`; exact with t0 = 0). diff --git a/closure/__init__.py b/examples/__init__.py similarity index 100% rename from closure/__init__.py rename to examples/__init__.py diff --git a/closure/mcs/FINDINGS_MCS.md b/examples/mcs/FINDINGS_MCS.md similarity index 100% rename from closure/mcs/FINDINGS_MCS.md rename to examples/mcs/FINDINGS_MCS.md diff --git a/closure/mcs/__init__.py b/examples/mcs/__init__.py similarity index 100% rename from closure/mcs/__init__.py rename to examples/mcs/__init__.py diff --git a/closure/mcs/forward.py b/examples/mcs/forward.py similarity index 99% rename from closure/mcs/forward.py rename to examples/mcs/forward.py index 585635c..9c63aa1 100644 --- a/closure/mcs/forward.py +++ b/examples/mcs/forward.py @@ -18,7 +18,7 @@ import jax import jax.numpy as jnp -from closure.mcs.mcs_physics import ( +from examples.mcs.mcs_physics import ( _perpendicular_basis, highland_theta0, _ke_to_beta_p, diff --git a/closure/mcs/mcs_physics.py b/examples/mcs/mcs_physics.py similarity index 99% rename from closure/mcs/mcs_physics.py rename to examples/mcs/mcs_physics.py index ee1bc72..00dd58b 100644 --- a/closure/mcs/mcs_physics.py +++ b/examples/mcs/mcs_physics.py @@ -137,7 +137,7 @@ def generate_mcs_muon_segments(energy, start, theta, phi, step_size_mm, angles the two agree to high precision; this generator exists as the ground-truth cross-check. - Parameters mirror :func:`closure.mcs.forward.generate_mcs_truth`. + Parameters mirror :func:`examples.mcs.forward.generate_mcs_truth`. Returns ------- diff --git a/closure/mcs/multi_event.py b/examples/mcs/multi_event.py similarity index 98% rename from closure/mcs/multi_event.py rename to examples/mcs/multi_event.py index ff85b62..d845e0a 100644 --- a/closure/mcs/multi_event.py +++ b/examples/mcs/multi_event.py @@ -7,7 +7,7 @@ the wall time. Truth signals are passed as a traced argument so the JIT compiles once and is reused for every event. - python3 -m closure.mcs.multi_event + python3 -m examples.mcs.multi_event """ import time import jax @@ -15,11 +15,11 @@ import numpy as np import optax -from closure.mcs.run import ( +from examples.mcs.run import ( project_unit_circle, N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, SCALES, ANGLE_SCALE, SOBOLEV_S, TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, ) -from closure.mcs.forward import ( +from examples.mcs.forward import ( generate_mcs_truth, mcs_cumsum_forward, build_mcs_forward, mask_outside_volume, highland_prior, ) diff --git a/closure/mcs/render_closure.py b/examples/mcs/render_closure.py similarity index 96% rename from closure/mcs/render_closure.py rename to examples/mcs/render_closure.py index 7f43a83..25f2ab7 100644 --- a/closure/mcs/render_closure.py +++ b/examples/mcs/render_closure.py @@ -5,7 +5,7 @@ truth signal, the reconstructed-track signal, and their difference — the post-reconstruction residual. - python3 -m closure.mcs.render_closure + python3 -m examples.mcs.render_closure """ import time @@ -17,13 +17,13 @@ matplotlib.use('Agg') import matplotlib.pyplot as plt -import closure.mcs.run as R -from closure.mcs.run import ( +import examples.mcs.run as R +from examples.mcs.run import ( build_globals_only_loss, build_full_loss, run_optimization, project_unit_circle, N_SEGMENTS, STEP_SIZE_MM, STEP_SIZE_CM, SCALES, ANGLE_SCALE, SOBOLEV_S, TRUTH_X, TRUTH_Y, TRUTH_Z, TRUTH_THETA, TRUTH_PHI, TRUTH_ENERGY, PLANE_NAMES, ) -from closure.mcs.forward import ( +from examples.mcs.forward import ( generate_mcs_truth, mcs_cumsum_forward, build_mcs_forward, mask_outside_volume, highland_prior, ) @@ -32,7 +32,8 @@ from tools.simulation import DetectorSimulator from tools.losses import make_sobolev_weight, sobolev_loss_geomean_log1p -OUT = os.path.dirname(os.path.abspath(__file__)) +OUT = os.environ.get('JAXTPC_EXAMPLES_OUT') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs') +os.makedirs(OUT, exist_ok=True) def bbox(img, pad=25, thr=0.03): diff --git a/closure/mcs/run.py b/examples/mcs/run.py similarity index 98% rename from closure/mcs/run.py rename to examples/mcs/run.py index 22f3a9a..1279c2a 100644 --- a/closure/mcs/run.py +++ b/examples/mcs/run.py @@ -11,8 +11,8 @@ --mode staged (Level 6b): 200 steps globals-only, then all Run from project root: - python3 -m closure.mcs.run --mode globals-only --steps 300 - python3 -m closure.mcs.run --mode full --steps 500 + python3 -m examples.mcs.run --mode globals-only --steps 300 + python3 -m examples.mcs.run --mode full --steps 500 Migrated from closure_analysis_MCS/mcs_closure.py. """ @@ -26,7 +26,7 @@ import time import os -from closure.mcs.forward import ( +from examples.mcs.forward import ( mcs_cumsum_forward, generate_mcs_truth, highland_prior, @@ -85,7 +85,8 @@ PARAM_NAMES = ['x', 'y', 'z', 'sin_th', 'cos_th', 'sin_ph', 'cos_ph', 'energy'] PLANE_NAMES = ['east_U', 'east_V', 'east_Y', 'west_U', 'west_V', 'west_Y'] -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) +OUT_DIR = os.environ.get('JAXTPC_EXAMPLES_OUT') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs') +os.makedirs(OUT_DIR, exist_ok=True) # ============================================================================= diff --git a/closure/mcs/validate_forward.py b/examples/mcs/validate_forward.py similarity index 99% rename from closure/mcs/validate_forward.py rename to examples/mcs/validate_forward.py index 25e34ef..56a8c12 100644 --- a/closure/mcs/validate_forward.py +++ b/examples/mcs/validate_forward.py @@ -6,7 +6,7 @@ Level 2 — Gradient checks (finite differences) Run from project root: - python3 -m closure.mcs.validate_forward + python3 -m examples.mcs.validate_forward Migrated from closure_analysis_MCS/validate_forward.py. """ @@ -16,7 +16,7 @@ import jax.numpy as jnp import numpy as np -from closure.mcs.forward import ( +from examples.mcs.forward import ( exclusive_cumsum, mcs_cumsum_positions, mcs_cumsum_forward, @@ -26,7 +26,7 @@ load_dedx_table_jax, _get_consistent_csda, ) -from closure.mcs.mcs_physics import ( +from examples.mcs.mcs_physics import ( _perpendicular_basis, _ke_to_beta_p, generate_mcs_muon_segments, diff --git a/closure/mcs/validate_wire.py b/examples/mcs/validate_wire.py similarity index 96% rename from closure/mcs/validate_wire.py rename to examples/mcs/validate_wire.py index 7ee5835..027e8f5 100644 --- a/closure/mcs/validate_wire.py +++ b/examples/mcs/validate_wire.py @@ -5,7 +5,7 @@ 4b: dL/d(dtheta1[k]) is nonzero at multiple segment positions. Run from project root: - python3 -m closure.mcs.validate_wire + python3 -m examples.mcs.validate_wire Migrated from closure_analysis_MCS/validate_wire_sensitivity.py. """ @@ -17,7 +17,7 @@ import numpy as np import time -from closure.mcs.forward import ( +from examples.mcs.forward import ( mcs_cumsum_forward, generate_mcs_truth, build_mcs_forward, @@ -45,7 +45,8 @@ PHI = np.pi / 6 PLANE_NAMES = ['east_U', 'east_V', 'east_Y', 'west_U', 'west_V', 'west_Y'] -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) +OUT_DIR = os.environ.get('JAXTPC_EXAMPLES_OUT') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs') +os.makedirs(OUT_DIR, exist_ok=True) results = [] diff --git a/closure/muon/__init__.py b/examples/muon/__init__.py similarity index 100% rename from closure/muon/__init__.py rename to examples/muon/__init__.py diff --git a/closure/muon/detector_surfaces.py b/examples/muon/detector_surfaces.py similarity index 97% rename from closure/muon/detector_surfaces.py rename to examples/muon/detector_surfaces.py index 3124d8c..97263ae 100644 --- a/closure/muon/detector_surfaces.py +++ b/examples/muon/detector_surfaces.py @@ -33,7 +33,8 @@ STEP_SIZE_MM = 0.5 HALF_EXT = (2160.0, 2160.0, 2160.0) N_SWEEP = 40 -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) +OUT_DIR = os.environ.get('JAXTPC_EXAMPLES_OUT') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs') +os.makedirs(OUT_DIR, exist_ok=True) # Truth muon parameters TRUTH_X, TRUTH_Y, TRUTH_Z = -200.0, 0.0, 100.0 @@ -103,7 +104,7 @@ def main(): det = generate_detector('config/cubic_wireplane_config.yaml') sim = DetectorSimulator( det, differentiable=True, n_segments=N_SEGMENTS, - include_noise=False, include_electronics=False, + include_intrinsic_noise=False, include_electronics=False, include_track_hits=False, ) truth_params = sim.default_sim_params diff --git a/closure/muon/event_display.py b/examples/muon/event_display.py similarity index 98% rename from closure/muon/event_display.py rename to examples/muon/event_display.py index c2e79f6..ff02691 100644 --- a/closure/muon/event_display.py +++ b/examples/muon/event_display.py @@ -52,7 +52,8 @@ TRUTH_PHI = np.pi / 2 # in y-z plane (no x component) TRUTH_ENERGY = 200.0 # MeV -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) +OUT_DIR = os.environ.get('JAXTPC_EXAMPLES_OUT') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs') +os.makedirs(OUT_DIR, exist_ok=True) # Perturbation sizes for parameter variation plots PERTURBATIONS = { @@ -153,8 +154,8 @@ def main(): print("\nGenerating event display...") wire_dict = signals_to_dict(truth_signals) fig = visualize_wire_signals( - wire_dict, detector_config, - sparse_data=False, threshold_enc=0, gamma=0.3, + wire_dict, sim.config, + sparse=False, threshold_enc=0, gamma=0.3, ) fig.suptitle( f'Muon Event Display — {TRUTH_ENERGY:.0f} MeV, ' diff --git a/closure/muon/render_3d.py b/examples/muon/render_3d.py similarity index 98% rename from closure/muon/render_3d.py rename to examples/muon/render_3d.py index c78ec60..c9bf974 100644 --- a/closure/muon/render_3d.py +++ b/examples/muon/render_3d.py @@ -27,7 +27,8 @@ COLORS = {'A': '#1f77b4', 'B': '#ff7f0e', 'C': '#2ca02c', 'D': '#d62728'} -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) +OUT_DIR = os.environ.get('JAXTPC_EXAMPLES_OUT') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs') +os.makedirs(OUT_DIR, exist_ok=True) # ============================================================================= diff --git a/closure/muon/run.py b/examples/muon/run.py similarity index 98% rename from closure/muon/run.py rename to examples/muon/run.py index c142869..f97b5b7 100644 --- a/closure/muon/run.py +++ b/examples/muon/run.py @@ -50,7 +50,8 @@ SCALES = np.array([200.0, 200.0, 200.0, 1.0, 1.0, 1.0, 1.0, 500.0]) SCALES_JAX = jnp.array(SCALES, dtype=jnp.float32) -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) +OUT_DIR = os.environ.get('JAXTPC_EXAMPLES_OUT') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs') +os.makedirs(OUT_DIR, exist_ok=True) INIT_CONFIGS = { 'A': {'dx': +400.0, 'dy': +300.0, 'dz': -300.0, diff --git a/closure/segments/FINDINGS_S1.md b/examples/segments/FINDINGS_S1.md similarity index 100% rename from closure/segments/FINDINGS_S1.md rename to examples/segments/FINDINGS_S1.md diff --git a/closure/segments/__init__.py b/examples/segments/__init__.py similarity index 100% rename from closure/segments/__init__.py rename to examples/segments/__init__.py diff --git a/closure/segments/run.py b/examples/segments/run.py similarity index 99% rename from closure/segments/run.py rename to examples/segments/run.py index f76203d..c89a7a0 100644 --- a/closure/segments/run.py +++ b/examples/segments/run.py @@ -33,7 +33,8 @@ # Constants # ============================================================================= -OUT_DIR = os.path.dirname(os.path.abspath(__file__)) +OUT_DIR = os.environ.get('JAXTPC_EXAMPLES_OUT') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs') +os.makedirs(OUT_DIR, exist_ok=True) # Plot font sizes (from run_overcomplete_combos.py) LABEL_SIZE = 16 @@ -230,7 +231,7 @@ def run_training_loop(grad_fn, init_params, n_seg, total_steps, mode, cfg): dead_counts = [] relocation_steps = [] cumulative_relocs = 0 - max_reloc = cfg.get('max_reloc', None) or n_seg + max_reloc = min(cfg.get('max_reloc', None) or n_seg, n_seg) # buffers are sized max_reloc reloc_every = cfg.get('reloc_every', 50) print_every = max(20, total_steps // 30) @@ -620,7 +621,7 @@ def run_full_closure(h5_path, event_idx=0, n_seg=40000, total_steps=3000, use_bucketed=False, total_pad=total_pad, response_chunk_size=50_000, - include_noise=False, + include_intrinsic_noise=False, include_electronics=False, include_track_hits=False, recombination_model=cfg['recomb_model'], @@ -785,7 +786,7 @@ def compute_Q(de_arr, dx_cm_arr=None): de_history_steps = [] relocation_steps = [] cumulative_relocs = 0 - max_reloc = cfg.get('max_reloc', None) or n_seg + max_reloc = min(cfg.get('max_reloc', None) or n_seg, n_seg) # buffers are sized max_reloc reloc_every = cfg.get('reloc_every', 50) print_every = max(20, total_steps // 30) de_hist_every = max(1, total_steps // 200) diff --git a/closure/segments/validate_convergence.py b/examples/segments/validate_convergence.py similarity index 98% rename from closure/segments/validate_convergence.py rename to examples/segments/validate_convergence.py index f8a8cc1..3333d37 100644 --- a/closure/segments/validate_convergence.py +++ b/examples/segments/validate_convergence.py @@ -5,7 +5,7 @@ Runs a short optimization (200 steps) to verify loss decreases. Run from project root: - python3 -m closure.segments.validate_convergence --data mpvmpr_20.h5 + python3 -m examples.segments.validate_convergence --data mpvmpr_20.h5 """ import argparse, time @@ -30,7 +30,7 @@ def build_truth(raw, detector_config, dx_mm, recomb_model): total_pad = ((total_pad + 9999) // 10000) * 10000 sim = DetectorSimulator( detector_config, use_bucketed=False, total_pad=total_pad, - response_chunk_size=50_000, include_noise=False, + response_chunk_size=50_000, include_intrinsic_noise=False, include_electronics=False, include_track_hits=False, recombination_model=recomb_model) diff --git a/closure/segments/validate_pipeline.py b/examples/segments/validate_pipeline.py similarity index 98% rename from closure/segments/validate_pipeline.py rename to examples/segments/validate_pipeline.py index f22d431..b25b976 100644 --- a/closure/segments/validate_pipeline.py +++ b/examples/segments/validate_pipeline.py @@ -7,8 +7,8 @@ Forces dx=0.1mm for both truth and optimizer to eliminate dx mismatch. Run from project root: - python3 -m closure.segments.validate_pipeline --data mpvmpr_20.h5 - python3 -m closure.segments.validate_pipeline --data mpvmpr_20.h5 --n-seg 10000 + python3 -m examples.segments.validate_pipeline --data mpvmpr_20.h5 + python3 -m examples.segments.validate_pipeline --data mpvmpr_20.h5 --n-seg 10000 """ import argparse, time @@ -182,7 +182,7 @@ def validate(h5_path, config_path, event_idx=0, n_seg=10000, recomb_model='modif print(f"\n[1] Truth simulation (forced dx={DX_MM}mm, recomb={recomb_model})...") sim_truth = DetectorSimulator( detector_config, use_bucketed=False, total_pad=200_000, - response_chunk_size=50_000, include_noise=False, + response_chunk_size=50_000, include_intrinsic_noise=False, include_electronics=False, include_track_hits=False, recombination_model=recomb_model) diff --git a/notebooks/reco/README.md b/notebooks/reco/README.md index 97ff910..6c3c1df 100644 --- a/notebooks/reco/README.md +++ b/notebooks/reco/README.md @@ -1,6 +1,6 @@ # Reconstruction — closure methods -Reconstruction in JAXTPC **is** the closure methods in [`closure/`](../../closure): +Reconstruction in JAXTPC **is** the closure methods in [`examples/`](../../examples): differentiable optimization of an event's parameters through the simulator until the simulated readout matches the observed (truth) readout. They all share the same machinery — `DetectorSimulator(differentiable=True).forward_segments(...)` @@ -10,22 +10,22 @@ as the forward, the **Sobolev geomean-log1p loss** (`tools/losses.py`, | Notebook | Based on | Optimizes | Status | |---|---|---|---| -| `segments_closure.ipynb` | `closure/segments/run.py` | an event as **N point charges** `[x, y, z, dE]`, with Adam + **MCMC relocation** of dead segments (3DGS-MCMC style) | **built, verified ✓** | -| `muon_closure.ipynb` | `closure/muon/run.py` | a muon track from initial guesses (track-surface parameterization) | planned | +| `segments_closure.ipynb` | `examples/segments/run.py` | an event as **N point charges** `[x, y, z, dE]`, with Adam + **MCMC relocation** of dead segments (3DGS-MCMC style) | **built, verified ✓** | +| `muon_closure.ipynb` | `examples/muon/run.py` | a muon track from initial guesses (track-surface parameterization) | planned | -Each notebook is a runnable walkthrough of the corresponding `closure/` script on +Each notebook is a runnable walkthrough of the corresponding `examples/` script on a small event: build truth signals → build the differentiable forward → Sobolev loss → optimize → show the loss curve and truth-vs-reconstruction overlay. `segments_closure.ipynb` is verified end-to-end (oversampled point charges + the real `relocate_segments`; loss 0.89 → 0.0035 with 3 relocations). -> The **MCS closure** (`closure/mcs/`) is intentionally *not* surfaced as a -> notebook — it is research code (see `closure/mcs/FINDINGS_MCS.md`), kept in -> `closure/` only. +> The **MCS closure** (`examples/mcs/`) is intentionally *not* surfaced as a +> notebook — it is research code (see `examples/mcs/FINDINGS_MCS.md`), kept in +> `examples/mcs/` only. > The full closure scripts read a real edepsim HDF5 (`load_particle_step_data`). > The notebooks use a synthetic truth event so they run with no external data; -> the `closure/` scripts remain the reference for full-scale runs. +> the `examples/` scripts remain the reference for full-scale runs. **Not in scope** (per project direction): learned/NN reconstruction and wire-crossing "space points" — these are not the closure standard. diff --git a/notebooks/reco/segments_closure.ipynb b/notebooks/reco/segments_closure.ipynb index 651a995..bf18ebf 100644 --- a/notebooks/reco/segments_closure.ipynb +++ b/notebooks/reco/segments_closure.ipynb @@ -8,7 +8,7 @@ "# Segments closure (reconstruction)\n", "\n", "JAXTPC's standard event reconstruction — based on\n", - "[`closure/segments/run.py`](../../closure/segments/run.py). An event is\n", + "[`examples/segments/run.py`](../../examples/segments/run.py). An event is\n", "reconstructed as **N point charges** `[x,y,z,dE]`, optimized through the\n", "differentiable simulator against the observed wire signals with the **Sobolev\n", "loss**, **Adam** (per-parameter learning rates), and **MCMC relocation** of dead\n", @@ -49,7 +49,7 @@ "from tools.geometry import generate_detector\n", "from tools.loader import build_deposit_data\n", "from tools.losses import sobolev_loss_geomean_log1p, make_sobolev_weight\n", - "from closure.segments.run import relocate_segments # the real MCMC relocation\n", + "from examples.segments.run import relocate_segments # the real MCMC relocation\n", "detector = generate_detector('config/cubic_wireplane_config.yaml')\n", "N_TRUTH = 400; N_SEG = 1200; DX_MM = 4.0 # oversample 3x -> relocation matters\n", "PLANE_NAMES = ['U0','V0','Y0','U1','V1','Y1']\n" @@ -220,7 +220,7 @@ "## Next\n", "- `mcs_closure.ipynb` — MCS muon (vertex/direction/energy + scattering angles)\n", "- `muon_closure.ipynb` — muon track from initial guesses\n", - "- `closure/segments/run.py` — full method on real edepsim events\n" + "- `examples/segments/run.py` — full method on real edepsim events\n" ] } ], diff --git a/tests/TESTS.md b/tests/TESTS.md index bdd4f21..ae6cb38 100644 --- a/tests/TESTS.md +++ b/tests/TESTS.md @@ -17,6 +17,12 @@ JAX_PLATFORM_NAME=cpu python3 -m pytest tests/ -v --cov=tools --cov-report=term- ## Test Modules +### test_examples.py + +Smoke tests for `examples/`. `test_mcs_forward_model` (MCS forward-model physics +checks, no detector) runs by default; the end-to-end example runs (muon fit and +event display, MCS globals fit, small segments run) need `JAXTPC_SLOW_TESTS=1`. + ### test_recombination.py (11 tests) Modified Box model charge recombination (`tools/recombination.py`). diff --git a/tests/test_examples.py b/tests/test_examples.py new file mode 100644 index 0000000..03d8721 --- /dev/null +++ b/tests/test_examples.py @@ -0,0 +1,49 @@ +"""Smoke tests for examples/ (run as subprocesses from the repo root). + +The MCS forward-model checks run by default (no detector). The end-to-end example +runs are slow (minutes, GPU recommended) and run only with JAXTPC_SLOW_TESTS=1. +""" +import os +import subprocess +import sys + +import pytest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +slow = pytest.mark.skipif(os.environ.get('JAXTPC_SLOW_TESTS') != '1', + reason='slow example run; set JAXTPC_SLOW_TESTS=1') + + +def _run(args, tmp_path, timeout=1800): + env = dict(os.environ, JAXTPC_EXAMPLES_OUT=str(tmp_path), MPLBACKEND='Agg') + r = subprocess.run([sys.executable, '-m', *args], cwd=ROOT, env=env, + capture_output=True, text=True, timeout=timeout) + assert r.returncode == 0, (r.stdout[-3000:] + r.stderr[-3000:]) + return r.stdout + + +def test_mcs_forward_model(tmp_path): + _run(['examples.mcs.validate_forward'], tmp_path) + + +@slow +def test_muon_track_fit(tmp_path): + _run(['examples.muon.run', 'A', '--steps', '20'], tmp_path) + assert (tmp_path / 'optimization_A.npz').exists() + + +@slow +def test_muon_event_display(tmp_path): + _run(['examples.muon.event_display'], tmp_path) + + +@slow +def test_mcs_globals_fit(tmp_path): + _run(['examples.mcs.run', '--mode', 'globals-only', '--steps', '5'], tmp_path) + + +@slow +def test_segments_full_mode_small(tmp_path): + # n_seg below the default max_reloc (1000) used to crash in relocate_segments + _run(['examples.segments.run', '--data', 'muon.h5', '--n-seg', '500', + '--steps', '30', '--mode', 'full', '--plot-every', '1000'], tmp_path)