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.
This commit is contained in:
2026-05-17 18:58:04 +03:00
parent 745bbae4cd
commit 38b44b56e6
29 changed files with 3538 additions and 2010 deletions
+161
View File
@@ -0,0 +1,161 @@
"""Tests for fitter.extractor."""
import numpy as np
from fitter.extractor import (
CWExtractor,
GVAExtractor,
CWExtractionResult,
GVAExtractionResult,
)
class TestCWExtractor:
"""Test CWExtractor."""
def test_extract(self):
from beta_spectrum import SpectrumConfig
config = SpectrumConfig(
Z_parent=43,
Z_daughter=44,
A_number=99,
endpoint_MeV=0.294,
)
extractor = CWExtractor(config)
energies_keV = np.linspace(0.01, 0.29, 50)
measured = np.linspace(10.0, 0.1, 50)
errors = np.sqrt(measured)
model = np.linspace(9.5, 0.09, 50)
result = extractor.extract(
measured_counts=measured,
measured_errors=errors,
energies_keV=energies_keV,
model_counts=model,
endpoint_keV=294.0,
)
assert isinstance(result, CWExtractionResult)
assert len(result.cw_values) == 50
assert len(result.energies_keV) == 50
assert np.isclose(result.endpoint_keV, 294.0)
assert np.all(np.isfinite(result.cw_values))
def test_extract_with_zero_model(self):
from beta_spectrum import SpectrumConfig
config = SpectrumConfig(
Z_parent=43,
Z_daughter=44,
A_number=99,
endpoint_MeV=0.294,
)
extractor = CWExtractor(config)
energies_keV = np.linspace(0.01, 0.29, 50)
measured = np.ones(50) * 5.0
errors = np.ones(50) * 2.0
model = np.zeros(50) # All zeros
result = extractor.extract(
measured_counts=measured,
measured_errors=errors,
energies_keV=energies_keV,
model_counts=model,
endpoint_keV=294.0,
)
# C(W) should be 1.0 where model is zero (default)
assert np.all(result.cw_values == 1.0)
class TestGVAExtractor:
"""Test GVAExtractor."""
def test_extract_from_curve_basic(self):
energies_W = np.linspace(1.1, 1.57, 100)
endpoint_W = 1.575 # ~294 keV
cw_values = np.ones_like(energies_W) # C(W) = 1 for allowed
result = GVAExtractor.extract_from_curve(
cw_values=cw_values,
energies_W=energies_W,
endpoint_W=endpoint_W,
)
assert isinstance(result, GVAExtractionResult)
assert np.isclose(result.gv_eff, 1.0)
assert result.chi2_per_dof >= 0
def test_extract_from_curve_with_slope(self):
energies_W = np.linspace(1.1, 1.57, 100)
endpoint_W = 1.575
# C(W) with slight slope
cw_values = 1.0 + 0.1 * (energies_W - endpoint_W)
result = GVAExtractor.extract_from_curve(
cw_values=cw_values,
energies_W=energies_W,
endpoint_W=endpoint_W,
)
assert isinstance(result, GVAExtractionResult)
# g_A should be non-zero due to slope
assert abs(result.ga_eff) > 0
def test_extract_from_curve_insufficient_data(self):
energies_W = np.array([1.0, 1.5])
endpoint_W = 1.575
cw_values = np.array([1.0, 1.0])
result = GVAExtractor.extract_from_curve(
cw_values=cw_values,
energies_W=energies_W,
endpoint_W=endpoint_W,
)
assert isinstance(result, GVAExtractionResult)
assert result.chi2_per_dof == 0.0
def test_gva_summary(self):
result = GVAExtractionResult(
gv_eff=1.0,
gv_error=0.01,
ga_eff=0.5,
ga_error=0.02,
correlation=-0.3,
chi2_per_dof=1.2,
)
summary = result.summary()
assert "g_V" in summary
assert "g_A" in summary
assert "1.0" in summary
assert "0.5" in summary
assert "1.2" in summary
class TestCWExtractionResult:
"""Test CWExtractionResult methods."""
def test_kurie_plot(self):
energies_W = np.linspace(1.1, 1.57, 100)
endpoint_W = 1.575
result = CWExtractionResult(
energies_W=energies_W,
energies_keV=energies_W * 510.998950 - 510.998950,
cw_values=np.ones_like(energies_W),
cw_errors=np.zeros_like(energies_W),
flux=np.ones_like(energies_W) * 10.0,
flux_errors=np.ones_like(energies_W) * 3.0,
endpoint_W=endpoint_W,
endpoint_keV=294.0,
)
E_keV, kurie = result.kurie_plot()
assert len(E_keV) > 0
assert len(kurie) > 0
assert np.all(np.isfinite(kurie))
assert np.all(kurie >= 0)
+176
View File
@@ -0,0 +1,176 @@
"""Tests for fitter.fit_engine."""
import numpy as np
from fitter.fit_engine import SpectrumFitter, FitConfig
from fitter.model import SpectrumModel
class TestFitConfig:
"""Test FitConfig defaults."""
def test_defaults(self):
config = FitConfig()
assert config.method == "trf"
assert config.max_nfev == 1000
assert config.loss == "linear"
class TestSpectrumFitter:
"""Test SpectrumFitter."""
def _make_fitter(self):
"""Create a simple fitter with synthetic data."""
# Create a simple linear model
def linear_model(energies_keV, norm, bg):
return norm * (1.0 - energies_keV / 100.0) + bg
# Synthetic data
energies = np.linspace(0.1, 99.9, 200)
counts = 10.0 * (1.0 - energies / 100.0) + 2.0
counts += np.random.RandomState(42).normal(0, 0.5, len(energies))
# Mock model
class MockModel:
def evaluate(self, energies_keV, norm, bg):
return linear_model(energies_keV, norm, bg)
model = MockModel()
fitter = SpectrumFitter(
model, energies, counts, exp_errors=np.ones_like(counts) * 0.5
)
return fitter
def test_fit_basic(self):
fitter = self._make_fitter()
result = fitter.fit(x0=[10.0, 2.0], param_names=["norm", "bg"])
assert result.success
assert result.n_points == 200
assert result.n_free == 2
assert result.chi2 > 0
assert result.chi2_per_dof > 0
assert len(result.parameters) == 2
def test_fit_with_bounds(self):
fitter = self._make_fitter()
result = fitter.fit(
x0=[10.0, 2.0],
bounds=([1.0, 0.0], [20.0, 10.0]),
)
assert result.success
def test_fit_returns_residuals(self):
fitter = self._make_fitter()
result = fitter.fit(x0=[10.0, 2.0])
assert len(result.residuals) == 200
assert len(result.model_values) == 200
def test_parameters_property(self):
fitter = self._make_fitter()
fitter.fit(x0=[10.0, 2.0])
params = fitter.parameters
assert len(params) == 2
def test_covariance_property(self):
fitter = self._make_fitter()
fitter.fit(x0=[10.0, 2.0])
cov = fitter.covariance
assert cov.shape == (2, 2)
def test_chi2_per_dof(self):
fitter = self._make_fitter()
result = fitter.fit(x0=[10.0, 2.0])
assert result.chi2_per_dof == result.chi2 / result.n_free
def test_p_value(self):
fitter = self._make_fitter()
result = fitter.fit(x0=[10.0, 2.0])
assert 0.0 <= result.p_value <= 1.0
def test_parameters_with_errors(self):
fitter = self._make_fitter()
result = fitter.fit(x0=[10.0, 2.0])
params = result.parameters_with_errors
assert len(params) == 2
for name, (val, err) in params.items():
assert isinstance(val, float)
assert isinstance(err, float)
assert err >= 0
def test_correlation_matrix(self):
fitter = self._make_fitter()
result = fitter.fit(x0=[10.0, 2.0])
corr = result.correlation_matrix
assert corr.shape == (2, 2)
# Diagonal should be 1
np.testing.assert_allclose(np.diag(corr), 1.0)
def test_summary(self):
fitter = self._make_fitter()
result = fitter.fit(x0=[10.0, 2.0], param_names=["norm", "bg"])
summary = result.summary(param_names=["norm", "bg"])
assert "norm" in summary
assert "bg" in summary
assert "Fit Results" in summary
def test_profile_likelihood(self):
fitter = self._make_fitter()
result = fitter.fit(x0=[10.0, 2.0])
param_vals, chi2_vals, norm_vals = result.profile_likelihood(0, n_points=10)
assert len(param_vals) == 10
assert len(chi2_vals) == 10
assert len(norm_vals) == 10
assert np.min(norm_vals) >= 0 # Normalized χ² should be >= 0
def test_confidence_interval(self):
fitter = self._make_fitter()
result = fitter.fit(x0=[10.0, 2.0])
ci = result.confidence_interval(0, confidence=0.95)
assert len(ci) == 2
assert ci[0] <= ci[1]
class TestSpectrumFitterWithRealModel:
"""Test SpectrumFitter with a real SpectrumModel."""
def test_fit_with_real_model(self):
from beta_spectrum import BetaSpectrum, SpectrumConfig
config = SpectrumConfig(
Z_parent=43,
Z_daughter=44,
A_number=99,
endpoint_MeV=0.294,
detector_model="gaussian",
detector_sigma_a_keV=0.5,
detector_n_channels=200,
)
spectrum = BetaSpectrum.from_config(config)
detector = BetaSpectrum.create_detector_from_config(config)
model = SpectrumModel(spectrum, detector)
# Generate synthetic data from model
energies_keV = detector.channel_energies
true_norm = 5.0
true_bg = 0.1
counts = model.evaluate(energies_keV, true_norm, true_bg)
counts = np.maximum(counts, 0) # Clip negatives
counts += np.random.RandomState(42).normal(
0, np.sqrt(np.maximum(counts, 1)), len(energies_keV)
)
counts = np.maximum(counts, 0)
fitter = SpectrumFitter(
model,
energies_keV,
counts,
exp_errors=np.sqrt(np.maximum(counts, 1)),
)
result = fitter.fit(x0=[1.0, 0.0], param_names=["norm", "bg"])
assert result.success
# Fit should complete without error
assert len(result.parameters) == 2
+119
View File
@@ -0,0 +1,119 @@
"""Tests for fitter.model."""
import numpy as np
import pytest
from beta_spectrum import BetaSpectrum, SpectrumConfig
from fitter.model import SpectrumModel
class TestSpectrumModel:
"""Test SpectrumModel."""
def _make_model(self, with_detector: bool = False):
"""Create a test SpectrumModel."""
config = SpectrumConfig(
Z_parent=43,
Z_daughter=44,
A_number=99,
endpoint_MeV=0.294,
)
spectrum = BetaSpectrum.from_config(config)
detector = None
if with_detector:
detector = BetaSpectrum.create_detector_from_config(
SpectrumConfig(
Z_parent=43,
Z_daughter=44,
A_number=99,
endpoint_MeV=0.294,
detector_model="gaussian",
detector_sigma_a_keV=1.0,
detector_n_channels=100,
)
)
model = SpectrumModel(spectrum, detector)
return model, config
def test_evaluate_unconvolved(self):
model, config = self._make_model()
energies_keV = np.linspace(0.01, 0.29, 50)
values = model.evaluate_unconvolved(energies_keV)
assert len(values) == 50
assert np.all(np.isfinite(values))
assert np.all(values >= 0)
def test_evaluate_no_detector(self):
model, config = self._make_model()
energies_keV = np.linspace(0.01, 0.29, 50)
values = model.evaluate(energies_keV, normalization=1.0, background=0.0)
assert len(values) == 50
assert np.all(np.isfinite(values))
def test_evaluate_with_normalization(self):
model, config = self._make_model()
energies_keV = np.linspace(0.01, 0.29, 50)
values1 = model.evaluate(energies_keV, normalization=1.0, background=0.0)
values2 = model.evaluate(energies_keV, normalization=2.0, background=0.0)
np.testing.assert_allclose(values2, values1 * 2.0)
def test_evaluate_with_background(self):
model, config = self._make_model()
energies_keV = np.linspace(0.01, 0.29, 50)
values1 = model.evaluate(energies_keV, normalization=1.0, background=0.0)
values2 = model.evaluate(energies_keV, normalization=1.0, background=5.0)
np.testing.assert_allclose(values2, values1 + 5.0)
def test_convolve_requires_detector(self):
model, _ = self._make_model()
energies_keV = np.linspace(0.01, 0.29, 50)
with pytest.raises(RuntimeError):
model.convolve(energies_keV)
def test_convolve_with_detector(self):
model, _ = self._make_model(with_detector=True)
energies_keV = model.detector_response.channel_energies
values = model.convolve(energies_keV)
assert len(values) == model.detector_response.n_channels
assert np.all(np.isfinite(values))
# Convolution can produce small negative values due to numerical effects
# — check that most values are non-negative
assert np.sum(values >= 0) > len(values) * 0.9
def test_default_params(self):
from exp_data.spectrum import ExpSpectrum
energies = np.linspace(0, 100, 200)
counts = 50 * np.exp(-0.5 * ((energies - 50) / 5) ** 2) + 10
exp_spec = ExpSpectrum(energies=energies, counts=counts)
norm, bg = SpectrumModel.default_params(exp_spec)
assert norm > 0
assert bg >= 0
def test_default_bounds(self):
lower, upper = SpectrumModel.default_bounds(100)
assert len(lower) == 2
assert len(upper) == 2
assert lower[0] < upper[0]
assert lower[1] < upper[1]
class TestSpectrumModelKeVToW:
"""Test energy unit conversion in SpectrumModel."""
def test_keV_to_W(self):
model = SpectrumModel(None) # type: ignore
# 0 keV → W = 1.0
W = model._keV_to_W(np.array([0.0]))
assert np.isclose(W[0], 1.0)
# 511 keV → W = 2.0
W = model._keV_to_W(np.array([510.998950]))
assert np.isclose(W[0], 2.0)
# 294 keV → W ≈ 1.575
W = model._keV_to_W(np.array([294.0]))
assert np.isclose(W[0], 294.0 / 510.998950 + 1.0)
+100
View File
@@ -0,0 +1,100 @@
"""Tests for fitter.result."""
import numpy as np
from fitter.result import AnalysisResult, FitSummary
class MockFitResult:
"""Mock FitResult for testing AnalysisResult."""
def __init__(self):
self.success = True
self.chi2 = 12.5
self.n_points = 100
self.n_free = 3
self.parameters = np.array([5.0, 0.1, 2.0])
self.covariance = np.array(
[
[0.01, 0.0, 0.0],
[0.0, 0.001, 0.0],
[0.0, 0.0, 0.04],
]
)
self.model_values = np.ones(100)
self.residuals = np.zeros(100)
self.message = "Optimization terminated successfully."
@property
def chi2_per_dof(self):
return self.chi2 / (self.n_points - self.n_free)
@property
def p_value(self):
from scipy.stats import chi2
return 1.0 - chi2.cdf(self.chi2, self.n_points - self.n_free)
@property
def parameters_with_errors(self):
errors = np.sqrt(np.diag(self.covariance))
return {
f"p{i}": (float(self.parameters[i]), float(errors[i]))
for i in range(len(self.parameters))
}
class TestFitSummary:
"""Test FitSummary."""
def test_str(self):
summary = FitSummary(
nuclide="Tc99",
converged=True,
chi2_per_dof=1.234,
p_value=0.0567,
parameters={"norm": (5.0, 0.1), "bg": (0.1, 0.01)},
)
text = str(summary)
assert "Tc99" in text
assert "1.234" in text
assert "5.0" in text
assert "Converged: True" in text
class TestAnalysisResult:
"""Test AnalysisResult."""
def test_summary(self):
mock = MockFitResult()
result = AnalysisResult(
fit_result=mock,
nuclide="Tc99",
metadata={"param_names": ["norm", "bg", "endpoint"]},
)
summary = result.summary
assert summary.nuclide == "Tc99"
assert summary.converged is True
assert summary.chi2_per_dof > 0
def test_to_dict(self):
mock = MockFitResult()
result = AnalysisResult(
fit_result=mock,
nuclide="Tc99",
gv_eff=0.97,
ga_eff=0.57,
endpoint_keV=294.0,
)
d = result.to_dict()
assert d["nuclide"] == "Tc99"
assert d["gv_eff"] == 0.97
assert d["ga_eff"] == 0.57
assert d["endpoint_keV"] == 294.0
assert d["converged"] is True
def test_empty_result(self):
mock = MockFitResult()
result = AnalysisResult(fit_result=mock)
summary = result.summary
assert summary.nuclide == ""