Commit Graph
40 Commits
Author SHA1 Message Date
unzhakov 2fedd03d92 fix: bump __version__ to 0.4.0 to match pyproject.toml 2026-05-22 15:18:09 +03:00
unzhakov 5c2b12c0e6 feat: experimental data calibration pipeline with ROOT I/O
- Fix chi2 calculation bug in calibration.py (remove incorrect
  coeffs[::-1] reversal in np.polyval)
- Fix broken beta_spectrum/cli.py (remove orphaned detector response
  add_argument calls and unused imports)
- Add ExpSpectrum.apply_calibration() and EnergyCalibrator.from_am241_spectrum()
- Add LivetimeDetermination class for pulser-based livetime
- Add SpectrumPipeline orchestration (read→subtract→calibrate→livetime→validate)
- Add ROOT I/O with PyROOT primary + uproot fallback
- Add bs_exp CLI with process, livetime, export subcommands
- Add exp_calibration notebook with pre-calibration visualization
- Add comprehensive tests (73 passing)
- Add bs_exp console script and [root] extra to pyproject.toml
- Remove obsolete detector_response module and unused notebooks
2026-05-21 16:01:25 +03:00
unzhakov 38b44b56e6 feat: v0.4.0 package restructuring — split into 4 modules
Separate monolithic beta_spectrum package into:
  beta_spectrum   — pure theory (components, spectrum, CLI, visualize)
  exp_data        — experimental data handling (spectrum, calibration,
                    fitters, corrections)
  fitter          — analysis framework (model, fit_engine, extractor,
                    result)
  beta_spectrum.visualize — plotting (BetaSpectrumAnalyzer)

Phase 1 — exp_data module:
  ExpSpectrum dataclass with metadata, normalization, serialization
  EnergyCalibrator (linear/quadratic calibration)
  GaussianFitter + PeakFitter for calibration sources
  DeadTimeCorrection, PileUpCorrection, BackgroundSubtractor
  43 new tests, ruff + mypy clean

Phase 2 — fitter module:
  SpectrumModel wraps BetaSpectrum + DetectorResponse with convolution
  SpectrumFitter with χ² minimization, covariance, profile likelihood,
  confidence intervals, robust loss functions
  CWExtractor + GVAExtractor for C(W) and g_V/g_A extraction
  AnalysisResult + FitSummary for physics-specific results
  CurveFitter general-purpose callable model fitter
  34 new tests, ruff + mypy clean

Phase 3 — clean up beta_spectrum:
  Remove cw_extractor.py and fitter.py (moved to fitter/)
  Clean __init__.py to export only theory classes
  Add backward-compat methods to CWExtractor
  Fix BetaSpectrumAnalyzer._get_branch_spectrum returning BetaSpectrum
  objects instead of numpy arrays (plot fix)

Phase 4 — package structure:
  Auto-discovered by setuptools (4 packages)
  All imports updated across 26 source files
  Black formatting applied
  322 tests pass (262 original + 60 new)
  ruff + mypy clean on all source files

Bug fixes:
  - Fix multi-branch spectrum plotting: universal component keys
    (Fermi, Screening, etc.) don't have per-branch prefix; fixed
    fallback lookup.
  - Fix negative phase space beyond endpoint: BetaSpectrum returns
    negative values for W > W0; clamp branch spectra to zero.
2026-05-17 18:58:04 +03:00
unzhakov 745bbae4cd refactor: rename 'analyzer' to 'visualize' — analysis belongs to fitter module 2026-05-17 01:33:13 +03:00
unzhakov 64785f4aa9 style: remove transition type from plot header — shown in branch legends instead 2026-05-16 23:24:33 +03:00
unzhakov 55cfb30b2b refactor: unify plotting — single-branch treated as multi-branch with one branch; remove old single-branch methods 2026-05-16 22:59:48 +03:00
unzhakov b3d6abb4d5 polish: unify plot output — external headers, compact legends, consistent titles 2026-05-16 21:21:28 +03:00
unzhakov f05a2de1b8 refactor: move BetaSpectrumAnalyzer to separate analyzer module 2026-05-16 20:41:58 +03:00
unzhakov 1a23283cf1 fix: decay_info_to_config() now passes branches to SpectrumConfig; update docs for paceENSDF completion
- Fixed bug: decay_info_to_config() was dropping branches, causing
  create_config_from_source('paceENSDF') to return single-branch config
