Commit Graph
58 Commits
Author SHA1 Message Date
unzhakov 3590ca91a1 fix(nuclear_data): use measured transition endpoints per branch
paceENSDF stores the measured beta endpoint energy of each transition
(ENSDF column 7). The parser instead derived branch endpoints as
base-endpoint minus level energy with the base taken from an arbitrary
first-listed branch, so Co60 produced negative branch endpoints and a
hard ValueError (bs_pnpi Co60 exited 1 regardless of cutoff).

- BranchInfo carries the measured endpoint_MeV
- overall endpoint = max measured endpoint over all branches
- decay_info_to_config prefers measured endpoints; the subtraction is
  retained only as a legacy fallback for hand-built DecayInfo objects
- Co60/Tc99/Cs137 endpoint tests + CLI dry-run/export tests (D3)
2026-10-02 08:42:51 +03:00
unzhakov 9c3dd80b5c refactor(cli): delegate paceENSDF config building to library
Remove the duplicated inline paceENSDF config builder in the CLI.
It renormalized branch intensities before filtering, diverging from
the library decay_info_to_config path that library callers use
(audit finding D5). CLI paceENSDF configs now come from
create_config_from_source exactly once per run.

Regression test spies on create_config_from_source during a CLI run.
2026-10-02 07:13:14 +03:00
unzhakov 18a46ad02f feat(cli): propagate export options through JSON/paceENSDF flows
- main(argv) signature enables in-process CLI invocation and testing
- parser defaults for --e-step/--neutrino-mass/--intensity-cutoff/
  --csv-separator/--normalize-to-one now None = 'not provided'
- JSON flow applies file values by default and CLI flags as overrides
  (previously these five options were silently discarded)
- paceENSDF flow resolves None flags to literal defaults
- new tests/integration/test_cli_flows.py: JSON propagation,
  degenerate-mode non-zero exit with no file (JSON + paceENSDF)
- adapted two neutrino-mass default tests to None-parsing semantics
2026-10-02 05:46:08 +03:00
unzhakov 62bf7fdac2 fix(output): apply positive-integral export guard to to_one mode
CSVEmitter.export_to_csv raised ValueError only in intensity mode;
degenerate exports with --normalize-to-one silently wrote all-zero
CSV files. The guard now runs before the mode split and no file is
written in either mode.
2026-10-01 23:02:33 +03:00
unzhakov ee7aedc80a fix(spectrum): lone branch defines endpoint in single-branch mode
When config.branches carries exactly one branch (e.g. after
--intensity-cutoff filtering), the branch endpoint/transition define
the spectrum, energy grid, analyzer unified branch view and CSV
header. The stale top-level endpoint inherited from the parent decay
no longer leaks into physics (proven wrong on Cs137: spectrum
extended to 1176 keV while the lone survivor ends at 514 keV).
2026-10-01 22:04:17 +03:00
unzhakov 6bb7b950c7 style: apply black formatting to pending files 2026-09-30 10:41:28 +03:00
unzhakov 7dc2ec79d1 feat(cli): report core in dry-run, build plots from exported CSV 2026-09-30 03:04:18 +03:00
unzhakov afb7afc5b7 feat(output): physical branch spectra, universal factor, CSV-driven plotting 2026-09-30 03:04:18 +03:00
unzhakov bab19de458 feat: make phase space and Fermi function unconditional core components 2026-09-30 03:04:18 +03:00
unzhakov 9bf1e1333e refactor: rename visualize module to output module and separate concerns into core, csv_export, and visualization modules 2026-07-07 12:59:11 +03:00
unzhakov 6dc1e3924d feat: add CLI options for custom CSV separator and normalize-to-one branch normalization 2026-07-06 17:32:56 +03:00
unzhakov 1b4d418b5f feat: change CSV output format to use tab delimiters instead of comma delimiters 2026-07-03 18:01:39 +03:00
unzhakov 643e035c54 feat: update CSV headers and plot titles to show active/excluded branches and intensity cutoff exclusions 2026-07-03 17:45:35 +03:00
unzhakov c6aaf3b76a fix: use underscores in branch names for CSV headers in concise mode 2026-07-03 15:21:44 +03:00
unzhakov c2795bf86e fix: use underscores in branch names for CSV headers 2026-07-03 15:10:10 +03:00
unzhakov a7eef7bc20 feat: polish CSV header format with improved metadata and column naming 2026-07-03 14:58:19 +03:00
unzhakov 876e1e3ab8 Add massive neutrino support and improve CSV/CLI output
- Add neutrino mass parameter to SpectrumConfig and CLI interface
- Update PhaseSpace component to handle neutrino mass effects properly
- Update CSV headers to show basic endpoint and all transition types
- Add --csv-verbosity option to CLI with 'full' and 'concise' options
- Fix comparison plots to properly show linear scale variations
- Add comprehensive tests for neutrino mass functionality
2026-07-02 10:33:28 +03:00
unzhakov 8b0ced4b65 fix: resolve 4 fatal bugs — json_to_config, create_config_from_source, Am-241 constant, CLI positional args 2026-05-26 14:57:35 +03:00
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