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
+38
View File
@@ -0,0 +1,38 @@
"""
Fitter module — main analysis framework for beta spectrometry.
Provides the analysis workhorse: theoretical model + detector convolution,
multi-parameter fitting, and physics parameter extraction (C(W), g_V, g_A).
Usage:
from fitter import SpectrumModel, SpectrumFitter, AnalysisResult
# Build theoretical model with detector response
model = SpectrumModel(spectrum, detector_response, channel_energies)
# Fit model to experimental data
fitter = SpectrumFitter(model, exp_spectrum)
result = fitter.fit(
x0=[endpoint_keV, normalization, background],
bounds=[(...), (...), (...)],
)
# Extract physics parameters
print(result.summary())
"""
from .model import SpectrumModel
from .fit_engine import SpectrumFitter, CurveFitter, FitConfig
from .result import AnalysisResult, FitSummary
from .extractor import CWExtractor, GVAExtractor
__all__ = [
"SpectrumModel",
"SpectrumFitter",
"CurveFitter",
"FitConfig",
"AnalysisResult",
"FitSummary",
"CWExtractor",
"GVAExtractor",
]
+373
View File
@@ -0,0 +1,373 @@
"""
C(W) shape factor and g_V/g_A extraction from fitted spectra.
Provides methods to:
- Extract C(W) from fitted spectrum vs measured spectrum
- Perform Kurie plot analysis for endpoint determination
- Fit C(W) parametrization to extract g_V, g_A
The beta decay spectrum is:
dΓ/dE = C₀ · p·E·(W₀-E)² · F(Z,E) · C(W) · [1 + δ(E)]
For allowed transitions with C(W) = 1, the Kurie plot
K(E) = sqrt(dΓ/dE / (p·E·F(Z,E)·[1+δ(E)]))
is linear in E with slope -(W₀-E₀)/E₀.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Optional, Tuple
import numpy as np
if TYPE_CHECKING:
from beta_spectrum.spectrum import SpectrumConfig
from beta_spectrum.utils import T_to_W, momentum
@dataclass
class CWExtractionResult:
"""Container for C(W) extraction results."""
energies_W: np.ndarray
"""Total energy grid in m_e units."""
energies_keV: np.ndarray
"""Kinetic energy grid in keV."""
cw_values: np.ndarray
"""Extracted C(W) values."""
cw_errors: np.ndarray
"""Uncertainties on C(W) values."""
flux: np.ndarray
"""Measured flux (counts per energy bin)."""
flux_errors: np.ndarray
"""Uncertainties on flux."""
endpoint_W: float
"""Endpoint energy W₀ in m_e units."""
endpoint_keV: float
"""Endpoint kinetic energy in keV."""
fit_result: Optional[Any] = None # FitResult from SpectrumFitter
def kurie_plot(self) -> Tuple[np.ndarray, np.ndarray]:
"""Compute Kurie plot values.
Returns
-------
(energies_keV, kurie_values)
"""
p = momentum(self.energies_W)
E = self.energies_W
# C(W) = (dΓ/dE) / (C₀ · p·E·(W₀-E)² · F · corrections)
# For Kurie plot: K(E) = sqrt(C(W) / (p·E·(W₀-E)²))
# Simplified: K(E) = sqrt(counts / (p·E·(W₀-E)²))
phase_space = p * E * (self.endpoint_W - E) ** 2
mask = phase_space > 0
kurie = np.zeros_like(self.energies_keV)
kurie[mask] = np.sqrt(
self.flux[mask] / (phase_space[mask] * self.energies_keV[mask] ** 2)
)
return self.energies_keV[mask], kurie[mask]
@dataclass
class GVAExtractionResult:
"""Container for g_V and g_A extraction results."""
gv_eff: float
"""Effective vector coupling constant."""
gv_error: float
"""1σ uncertainty on g_V."""
ga_eff: float
"""Effective axial coupling constant."""
ga_error: float
"""1σ uncertainty on g_A."""
correlation: float
"""Correlation coefficient between g_V and g_A."""
chi2_per_dof: float
"""Reduced χ²."""
def summary(self) -> str:
lines = [
"=" * 60,
"g_V / g_A Extraction",
"=" * 60,
f"g_V^eff = {self.gv_eff:.6f} ± {self.gv_error:.6f}",
f"g_A^eff = {self.ga_eff:.6f} ± {self.ga_error:.6f}",
f"Correlation(g_V, g_A) = {self.correlation:.3f}",
f"χ²/ndof = {self.chi2_per_dof:.3f}",
"=" * 60,
]
return "\n".join(lines)
class CWExtractor:
"""Extract C(W) shape factor from fitted spectrum.
Parameters
----------
config : SpectrumConfig
Configuration used for the theoretical model.
"""
def __init__(self, config: "SpectrumConfig"):
self.config = config
def extract(
self,
measured_counts: np.ndarray,
measured_errors: np.ndarray,
energies_keV: np.ndarray,
model_counts: np.ndarray,
endpoint_keV: float,
) -> CWExtractionResult:
"""Extract C(W) from measured spectrum and model prediction.
Parameters
----------
measured_counts : np.ndarray
Measured counts per channel.
measured_errors : np.ndarray
Measurement uncertainties.
energies_keV : np.ndarray
Energy grid in keV.
model_counts : np.ndarray
Theoretical model counts (from fit).
endpoint_keV : float
Endpoint energy in keV.
Returns
-------
CWExtractionResult
"""
W = T_to_W(energies_keV)
W0 = T_to_W(endpoint_keV)
# C(W) ∝ measured / model (ratio gives shape factor)
# For allowed transitions, model includes phase space + Fermi + corrections
cw_values = np.where(model_counts > 0, measured_counts / model_counts, 1.0)
cw_errors = np.where(
model_counts > 0,
measured_errors / model_counts,
0.0,
)
# Clip C(W) to reasonable range
cw_values = np.clip(cw_values, 0.01, 10.0)
# Ensure errors are positive
cw_errors = np.maximum(cw_errors, 1e-10)
return CWExtractionResult(
energies_W=W,
energies_keV=energies_keV,
cw_values=cw_values,
cw_errors=cw_errors,
flux=measured_counts,
flux_errors=measured_errors,
endpoint_W=W0,
endpoint_keV=endpoint_keV,
)
def fit_parametrization(
self,
cw_result: "CWExtractionResult",
parametrization: str = "constant",
) -> np.ndarray:
"""Fit C(W) parametrization to extracted values.
Parameters
----------
cw_result : CWExtractionResult
Extracted C(W) values.
parametrization : str
Parametrization type: 'constant', 'linear', 'quadratic'.
Returns
-------
np.ndarray
Fitted parameters [a0, a1, ...].
Raises
------
ValueError
If parametrization is not recognized.
"""
valid = cw_result.energies_W > 0
W = cw_result.energies_W[valid] - 1.0
cw = cw_result.cw_values[valid]
if len(W) < 3:
raise ValueError("Not enough points for fit")
if parametrization == "constant":
coeffs, cov = np.polyfit(W, cw, 0, cov=True)
return np.array([float(coeffs)])
elif parametrization == "linear":
coeffs, cov = np.polyfit(W, cw, 1, cov=True)
return coeffs
elif parametrization == "quadratic":
coeffs, cov = np.polyfit(W, cw, 2, cov=True)
return coeffs
else:
raise ValueError(f"Unknown parametrization: {parametrization}")
def fit_gV_gA(
self,
cw_result: "CWExtractionResult",
M_F: float = 1.0,
M_GT: float = 0.0,
) -> "GVAExtractionResult":
"""Extract effective g_V and g_A from C(W) values.
Parameters
----------
cw_result : CWExtractionResult
Extracted C(W) values.
M_F : float
Fermi matrix element.
M_GT : float
Gamow-Teller matrix element.
Returns
-------
GVAExtractionResult
"""
return GVAExtractor.extract_from_curve(
cw_values=cw_result.cw_values,
energies_W=cw_result.energies_W,
endpoint_W=cw_result.endpoint_W,
)
def kurie_analysis(
self,
endpoint_keV: float,
) -> Tuple["CWExtractionResult", Optional[Any]]:
"""Perform Kurie plot analysis to extract C(W).
Placeholder method: in a full implementation, this would
use the fitted model to compute C(W) from experimental data.
Returns
-------
(CWExtractionResult, fit_result)
Extracted C(W) and optional fit result.
"""
# For now, return a dummy result — the real implementation
# would use the fitted spectrum model
energies_keV = np.linspace(5, endpoint_keV * 0.98, 50)
W = T_to_W(energies_keV / 1000.0)
cw_values = np.ones_like(W)
cw_errors = np.ones_like(W) * 0.05
flux = np.ones_like(W) * 10.0
flux_errors = np.ones_like(W) * 3.0
W0 = T_to_W(endpoint_keV / 1000.0)
result = CWExtractionResult(
energies_W=W,
energies_keV=energies_keV,
cw_values=cw_values,
cw_errors=cw_errors,
flux=flux,
flux_errors=flux_errors,
endpoint_W=W0,
endpoint_keV=endpoint_keV,
)
return result, None
class GVAExtractor:
"""Extract effective g_V and g_A from C(W) shape factor.
For allowed transitions:
C(W) ≈ 1 + (g_A/g_V)² · (corrections)
The ratio g_A^eff/g_V^eff can be extracted from the shape of C(W).
"""
@staticmethod
def extract_from_curve(
cw_values: np.ndarray,
energies_W: np.ndarray,
endpoint_W: float,
transition_type: str = "F",
) -> GVAExtractionResult:
"""Extract g_V and g_A from C(W) values.
Parameters
----------
cw_values : np.ndarray
Extracted C(W) values.
energies_W : np.ndarray
Total energy grid.
endpoint_W : float
Endpoint energy W₀.
transition_type : str
Transition type (F, GT, etc.).
Returns
-------
GVAExtractionResult
"""
# For allowed transitions, C(W) ≈ 1 + b·(W - W₀) where b depends on g_A/g_V
# Simple linear fit of C(W) vs energy near endpoint
mask = (energies_W > 0) & (energies_W < endpoint_W) & (cw_values > 0)
if np.sum(mask) < 3:
return GVAExtractionResult(
gv_eff=1.0,
gv_error=0.0,
ga_eff=0.0,
ga_error=0.0,
correlation=0.0,
chi2_per_dof=0.0,
)
# Fit C(W) = a + b·(W - W₀)
x = energies_W[mask] - endpoint_W
y = cw_values[mask]
# Linear fit
coeffs, cov = np.polyfit(x, y, 1, cov=True)
a, b = coeffs
# For allowed transitions: g_V ≈ 1 (CVC), g_A extracted from slope
gv_eff = 1.0
gv_error = 0.0
ga_eff = b * endpoint_W # Simplified relation
ga_error = np.sqrt(cov[1, 1]) * endpoint_W
correlation = (
cov[0, 1] / (np.sqrt(cov[0, 0]) * np.sqrt(cov[1, 1]))
if cov[0, 0] * cov[1, 1] > 0
else 0.0
)
# χ² estimate
y_fit = a + b * x
chi2 = float(np.sum(((y - y_fit) / np.maximum(np.abs(y) * 0.01, 1e-10)) ** 2))
ndof = max(len(x) - 2, 1)
return GVAExtractionResult(
gv_eff=gv_eff,
gv_error=gv_error,
ga_eff=ga_eff,
ga_error=ga_error,
correlation=float(correlation),
chi2_per_dof=chi2 / ndof if ndof > 0 else chi2,
)
+541
View File
@@ -0,0 +1,541 @@
"""
Multi-parameter fitting engine for beta spectrum analysis.
Orchestrates the fitting of theoretical models to experimental data,
including parameter optimization, covariance estimation, and goodness-of-fit.
Usage:
fitter = SpectrumFitter(model, exp_spectrum, param_names)
result = fitter.fit(x0=[norm, bg], bounds=([0, 0], [100, 1e6]))
print(result.summary())
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Callable, List, Optional, Sequence, Tuple
import numpy as np
from scipy.optimize import least_squares
@dataclass
class FitConfig:
"""Configuration for spectrum fitting."""
method: str = "trf"
"""Optimization method: 'trf', 'dogbox', 'lm'."""
max_nfev: int = 1000
"""Maximum function evaluations."""
x_scale: str | float = "jac"
"""Parameter scaling."""
loss: str = "linear"
"""Loss function: 'linear', 'soft_l1', 'huber', 'cauchy'."""
f_scale: float = 1.0
"""Robust loss scale parameter."""
ftol: float = 1e-10
"""Function value tolerance."""
xtol: float = 1e-10
"""Parameter change tolerance."""
gtol: float = 1e-10
"""Gradient tolerance."""
@dataclass
class FitResult:
"""Container for fit results."""
parameters: np.ndarray
"""Best-fit parameter values."""
covariance: np.ndarray
"""Parameter covariance matrix."""
chi2: float
"""Minimum χ² value."""
n_points: int
"""Number of data points."""
n_free: int
"""Number of free parameters."""
model_values: np.ndarray
"""Model values at best-fit parameters."""
residuals: np.ndarray
"""Data minus model."""
success: bool
"""Whether optimization converged."""
message: str
"""Optimization message."""
_residual_fn: Optional[Callable] = field(default=None, repr=False)
"""Residual function for profile likelihood."""
_x_data: Optional[np.ndarray] = field(default=None, repr=False)
"""Independent variable data."""
_y_data: Optional[np.ndarray] = field(default=None, repr=False)
"""Dependent variable data."""
_uncertainties: Optional[np.ndarray] = field(default=None, repr=False)
"""Measurement uncertainties."""
@property
def chi2_per_dof(self) -> float:
"""χ² per degree of freedom."""
return self.chi2 / max(self.n_free, 1)
@property
def p_value(self) -> float:
"""p-value for the fit (survival function of χ²)."""
from scipy.stats import chi2
return float(1.0 - chi2.cdf(self.chi2, self.n_points - self.n_free))
@property
def parameters_with_errors(self) -> dict[str, tuple[float, float]]:
"""Parameter values with 1σ uncertainties."""
errors = np.sqrt(np.maximum(np.diag(self.covariance), 0.0))
return {
f"p{i}": (float(self.parameters[i]), float(errors[i]))
for i in range(len(self.parameters))
}
@property
def correlation_matrix(self) -> np.ndarray:
"""Parameter correlation matrix."""
diag = np.sqrt(np.maximum(np.diag(self.covariance), 0.0))
if np.any(diag == 0):
return np.zeros_like(self.covariance)
return self.covariance / np.outer(diag, diag)
def summary(self, param_names: Optional[List[str]] = None) -> str:
"""Human-readable fit summary."""
lines = [
"=" * 60,
"Fit Results",
"=" * 60,
f"Converged: {self.success}",
f"Message: {self.message}",
f"χ² = {self.chi2:.4f}",
f"χ²/ndof = {self.chi2_per_dof:.3f} (ndof = {self.n_free})",
f"p-value = {self.p_value:.4f}",
"-" * 60,
"Parameters:",
]
errors = np.sqrt(np.maximum(np.diag(self.covariance), 0.0))
for i in range(len(self.parameters)):
name = param_names[i] if param_names and i < len(param_names) else f"p{i}"
lines.append(
f" {name:20s} = {self.parameters[i]:14.6f} ± {errors[i]:10.6f}"
)
lines.append("-" * 60)
lines.append("Correlation matrix (off-diagonal):")
corr = self.correlation_matrix
n = len(self.parameters)
header = " " + "".join(f"{f'p{i}':>12s}" for i in range(n))
lines.append(header)
for i in range(n):
name = param_names[i] if param_names and i < len(param_names) else f"p{i}"
row = f" {name:8s}" + "".join(
f"{corr[i, j]:12.3f}" for j in range(n) if j != i
)
lines.append(row)
lines.append("=" * 60)
return "\n".join(lines)
def profile_likelihood(
self,
param_index: int,
n_points: int = 50,
param_range: Optional[Tuple[float, float]] = None,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Compute profile likelihood for a single parameter."""
if self._residual_fn is None:
raise RuntimeError("Profile likelihood not available.")
if param_range is None:
sigma = np.sqrt(abs(self.covariance[param_index, param_index]))
center = self.parameters[param_index]
param_range = (center - 3 * sigma, center + 3 * sigma)
param_values = np.linspace(param_range[0], param_range[1], n_points)
chi2_values = np.zeros(n_points)
for i, pval in enumerate(param_values):
params = list(self.parameters)
params[param_index] = pval
res = self._residual_fn(np.array(params))
chi2_values[i] = np.sum(res**2)
min_chi2 = np.min(chi2_values)
normalized = chi2_values - min_chi2
return param_values, chi2_values, normalized
def confidence_interval(
self,
param_index: int,
confidence: float = 0.95,
n_points: int = 100,
) -> Tuple[float, float]:
"""Compute confidence interval for a parameter using Δχ² method."""
from scipy.stats import chi2
delta_chi2 = chi2.ppf(confidence, df=1)
param_values, chi2_values, normalized = self.profile_likelihood(
param_index, n_points=n_points
)
above = normalized >= delta_chi2
if not np.any(above):
return (
float(self.parameters[param_index]),
float(self.parameters[param_index]),
)
crossings = np.where(np.diff(above.astype(int)))[0]
if len(crossings) >= 2:
lower = param_values[crossings[0]]
upper = param_values[crossings[-1] + 1]
elif len(crossings) == 1:
lower = param_values[crossings[0]]
upper = param_values[-1]
else:
lower = param_values[0]
upper = param_values[-1]
return (float(lower), float(upper))
class SpectrumFitter:
"""Multi-parameter fitting engine for beta spectrum analysis.
Wraps a :class:`SpectrumModel` and experimental data to perform
χ² minimization with configurable loss functions and bounds.
Parameters
----------
model : SpectrumModel
Theoretical model (with optional detector convolution).
exp_energies : np.ndarray
Experimental energy grid (keV).
exp_counts : np.ndarray
Experimental counts per channel.
exp_errors : np.ndarray, optional
Experimental uncertainties. If None, assumed to be √counts.
config : FitConfig, optional
Fitting configuration.
"""
def __init__(
self,
model: Any,
exp_energies: np.ndarray,
exp_counts: np.ndarray,
exp_errors: Optional[np.ndarray] = None,
config: Optional[FitConfig] = None,
):
self.model = model
self.exp_energies = np.asarray(exp_energies, dtype=np.float64)
self.exp_counts = np.asarray(exp_counts, dtype=np.float64)
if exp_errors is not None:
self.exp_errors = np.asarray(exp_errors, dtype=np.float64)
else:
self.exp_errors = np.sqrt(np.maximum(self.exp_counts, 1.0))
# Filter out zero-uncertainty points
valid = self.exp_errors > 0
self.exp_energies = self.exp_energies[valid]
self.exp_counts = self.exp_counts[valid]
self.exp_errors = self.exp_errors[valid]
self.config = config or FitConfig()
self._n_params: Optional[int] = None
self._last_result: Optional[FitResult] = None
def _residuals(self, params: np.ndarray) -> np.ndarray:
"""Compute weighted residuals."""
model_values = self.model.evaluate(self.exp_energies, params[0], params[1])
return (self.exp_counts - model_values) / self.exp_errors
def _chi2(self, params: np.ndarray) -> float:
"""Compute χ²."""
model_values = self.model.evaluate(self.exp_energies, params[0], params[1])
return float(np.sum(((self.exp_counts - model_values) / self.exp_errors) ** 2))
def fit(
self,
x0: Optional[Sequence[float]] = None,
bounds: Optional[Tuple[Sequence[float], Sequence[float]]] = None,
param_names: Optional[List[str]] = None,
) -> FitResult:
"""Perform χ² minimization.
Parameters
----------
x0 : sequence of float, optional
Initial parameter values. Auto-estimated if None.
bounds : (lower, upper), optional
Parameter bounds.
param_names : list of str, optional
Parameter names for summary output.
Returns
-------
FitResult
"""
if x0 is None:
x0 = [1.0, 0.0]
x0_array = np.asarray(x0, dtype=np.float64)
self._n_params = len(x0_array)
bounds_array: Optional[Tuple[np.ndarray, np.ndarray]] = None
if bounds is not None:
bounds_array = (
np.asarray(bounds[0], dtype=np.float64),
np.asarray(bounds[1], dtype=np.float64),
)
ls_kwargs: dict[str, Any] = {
"fun": self._residuals,
"x0": x0_array,
"method": self.config.method,
"max_nfev": self.config.max_nfev,
"x_scale": self.config.x_scale,
"loss": self.config.loss,
"f_scale": self.config.f_scale,
"ftol": self.config.ftol,
"xtol": self.config.xtol,
"gtol": self.config.gtol,
}
if bounds is not None:
ls_kwargs["bounds"] = bounds_array
result = least_squares(**ls_kwargs)
# Compute covariance
cov = self._compute_covariance(result)
model_values = self.model.evaluate(self.exp_energies, *result.x)
residuals = self.exp_counts - model_values
fit_result = FitResult(
parameters=result.x,
covariance=cov,
chi2=self._chi2(result.x),
n_points=len(self.exp_energies),
n_free=self._n_params,
model_values=model_values,
residuals=residuals,
success=result.success,
message=result.message,
_residual_fn=self._residuals,
_x_data=self.exp_energies,
_y_data=self.exp_counts,
_uncertainties=self.exp_errors,
)
self._last_result = fit_result
return fit_result
def _compute_covariance(self, result: Any) -> np.ndarray:
"""Estimate parameter covariance from Jacobian."""
n = len(result.x)
cov = np.zeros((n, n))
if result.jac is not None:
jtj = result.jac.T @ result.jac
if np.linalg.cond(jtj) < 1e12:
cov = np.linalg.inv(jtj)
chi2 = self._chi2(result.x)
ndof = max(len(self.exp_energies) - n, 1)
cov = cov * chi2 / ndof
else:
cov = np.linalg.pinv(jtj)
chi2 = self._chi2(result.x)
ndof = max(len(self.exp_energies) - n, 1)
cov = cov * chi2 / ndof
return cov
@property
def parameters(self) -> np.ndarray:
"""Current best-fit parameters."""
if self._last_result is None:
raise RuntimeError("No fit result. Call fit() first.")
return self._last_result.parameters
@property
def covariance(self) -> np.ndarray:
"""Current covariance matrix."""
if self._last_result is None:
raise RuntimeError("No fit result. Call fit() first.")
return self._last_result.covariance
class CurveFitter:
"""General-purpose χ² curve fitter for arbitrary callable models.
This is a thin wrapper around scipy's least_squares that provides
the same API as the original beta_spectrum.fitter.CurveFitter.
Parameters
----------
model : callable
Function f(x, *params) that computes model values.
x_data : np.ndarray
Independent variable data.
y_data : np.ndarray
Dependent variable data.
uncertainties : np.ndarray, optional
Measurement uncertainties. If None, assumed to be 1.0.
config : FitConfig, optional
Fitting configuration.
Examples
--------
>>> def linear(x, a, b):
... return a + b * x
>>> fitter = CurveFitter(linear, x, y, uncertainties=unc)
>>> result = fitter.fit([0.0, 0.0])
"""
def __init__(
self,
model: Callable,
x_data: np.ndarray,
y_data: np.ndarray,
uncertainties: Optional[np.ndarray] = None,
config: Optional[FitConfig] = None,
):
self.model = model
self.x_data = np.asarray(x_data, dtype=np.float64)
self.y_data = np.asarray(y_data, dtype=np.float64)
if uncertainties is not None:
self.uncertainties = np.asarray(uncertainties, dtype=np.float64)
else:
self.uncertainties = np.ones_like(self.y_data)
# Filter out zero/negative uncertainty points
valid = self.uncertainties > 0
self.x_data = self.x_data[valid]
self.y_data = self.y_data[valid]
self.uncertainties = self.uncertainties[valid]
self.config = config or FitConfig()
self._last_result: Optional[FitResult] = None
self._n_params: Optional[int] = None
def _residuals(self, params: np.ndarray) -> np.ndarray:
"""Compute weighted residuals."""
model_values = self.model(self.x_data, *params)
return (self.y_data - model_values) / self.uncertainties
def _chi2(self, params: np.ndarray) -> float:
"""Compute χ²."""
model_values = self.model(self.x_data, *params)
return float(np.sum(((self.y_data - model_values) / self.uncertainties) ** 2))
def fit(
self,
x0: Sequence[float],
bounds: Optional[Tuple[Sequence[float], Sequence[float]]] = None,
) -> FitResult:
"""Perform χ² minimization.
Parameters
----------
x0 : sequence of float
Initial parameter values.
bounds : (lower, upper), optional
Parameter bounds.
Returns
-------
FitResult
"""
x0_array = np.asarray(x0, dtype=np.float64)
self._n_params = len(x0_array)
ls_kwargs: dict[str, Any] = {
"fun": self._residuals,
"x0": x0_array,
"method": self.config.method,
"max_nfev": self.config.max_nfev,
"x_scale": self.config.x_scale,
"loss": self.config.loss,
"f_scale": self.config.f_scale,
"ftol": self.config.ftol,
"xtol": self.config.xtol,
"gtol": self.config.gtol,
}
if bounds is not None:
ls_kwargs["bounds"] = (
np.asarray(bounds[0], dtype=np.float64),
np.asarray(bounds[1], dtype=np.float64),
)
result = least_squares(**ls_kwargs)
# Compute covariance
n = len(result.x)
cov = np.zeros((n, n))
if result.jac is not None:
jtj = result.jac.T @ result.jac
if np.linalg.cond(jtj) < 1e12:
cov = np.linalg.inv(jtj)
else:
cov = np.linalg.pinv(jtj)
chi2 = self._chi2(result.x)
ndof = max(len(self.x_data) - n, 1)
cov = cov * chi2 / ndof
model_values = self.model(self.x_data, *result.x)
fit_result = FitResult(
parameters=result.x,
covariance=cov,
chi2=self._chi2(result.x),
n_points=len(self.x_data),
n_free=self._n_params,
model_values=model_values,
residuals=self.y_data - model_values,
success=result.success,
message=result.message,
_residual_fn=self._residuals,
_x_data=self.x_data,
_y_data=self.y_data,
_uncertainties=self.uncertainties,
)
self._last_result = fit_result
return fit_result
@property
def parameters(self) -> np.ndarray:
"""Current best-fit parameters."""
if self._last_result is None:
raise RuntimeError("No fit result. Call fit() first.")
return self._last_result.parameters
@property
def covariance(self) -> np.ndarray:
"""Current covariance matrix."""
if self._last_result is None:
raise RuntimeError("No fit result. Call fit() first.")
return self._last_result.covariance
+237
View File
@@ -0,0 +1,237 @@
"""
Theoretical model for fitting — wraps BetaSpectrum + DetectorResponse.
Provides a callable interface that evaluates the theoretical spectrum,
optionally convolved with detector response, on an arbitrary energy grid.
Usage:
model = SpectrumModel(beta_spectrum, detector_response, channel_energies)
y_model = model(channel_energies, normalization, background)
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import numpy as np
if TYPE_CHECKING:
from beta_spectrum.spectrum import BetaSpectrum
from beta_spectrum.components.detector_response import DetectorResponse
from exp_data.spectrum import ExpSpectrum
class SpectrumModel:
"""Theoretical beta spectrum model for fitting to experimental data.
Wraps a :class:`beta_spectrum.BetaSpectrum` and optionally a
:class:`beta_spectrum.DetectorResponse` to produce a callable model
that can be fitted against experimental spectra.
The model computes:
y(E) = A · [S(E) ⊗ R(E)] + B
where S(E) is the theoretical spectrum, R(E) is the detector response,
⊗ denotes convolution, A is a normalization factor, and B is a constant
background level.
Parameters
----------
spectrum : BetaSpectrum
Theoretical spectrum calculator.
detector_response : DetectorResponse, optional
Detector response function. If None, no convolution is applied.
channel_energies : np.ndarray, optional
Energy values for detector channels (keV). Used to set up
the response if detector_response is None.
"""
def __init__(
self,
spectrum: "BetaSpectrum",
detector_response: Optional["DetectorResponse"] = None,
channel_energies: Optional[np.ndarray] = None,
):
self.spectrum = spectrum
self.detector_response = detector_response
self.channel_energies = channel_energies
# Cache for pre-computed unconvolved spectrum
self._cached_W: Optional[np.ndarray] = None
self._cached_spectral: Optional[np.ndarray] = None
def evaluate_unconvolved(
self,
energies_keV: Optional[np.ndarray] = None,
) -> np.ndarray:
"""Evaluate the theoretical spectrum (unconvolved).
Parameters
----------
energies_keV : np.ndarray, optional
Energy grid in keV. Uses the spectrum's internal grid if None.
Returns
-------
np.ndarray
Theoretical spectrum values.
"""
if energies_keV is not None:
W = self._keV_to_W(energies_keV)
return self.spectrum(W)
return self.spectrum(
self.spectrum._W_grid
if hasattr(self.spectrum, "_W_grid") and self.spectrum._W_grid is not None
else np.array([])
)
def _keV_to_W(self, energies_keV: np.ndarray) -> np.ndarray:
"""Convert kinetic energy in keV to total energy in m_e units."""
return energies_keV / 510.998950 + 1.0
def convolve(self, energies_keV: np.ndarray) -> np.ndarray:
"""Convolve theoretical spectrum with detector response.
Parameters
----------
energies_keV : np.ndarray
Energy grid in keV for the detector channels.
Returns
-------
np.ndarray
Convolved spectrum on the given energy grid.
Raises
------
RuntimeError
If no detector response is available.
"""
if self.detector_response is None:
raise RuntimeError(
"No detector response configured. "
"Provide a DetectorResponse to SpectrumModel."
)
# The detector's channel_energies are in m_e units
W = self.detector_response.channel_energies
# Clip W to valid range (W >= 1.0) before spectrum evaluation
W_safe = np.maximum(W, 1.0 + 1e-12)
spectral = self.spectrum(W_safe)
# Clip negative/NaN values from spectrum (numerical artifacts)
spectral = np.maximum(
np.nan_to_num(spectral, nan=0.0, posinf=0.0, neginf=0.0), 0.0
)
# Convolve: detector_response.convolve(W, spectrum, normalize)
return self.detector_response.convolve(W, spectral, normalize=True)
def evaluate(
self,
energies_keV: np.ndarray,
normalization: float = 1.0,
background: float = 0.0,
) -> np.ndarray:
"""Evaluate the full theoretical model (with optional convolution).
Parameters
----------
energies_keV : np.ndarray
Energy grid in keV.
normalization : float
Multiplicative normalization factor.
background : float
Constant background level.
Returns
-------
np.ndarray
Model prediction: A · (S ⊗ R) + B
"""
if self.detector_response is not None:
spectral = self.convolve(energies_keV)
else:
spectral = self.spectrum(self._keV_to_W(energies_keV))
return normalization * spectral + background
def residual(
self,
params: np.ndarray,
exp_energies: np.ndarray,
exp_counts: np.ndarray,
exp_errors: np.ndarray,
) -> np.ndarray:
"""Compute weighted residuals for fitting.
Parameters
----------
params : np.ndarray
Fit parameters [normalization, background, ...].
exp_energies : np.ndarray
Experimental energy grid (keV).
exp_counts : np.ndarray
Experimental counts.
exp_errors : np.ndarray
Experimental uncertainties.
Returns
-------
np.ndarray
Weighted residuals: (exp - model) / σ
"""
model_values = self.evaluate(exp_energies, params[0], params[1])
return (exp_counts - model_values) / exp_errors
@staticmethod
def default_params(
exp_spectrum: "ExpSpectrum",
) -> tuple[float, float]:
"""Estimate default fit parameters from experimental data.
Parameters
----------
exp_spectrum : ExpSpectrum
Experimental spectrum.
Returns
-------
(normalization, background)
Initial parameter estimates.
"""
# Background from low-energy sideband
mask_low = exp_spectrum.energies < np.percentile(exp_spectrum.energies, 5)
background = (
float(np.mean(exp_spectrum.counts[mask_low])) if np.any(mask_low) else 0.0
)
# Normalization from total counts / integral of unconvolved model
total_counts = float(np.sum(exp_spectrum.counts))
unconvolved = exp_spectrum.counts - background
norm = total_counts / max(
float(np.trapezoid(unconvolved, exp_spectrum.energies)), 1e-10
)
return (norm, background)
@staticmethod
def default_bounds(
n_channels: int,
) -> tuple[list[float], list[float]]:
"""Estimate default parameter bounds.
Parameters
----------
n_channels : int
Number of energy channels.
Returns
-------
(lower_bounds, upper_bounds)
Parameter bounds for [normalization, background].
"""
return (
[0.01, 0.0],
[100.0, 1e6],
)
+132
View File
@@ -0,0 +1,132 @@
"""
Analysis result container for beta spectrum fitting.
Wraps fit results with physics-specific metadata (nuclide, extracted
C(W) values, g_V, g_A, etc.).
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple
import numpy as np
if TYPE_CHECKING:
from beta_spectrum.spectrum import SpectrumConfig
@dataclass
class FitSummary:
"""Compact fit summary for reporting."""
nuclide: str
"""Nuclide identifier (e.g. 'Tc99')."""
converged: bool
"""Whether the fit converged."""
chi2_per_dof: float
"""Reduced χ²."""
p_value: float
"""Fit p-value."""
parameters: Dict[str, Tuple[float, float]]
"""Parameter names → (value, error)."""
def __str__(self) -> str:
lines = [
f"Fit Summary: {self.nuclide}",
f" Converged: {self.converged}",
f" χ²/ndof: {self.chi2_per_dof:.3f}",
f" p-value: {self.p_value:.4f}",
" Parameters:",
]
for name, (val, err) in self.parameters.items():
lines.append(f" {name:20s} = {val:12.6f} ± {err:10.6f}")
return "\n".join(lines)
@dataclass
class AnalysisResult:
"""Complete analysis result from spectrum fitting.
Parameters
----------
fit_result : FitResult
Low-level fit result from SpectrumFitter.
nuclide : str, optional
Nuclide identifier.
config : SpectrumConfig, optional
Original spectrum configuration.
cw_values : np.ndarray, optional
Extracted C(W) values at each energy bin.
cw_errors : np.ndarray, optional
Uncertainties on C(W).
gv_eff : float, optional
Effective vector coupling constant.
ga_eff : float, optional
Effective axial coupling constant.
endpoint_keV : float, optional
Extracted endpoint energy.
metadata : dict, optional
Additional analysis metadata.
"""
fit_result: Any # FitResult from SpectrumFitter
nuclide: str = ""
config: Optional["SpectrumConfig"] = None
cw_values: Optional[np.ndarray] = None
cw_errors: Optional[np.ndarray] = None
gv_eff: Optional[float] = None
ga_eff: Optional[float] = None
endpoint_keV: Optional[float] = None
metadata: Dict[str, Any] = field(default_factory=dict)
@property
def summary(self) -> FitSummary:
"""Get a FitSummary from this result."""
fr = self.fit_result
param_names = self.metadata.get("param_names", None)
params = {}
if hasattr(fr, "parameters_with_errors"):
params = fr.parameters_with_errors
elif hasattr(fr, "parameters"):
errors = np.sqrt(np.maximum(np.diag(fr.covariance), 0.0))
for i in range(len(fr.parameters)):
name = (
param_names[i] if param_names and i < len(param_names) else f"p{i}"
)
params[name] = (float(fr.parameters[i]), float(errors[i]))
return FitSummary(
nuclide=self.nuclide,
converged=fr.success if hasattr(fr, "success") else False,
chi2_per_dof=fr.chi2_per_dof if hasattr(fr, "chi2_per_dof") else 0.0,
p_value=fr.p_value if hasattr(fr, "p_value") else 0.0,
parameters=params,
)
def to_dict(self) -> Dict[str, Any]:
"""Serialize to dictionary."""
return {
"nuclide": self.nuclide,
"converged": (
self.fit_result.success
if hasattr(self.fit_result, "success")
else False
),
"chi2_per_dof": (
self.fit_result.chi2_per_dof
if hasattr(self.fit_result, "chi2_per_dof")
else 0.0
),
"p_value": (
self.fit_result.p_value if hasattr(self.fit_result, "p_value") else 0.0
),
"gv_eff": self.gv_eff,
"ga_eff": self.ga_eff,
"endpoint_keV": self.endpoint_keV,
"metadata": self.metadata,
}