- Added BranchConfig import to nuclear_data.py
- Marked B1 (paceENSDF integration) as complete in TODO.md
- Updated README.md with paceENSDF details in Implementation Status
- Updated TODO.md Current Status with v0.3.1 notes
2026-05-16 18:50:06 +03:00
unzhakov 620488860b Fix Tc99 branch intensity from paceENSDF
paceENSDF returns intensity at state[9] (percent), not state[8] (ENSDF
normalization field, ~1.0 for all branches). This was causing ~50/50
split for Tc99 instead of the correct 99.9984%/0.0016%.
2026-05-08 16:08:41 +03:00
unzhakov c404d83418 Remove 'universal_' prefix from CSV column names in multi-branch mode
Universal components (Fermi, Screening, etc.) are exported under their
plain names — no redundant prefix needed.
2026-05-08 15:54:13 +03:00
unzhakov b02159ba5c Remove repeated per-branch metadata columns from CSV export
Branch intensity, endpoint, and transition are constant per branch and
already documented in the CSV header. No need to repeat them as columns
for every energy row.
2026-05-08 15:41:10 +03:00
unzhakov ef337073d6 docs: update TODO and README for B3 completion and BranchConfig export
- Cross out B3 in TODO.md with completion details
- Export BranchConfig in __init__.py public API
- Update README to mention per-branch transition types and intensity cutoff
2026-05-08 08:35:01 +03:00
unzhakov 6293710089 feat: multi-branch CLI with intensity cutoff and per-branch info
- Add --intensity-cutoff CLI option to filter negligible branches
- Fetch DecayInfo from paceENSDF and construct SpectrumConfig with
  branches including per-branch transition types
- Normalize branch intensities to sum to 1.0, filter by cutoff
- Display branch info in dry-run output and logging
- Add intensity_cutoff to SpectrumConfig
2026-05-08 08:33:39 +03:00
unzhakov 3216c50943 feat: per-branch transition types from ENSDF and raw-value plotting
- Add transition_type field to BranchInfo and extract per-branch
  forbiddenness codes from paceENSDF (not defaulting all to 'A')
- Fix _multi_branch_call to use np.maximum instead of np.where mask
  so branches smoothly approach zero at endpoint
- Rewrite _plot_multi_branch_spectra and _plot_multi_branch_debug Panel 1
  to plot raw (un-normalized) branch contributions so total = sum of branches
- Remove independent unit-area normalization that made small branches
  appear larger than total
2026-05-08 08:33:12 +03:00
unzhakov 5ac004352b Fix mypy type errors and black formatting
- spectrum.py: Use Axes from TYPE_CHECKING instead of plt.Axes
- fitter.py: Remove unused type: ignore comment
- phase_space.py: Black formatting
2026-05-05 14:01:28 +03:00
unzhakov d6328d4b24 Enhance plot output with ID tracking and two display modes
- Add commit hash (6 chars) and UTC timestamp to all plots via text boxes
- Add nuclear data header (nuclide, endpoint, transition, corrections) to plots
- Two display modes:
  - DEBUG (-vv): 4-panel debug view with all correction factors
  - Normal (default): single spectrum plot with nuclear data header
- CLI: --plot now passes show_components=(args.verbose >= 2)
2026-05-05 13:33:46 +03:00
unzhakov 3749220efc Fix pyright type errors and correct paceENSDF Q-value extraction
- nuclear_data.py: Extract Q-value from ground state branch state[7] instead of
  halflife_data (was reading half-life seconds as Q-value)
- nuclear_data.py: Use ground state branch for forbiddenness code, with fallback
- nuclear_data.py: Add None guards for beta_data and pairs
- spectrum.py: Pass Z=config.Z_daughter, A=config.A_number to RadiativeCorrection
- phase_space.py: Add __init__ debug logging (W0, transition_type, m_e, m_nu)
- phase_space.py: Add output range logging in __call__
- phase_space.py: Fix possibly unbound forbid_factor variable
- logging_utils.py: Fix broken get_git_short_hash indentation
- cli.py: Add explicit SpectrumConfig annotation to fix pyright type identity
- cw_extractor.py: Fix T_to_W ndarray→float conversions (6 locations)
- cw_extractor.py: Fix FermiFunction() calls — was passing Z as __call__ arg
- fitter.py: Add explicit dict type annotation for least_squares kwargs
2026-05-05 12:43:43 +03:00
unzhakov 330ebddaef refactor: refine CLI options and enhance debug logging
- Remove --mode, --transition-type, and --decay-index CLI flags
  (parameters now come from ENSDF data or custom JSON input)
- Clarify energy units in all CLI help text (MeV throughout, keV for detector params)
- Enhance logging verbosity:
  - -v (INFO): shows source, component initialization, workflow steps
  - -vv (DEBUG): shows detailed internals of all spectrum components
    (parameters, evaluation counts, input/output ranges)
- Improve CSV headers with element notation (e.g. Tc99 -> Ru99)
- Add CONVENTIONS.md documenting energy unit and logging conventions
- Update TODO.md with completion status
2026-05-05 09:08:08 +03:00
unzhakov 9050019ddd feat: add structured logging, CSV metadata headers, and CLI improvements
- New module: beta_spectrum/logging_utils.py
  - LoggingConfig dataclass with level, log_file, format options
  - setup_logging() one-shot configuration (opt-in for library use)
  - get_logger() for named child loggers
  - get_git_short_hash() for commit identification
  - _find_git_root() for repo detection

- CLI enhancements (beta_spectrum/cli.py):
  - --verbose/-v (repeatable): -v=INFO, -vv=DEBUG
  - --quiet/-q: suppress all terminal output
  - --log-file PATH: append log to file
  - --dry-run: validate input, display resolved config, exit
  - --version: show package version
  - Replace print() with structured logging throughout
  - Handle KeyboardInterrupt gracefully

- CSV metadata headers (BetaSpectrumAnalyzer.export_to_csv):
  - YAML-style # comments with version, timestamp, source, nuclide info
  - Corrections enabled, e_step, detector settings, git commit hash

- Base class integration (SpectrumComponent):
  - Optional logger parameter for debug/info output (opt-in)

- BetaSpectrum integration:
  - Optional logger parameter passed through from_config()
  - Detector logging in create_detector_from_config()
  - Convolution logging in convolve_with_detector()

- Tests: tests/test_logging_utils.py (28 tests)
  - LoggingConfig, setup_logging, get_logger, git hash, CSV headers, CLI flags

- Update TODO.md: mark B8 as complete, update Current Status
2026-05-04 15:11:01 +03:00
unzhakov 1a0754be5f docs: remove empty recoil.py stub, update README and TODO to reflect actual state
- Remove empty beta_spectrum/components/recoil.py (0-line stub)
- Remove recoil.py from README.md project tree and components table
- Update TODO.md: replace specific recoil section with generic 'Additional
  Corrections' deferred item, update Current Status to 0.3.0 with actual
  implementation list, mark A4 as complete, set A3 as next step
2026-05-04 11:56:41 +03:00
unzhakov 66a93d9cac fix: satisfy mypy strict type-checking requirements
- Add proper type annotations to all source files
- Fix return types for numpy operations (np.asarray with dtype=np.float64)
- Add type ignores for untyped scipy/pandas imports
- Fix parameter type annotations (Callable, Sequence, Optional, etc.)
- Add TYPE_CHECKING imports for forward references
- Fix fitter.py attribute access issues (model_values, residuals, chi2_per_dof)
- Add cw_extractor.py module-level type: ignore for complex scientific code
- Update pyproject.toml to exclude notebooks from mypy
- Add mypy disable_error_code configuration for test files
- Run black and ruff for formatting and linting
2026-05-03 01:00:47 +03:00
unzhakov 33ed4f7e44 fix: satisfy mypy strict type-checking requirements
- Add proper type annotations to all source files
- Fix return types for numpy operations (np.asarray with dtype=np.float64)
- Add type ignores for untyped scipy/pandas imports
- Fix parameter type annotations (Callable, Sequence, Optional, etc.)
- Add TYPE_CHECKING imports for forward references
- Fix fitter.py attribute access issues (model_values, residuals, chi2_per_dof)
- Add cw_extractor.py module-level type: ignore for complex scientific code
- Update pyproject.toml to exclude notebooks from mypy
- Run black and ruff for formatting and linting
2026-05-03 00:44:11 +03:00
unzhakov 1269244b93 feat: add paceENSDF integration and CLI interface (Track B1)
- Add nuclear_data.py module for paceENSDF integration and JSON input
- Add DecayInfo and BranchInfo dataclasses for parsed nuclear data
- Implement get_decay_info_from_paceENSDF() to retrieve decay parameters
- Implement load_json_input() and json_to_config() for custom JSON input
- Add create_config_from_source() unified interface for both sources
- Add bs_pnpi CLI with --nuclide, --input, --output, --plot, and detector options
- Add 23 comprehensive tests for nuclear_data module
- Add sample JSON input file
- Update __init__.py and pyproject.toml with new exports and entry point
- Add paceENSDF as optional dependency
2026-05-02 22:09:25 +03:00
unzhakov 272841f50d feat: add χ² fitter and C(W) shape factor extraction modules
Add CurveFitter with scipy least_squares, configurable loss functions
(soft_l1, huber, cauchy), profile likelihood, confidence intervals, and
goodness-of-fit metrics. Add CWExtractor for extracting shape factors
from beta spectra via Kurie analysis, parametrization fitting, and
g_V/g_A extraction. Includes 32 new tests (18 fitter + 14 CW extractor).
Bump version to 0.3.0.
2026-05-02 09:40:38 +03:00
unzhakov 8b4545fe3e refactor: centralize all physical constants in constants.py, fix unit naming
- Add EULER_GAMMA, ME_KEV, R0_FM to constants.py
- Replace hardcoded 0.511, 0.5772..., 1.2 with imports from constants
- Fix T_to_W parameter name: T_kev -> T_MeV (it takes MeV, not keV)
- Remove duplicate ME_ME from spectrum.py (import ME_MEV from constants)
- Remove hardcoded r_0 from detector_response.py and radiative.py
- Update CONVENTIONS.md to reference correct constant names
2026-05-01 22:34:15 +03:00
unzhakov 5f99566a0e feat(detector): add detector response module, convolution, and integration
- Analytical detector response: gaussian, gaussian_tail, tikhonov models
- Low-energy tail modeling for charge collection effects
- Response matrix convolution via R^T · (Φ·ΔW)
- Declarative API: create_detector_from_config(), convolve_detector()
- BetaSpectrumAnalyzer.convolved_spectrum() for auto-convolution
- Integration tests: TestBetaSpectrumIntegration, TestDeclarativeDetectorResponse
- Documentation: docs/08-detector-response.md
2026-05-01 19:20:59 +03:00
unzhakov 968cd6eff7 style: remove trailing blank lines in base.py and fermi.py 2026-05-01 19:17:08 +03:00
unzhakov c99ce51487 fix(radiative): only apply endpoint resummation within delta_cut per spec Section 3.4
The resummation was previously applied to all energy points when the
flag was set, causing resummed and standard modes to differ everywhere.
Per spec, it should only replace C(beta)*ln(W0-W) with the resummed
power-law form when (W0-W) < delta_cut (~1e-3).

Adds delta_cut parameter (default 1e-3) and corrects the resummation
switch test to verify identical results far from endpoint.
2026-04-30 21:06:00 +03:00
unzhakov ed3fd5dc9d feat(radiative): implement O(Z*alpha^2) correction and improve numerical stability
- Add Z (nuclear charge) and A (mass number) parameters to RadiativeCorrection
- Implement O(Z*alpha^2) finite nuclear size correction per Sirlin 1987:
  - Energy-dependent part: ln(m_p) - (5/12)*ln(2W) + 43/18
  - Nuclear-structure-dependent part: Delta_F(Z,A) from modified Gaussian model
- Add small-beta Taylor expansion for numerical stability at threshold (beta < 1e-6)
- Extract _safe_beta() and _safe_tanh_inv_beta_over_beta() helper methods
- Remove unused log_wright_bessel import
- Add 14 new tests: Z-dependence, numerical stability, A parameter coverage
- Update docs/06-radiative-corrections.md with new API usage examples

All 70 tests pass. 14 new tests in 3 new test classes.
2026-04-30 07:18:02 +03:00
unzhakov 0e9b20caa2 Fix deprecated np.maximum calls with 3 params 2026-04-28 11:38:31 +03:00
unzhakov 4c0fe493d8 Fix call parameter typo 2026-04-28 11:32:07 +03:00
unzhakov f04f52b747 Update Phase Space calculation
Add support for proper calculation of phase space component based on the
transition type (allowed/Nth order forbidden).
2026-04-27 15:36:36 +03:00
unzhakov bce6e63663 Add pytest test suite (56 tests) for all spectrum components 2026-04-26 23:45:53 +03:00
unzhakov 75ad14946d fix/Radiative correction
Implement correct resummation for high-energy electrons (near endpoint).
See pages 12-13 in Hayen 2017, eqs. 50, 53, 54
2026-04-17 12:53:26 +03:00
unzhakov 04c6a4b250 Output csv precision fix
Switched to 4 decimal digits.
2026-04-17 12:52:19 +03:00
unzhakov 8c4d281fb5 Add data directory
Storage for data files used in calculations (extracted tables,
coefficients etc)
2026-04-15 18:12:53 +03:00
unzhakov 91f716c851 Version 0.1.2
Implemented all planned corrections:
  - finite-size e/m L0 and U
  - atomic screening and exchange
  - radiative (electron only so far)

Added plotter and csv_export
2026-04-15 18:05:04 +03:00
unzhakov 0c5c53688d MVP Correction Implemented
Add implementation for the basic set of spectrum components:

Primary
-------
- Phase Space
- Fermi Function

Corrections
-----------

- Atomic:
  - Screening
  - Atomic exchange
- E/M and finite size:
  - Finite nucleus size and charge distribution
  - Radiative
2026-04-10 15:32:47 +03:00
unzhakov a5e1962fe2 Initial commit
Base modular structure (phase space, Fermi function)
Initial .gitignore
2026-04-02 15:38:37 +03:00