refactor: remove fitter analysis framework
Spectrum model, convolution, chi2 fit engine, C(W) and g_V/g_A extractors and result containers are analysis code outside the theory-only scope. Removes the package and its test suites.
This commit is contained in:
@@ -1,161 +0,0 @@
|
||||
"""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)
|
||||
@@ -1,176 +0,0 @@
|
||||
"""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) -> None:
|
||||
config = FitConfig()
|
||||
assert config.method == "trf"
|
||||
assert config.max_nfev == 1000
|
||||
assert config.loss == "linear"
|
||||
|
||||
|
||||
class TestSpectrumFitter:
|
||||
"""Test SpectrumFitter."""
|
||||
|
||||
def _make_fitter(self) -> "SpectrumFitter":
|
||||
"""Create a simple fitter with synthetic data."""
|
||||
|
||||
# Create a simple linear model
|
||||
def linear_model(
|
||||
energies_keV: np.ndarray, norm: float, bg: float
|
||||
) -> np.ndarray:
|
||||
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: np.ndarray, norm: float, bg: float
|
||||
) -> np.ndarray:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
fitter = self._make_fitter()
|
||||
fitter.fit(x0=[10.0, 2.0])
|
||||
params = fitter.parameters
|
||||
assert len(params) == 2
|
||||
|
||||
def test_covariance_property(self) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
from beta_spectrum import BetaSpectrum, SpectrumConfig
|
||||
|
||||
config = SpectrumConfig(
|
||||
Z_parent=43,
|
||||
Z_daughter=44,
|
||||
A_number=99,
|
||||
endpoint_MeV=0.294,
|
||||
)
|
||||
spectrum = BetaSpectrum.from_config(config)
|
||||
model = SpectrumModel(spectrum)
|
||||
|
||||
# Generate synthetic data from the unconvolved model on a keV grid
|
||||
energies_keV = np.linspace(1.0, 293.0, 200)
|
||||
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
|
||||
@@ -1,98 +0,0 @@
|
||||
"""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) -> tuple[SpectrumModel, SpectrumConfig]:
|
||||
"""Create a test SpectrumModel (no detector response)."""
|
||||
config = SpectrumConfig(
|
||||
Z_parent=43,
|
||||
Z_daughter=44,
|
||||
A_number=99,
|
||||
endpoint_MeV=0.294,
|
||||
)
|
||||
spectrum = BetaSpectrum.from_config(config)
|
||||
|
||||
model = SpectrumModel(spectrum)
|
||||
return model, config
|
||||
|
||||
def test_evaluate_unconvolved(self) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
model, _ = self._make_model()
|
||||
energies_keV = np.linspace(0.01, 0.29, 50)
|
||||
with pytest.raises(RuntimeError):
|
||||
model.convolve(energies_keV)
|
||||
|
||||
def test_default_params(self) -> None:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
config = SpectrumConfig(
|
||||
Z_parent=43, Z_daughter=44, A_number=99, endpoint_MeV=0.294
|
||||
)
|
||||
model = SpectrumModel(BetaSpectrum.from_config(config))
|
||||
# 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)
|
||||
@@ -1,100 +0,0 @@
|
||||
"""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 == ""
|
||||
@@ -1,448 +0,0 @@
|
||||
# tests/test_fitter.py — Tests for χ² minimization framework
|
||||
|
||||
"""
|
||||
Why test this?
|
||||
--------------
|
||||
The fitter is the core numerical tool for extracting physical parameters
|
||||
from beta spectra. It must be correct because all downstream results
|
||||
(g_V, g_A, C(W) extraction) depend on it.
|
||||
|
||||
We test:
|
||||
1. Basic χ² minimization on known functions (quadratic, linear).
|
||||
2. Covariance matrix estimation (should match input uncertainties).
|
||||
3. Confidence interval computation via profile likelihood.
|
||||
4. Goodness-of-fit metrics (χ²/ndf, p-value).
|
||||
5. Bounds handling and convergence diagnostics.
|
||||
6. Robust loss functions (soft_l1, huber) for outlier resistance.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from fitter.fit_engine import CurveFitter, FitConfig
|
||||
|
||||
|
||||
class TestBasicFitting:
|
||||
"""Test χ² minimization on simple known functions."""
|
||||
|
||||
def test_quadratic_fit(self):
|
||||
"""Fit y = a + b·x + c·x² with known coefficients."""
|
||||
np.random.seed(42)
|
||||
x = np.linspace(0, 10, 50)
|
||||
true_params = [1.0, 2.0, -0.1]
|
||||
y = true_params[0] + true_params[1] * x + true_params[2] * x**2
|
||||
y += np.random.normal(0, 0.5, len(x))
|
||||
|
||||
def model(x, a, b, c):
|
||||
return a + b * x + c * x**2
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(y) * 0.5)
|
||||
result = fitter.fit([0.0, 0.0, 0.0])
|
||||
|
||||
for i, name in enumerate(["a", "b", "c"]):
|
||||
assert (
|
||||
abs(result.parameters[i] - true_params[i]) < 0.5
|
||||
), f"Parameter {name}: expected {true_params[i]}, got {result.parameters[i]}"
|
||||
|
||||
assert result.success, "Fit should converge"
|
||||
assert result.chi2 > 0, "χ² must be positive"
|
||||
|
||||
def test_linear_fit(self):
|
||||
"""Fit y = a + b·x with known coefficients."""
|
||||
np.random.seed(123)
|
||||
x = np.linspace(0, 5, 30)
|
||||
true_a, true_b = 3.0, -1.5
|
||||
y = true_a + true_b * x
|
||||
y += np.random.normal(0, 0.2, len(x))
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(y) * 0.2)
|
||||
result = fitter.fit([0.0, 0.0])
|
||||
|
||||
assert abs(result.parameters[0] - true_a) < 0.3
|
||||
assert abs(result.parameters[1] - true_b) < 0.3
|
||||
assert result.success
|
||||
|
||||
def test_constant_fit(self):
|
||||
"""Fit y = a (constant) with known value."""
|
||||
np.random.seed(456)
|
||||
x = np.linspace(0, 10, 40)
|
||||
true_a = 5.0
|
||||
y = np.full_like(x, true_a)
|
||||
y += np.random.normal(0, 0.3, len(x))
|
||||
|
||||
def model(x, a):
|
||||
return np.full_like(x, a)
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.3)
|
||||
result = fitter.fit([0.0])
|
||||
|
||||
assert abs(result.parameters[0] - true_a) < 0.2
|
||||
assert result.success
|
||||
|
||||
|
||||
class TestCovarianceEstimation:
|
||||
"""Test that covariance matrix is correctly estimated."""
|
||||
|
||||
def test_covariance_matches_uncertainty(self):
|
||||
"""For a constant model, parameter error should match input σ."""
|
||||
np.random.seed(789)
|
||||
x = np.linspace(0, 10, 50)
|
||||
true_a = 5.0
|
||||
sigma = 0.5
|
||||
y = np.full_like(x, true_a, dtype=float)
|
||||
y += np.random.normal(0, sigma, len(x))
|
||||
|
||||
def model(x, a):
|
||||
return np.full_like(x, a)
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * sigma)
|
||||
result = fitter.fit([0.0])
|
||||
|
||||
error = np.sqrt(result.covariance[0, 0])
|
||||
# Expected error: σ / sqrt(N)
|
||||
expected_error = sigma / np.sqrt(len(x))
|
||||
assert (
|
||||
abs(error - expected_error) < expected_error * 0.3
|
||||
), f"Covariance error {error:.4f} != expected {expected_error:.4f}"
|
||||
|
||||
def test_covariance_matrix_positive_definite(self):
|
||||
"""Covariance matrix must be positive definite."""
|
||||
np.random.seed(321)
|
||||
x = np.linspace(0, 5, 30)
|
||||
y = 2.0 + 1.5 * x - 0.3 * x**2
|
||||
y += np.random.normal(0, 0.2, len(x))
|
||||
|
||||
def model(x, a, b, c):
|
||||
return a + b * x + c * x**2
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.2)
|
||||
result = fitter.fit([0.0, 0.0, 0.0])
|
||||
|
||||
# Check eigenvalues are non-negative
|
||||
eigvals = np.linalg.eigvalsh(result.covariance)
|
||||
assert np.all(eigvals >= -1e-10), f"Covariance not positive definite: {eigvals}"
|
||||
|
||||
def test_correlation_matrix(self):
|
||||
"""Correlation matrix should have 1.0 on diagonal."""
|
||||
np.random.seed(654)
|
||||
x = np.linspace(0, 10, 50)
|
||||
y = 1.0 + 2.0 * x + 0.1 * x**2
|
||||
y += np.random.normal(0, 0.5, len(x))
|
||||
|
||||
def model(x, a, b, c):
|
||||
return a + b * x + c * x**2
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.5)
|
||||
result = fitter.fit([0.0, 0.0, 0.0])
|
||||
|
||||
diag = np.diag(result.correlation_matrix)
|
||||
assert np.allclose(
|
||||
diag, 1.0, atol=1e-6
|
||||
), f"Diagonal of correlation matrix: {diag}"
|
||||
|
||||
|
||||
class TestGoodnessOfFit:
|
||||
"""Test χ²/ndf and p-value calculations."""
|
||||
|
||||
def test_chi2_per_dof(self):
|
||||
"""χ²/ndof should be positive and reasonable."""
|
||||
np.random.seed(111)
|
||||
x = np.linspace(0, 10, 50)
|
||||
y = 2.0 * x
|
||||
y += np.random.normal(0, 0.3, len(x))
|
||||
|
||||
def model(x, a):
|
||||
return a * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.3)
|
||||
result = fitter.fit([0.0])
|
||||
|
||||
assert result.chi2_per_dof > 0
|
||||
assert result.n_points == 50
|
||||
assert result.n_free == 1
|
||||
assert result.n_free == 1
|
||||
|
||||
def test_p_value_range(self):
|
||||
"""p-value should be in [0, 1]."""
|
||||
np.random.seed(222)
|
||||
x = np.linspace(0, 5, 30)
|
||||
y = 1.0 + x
|
||||
y += np.random.normal(0, 0.1, len(x))
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.1)
|
||||
result = fitter.fit([0.0, 0.0])
|
||||
|
||||
assert 0.0 <= result.p_value <= 1.0
|
||||
|
||||
def test_p_value_good_fit(self):
|
||||
"""Good fit should have reasonable p-value."""
|
||||
np.random.seed(333)
|
||||
x = np.linspace(0, 10, 100)
|
||||
y = 3.0 + 1.5 * x - 0.05 * x**2
|
||||
y += np.random.normal(0, 0.2, len(x))
|
||||
|
||||
def model(x, a, b, c):
|
||||
return a + b * x + c * x**2
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.2)
|
||||
result = fitter.fit([0.0, 0.0, 0.0])
|
||||
|
||||
assert (
|
||||
result.p_value > 0.001
|
||||
), f"Good fit should have reasonable p-value, got {result.p_value}"
|
||||
|
||||
|
||||
class TestBounds:
|
||||
"""Test parameter bounds handling."""
|
||||
|
||||
def test_lower_bound(self):
|
||||
"""Test that lower bounds are respected."""
|
||||
np.random.seed(444)
|
||||
x = np.linspace(0, 5, 30)
|
||||
y = 2.0 + 1.0 * x
|
||||
y += np.random.normal(0, 0.1, len(x))
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.1)
|
||||
result = fitter.fit([1.5, 0.5], bounds=([1.0, 0.0], [10.0, 5.0]))
|
||||
|
||||
assert (
|
||||
result.parameters[0] >= 1.0
|
||||
), f"Parameter a should be >= 1.0, got {result.parameters[0]}"
|
||||
assert (
|
||||
result.parameters[1] >= 0.0
|
||||
), f"Parameter b should be >= 0.0, got {result.parameters[1]}"
|
||||
|
||||
def test_upper_bound(self):
|
||||
"""Test that upper bounds are respected."""
|
||||
np.random.seed(555)
|
||||
x = np.linspace(0, 5, 30)
|
||||
y = 0.5 + 0.5 * x
|
||||
y += np.random.normal(0, 0.1, len(x))
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.1)
|
||||
result = fitter.fit([0.5, 0.5], bounds=([0.0, 0.0], [1.0, 1.0]))
|
||||
|
||||
assert result.parameters[0] <= 1.0
|
||||
assert result.parameters[1] <= 1.0
|
||||
|
||||
|
||||
class TestRobustLoss:
|
||||
"""Test robust loss functions for outlier resistance."""
|
||||
|
||||
def test_soft_l1_loss(self):
|
||||
"""soft_l1 loss should handle outliers better than linear."""
|
||||
np.random.seed(666)
|
||||
x = np.linspace(0, 10, 50)
|
||||
y = 1.0 + 2.0 * x
|
||||
y[25] = 50.0 # Add outlier
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
# Linear loss — outlier pulls fit away
|
||||
config_linear = FitConfig(loss="linear")
|
||||
fitter_linear = CurveFitter(
|
||||
model, x, y, uncertainties=np.ones_like(x) * 1.0, config=config_linear
|
||||
)
|
||||
result_linear = fitter_linear.fit([0.0, 0.0])
|
||||
|
||||
# soft_l1 loss — outlier has less influence
|
||||
config_robust = FitConfig(loss="soft_l1")
|
||||
fitter_robust = CurveFitter(
|
||||
model, x, y, uncertainties=np.ones_like(x) * 1.0, config=config_robust
|
||||
)
|
||||
result_robust = fitter_robust.fit([0.0, 0.0])
|
||||
|
||||
# Robust fit should be closer to true slope
|
||||
assert (
|
||||
abs(result_robust.parameters[1] - 2.0)
|
||||
< abs(result_linear.parameters[1] - 2.0) * 1.5
|
||||
), "Robust loss should handle outliers better"
|
||||
|
||||
|
||||
class TestFitResult:
|
||||
"""Test FitResult dataclass methods."""
|
||||
|
||||
def test_parameters_with_errors(self):
|
||||
"""parameters_with_errors should return dict of (value, error)."""
|
||||
np.random.seed(777)
|
||||
x = np.linspace(0, 5, 30)
|
||||
y = 2.0 + x
|
||||
y += np.random.normal(0, 0.1, len(x))
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.1)
|
||||
result = fitter.fit([0.0, 0.0])
|
||||
|
||||
errors = result.parameters_with_errors
|
||||
assert len(errors) == 2
|
||||
for key, (val, err) in errors.items():
|
||||
assert isinstance(val, float)
|
||||
assert isinstance(err, float)
|
||||
assert err >= 0
|
||||
|
||||
def test_summary(self):
|
||||
"""summary() should return a non-empty string."""
|
||||
np.random.seed(888)
|
||||
x = np.linspace(0, 5, 30)
|
||||
y = 1.0 + 2.0 * x
|
||||
y += np.random.normal(0, 0.1, len(x))
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.1)
|
||||
result = fitter.fit([0.0, 0.0])
|
||||
|
||||
summary = result.summary(param_names=["a", "b"])
|
||||
assert "Fit Results" in summary
|
||||
assert "a" in summary
|
||||
assert "b" in summary
|
||||
assert "χ²" in summary
|
||||
assert "Converged" in summary
|
||||
|
||||
def test_residuals_property(self):
|
||||
"""residuals should be data - model."""
|
||||
np.random.seed(999)
|
||||
x = np.linspace(0, 5, 30)
|
||||
y = 2.0 + x
|
||||
y += np.random.normal(0, 0.1, len(x))
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.1)
|
||||
result = fitter.fit([0.0, 0.0])
|
||||
|
||||
expected_residuals = y - result.model_values
|
||||
np.testing.assert_allclose(result.residuals, expected_residuals)
|
||||
|
||||
|
||||
class TestFitConfig:
|
||||
"""Test FitConfig options."""
|
||||
|
||||
def test_custom_config(self):
|
||||
"""Custom FitConfig should be respected."""
|
||||
np.random.seed(101)
|
||||
x = np.linspace(0, 5, 30)
|
||||
y = 1.0 + x
|
||||
y += np.random.normal(0, 0.1, len(x))
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
config = FitConfig(
|
||||
method="trf",
|
||||
max_nfev=500,
|
||||
loss="linear",
|
||||
ftol=1e-10,
|
||||
)
|
||||
fitter = CurveFitter(
|
||||
model, x, y, uncertainties=np.ones_like(x) * 0.1, config=config
|
||||
)
|
||||
result = fitter.fit([0.0, 0.0])
|
||||
|
||||
assert result.success
|
||||
|
||||
|
||||
class TestConfidenceIntervals:
|
||||
"""Test confidence interval computation."""
|
||||
|
||||
def test_95_percent_ci(self):
|
||||
"""95% CI should contain the true parameter value."""
|
||||
np.random.seed(202)
|
||||
x = np.linspace(0, 10, 60)
|
||||
true_a, true_b = 2.0, 1.5
|
||||
y = true_a + true_b * x
|
||||
y += np.random.normal(0, 0.3, len(x))
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.3)
|
||||
result = fitter.fit([0.0, 0.0])
|
||||
|
||||
ci_a = result.confidence_interval(0, confidence=0.95)
|
||||
ci_b = result.confidence_interval(1, confidence=0.95)
|
||||
|
||||
assert ci_a[0] <= true_a <= ci_a[1], f"True a={true_a} not in CI {ci_a}"
|
||||
assert ci_b[0] <= true_b <= ci_b[1], f"True b={true_b} not in CI {ci_b}"
|
||||
|
||||
def test_ci_width_increases_with_confidence(self):
|
||||
"""Higher confidence level → wider interval."""
|
||||
np.random.seed(303)
|
||||
x = np.linspace(0, 5, 40)
|
||||
y = 1.0 + 2.0 * x
|
||||
y += np.random.normal(0, 0.2, len(x))
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.2)
|
||||
result = fitter.fit([0.0, 0.0])
|
||||
|
||||
ci_90 = result.confidence_interval(0, confidence=0.90)
|
||||
ci_95 = result.confidence_interval(0, confidence=0.95)
|
||||
|
||||
width_90 = ci_90[1] - ci_90[0]
|
||||
width_95 = ci_95[1] - ci_95[0]
|
||||
|
||||
assert (
|
||||
width_95 > width_90
|
||||
), f"95% CI width {width_95} should be > 90% width {width_90}"
|
||||
|
||||
|
||||
class TestEdgeCases:
|
||||
"""Test edge cases and error handling."""
|
||||
|
||||
def test_zero_uncertainties_filtered(self):
|
||||
"""Points with zero uncertainty should be filtered out."""
|
||||
x = np.array([1.0, 2.0, 3.0, 4.0])
|
||||
y = np.array([2.0, 4.0, 6.0, 8.0])
|
||||
unc = np.array([1.0, 0.0, 1.0, 0.0])
|
||||
|
||||
def model(x, a):
|
||||
return a * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=unc)
|
||||
assert len(fitter.x_data) == 2, "Zero-uncertainty points should be removed"
|
||||
assert len(fitter.y_data) == 2
|
||||
|
||||
def test_negative_uncertainties_filtered(self):
|
||||
"""Points with negative uncertainty should be filtered out."""
|
||||
x = np.array([1.0, 2.0, 3.0])
|
||||
y = np.array([2.0, 4.0, 6.0])
|
||||
unc = np.array([1.0, -1.0, 1.0])
|
||||
|
||||
def model(x, a):
|
||||
return a * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=unc)
|
||||
assert len(fitter.x_data) == 2
|
||||
|
||||
def test_unbounded_parameters(self):
|
||||
"""Unbounded parameters (±inf) should work."""
|
||||
np.random.seed(404)
|
||||
x = np.linspace(0, 5, 30)
|
||||
y = 1.0 + 2.0 * x
|
||||
y += np.random.normal(0, 0.1, len(x))
|
||||
|
||||
def model(x, a, b):
|
||||
return a + b * x
|
||||
|
||||
fitter = CurveFitter(model, x, y, uncertainties=np.ones_like(x) * 0.1)
|
||||
result = fitter.fit([0.0, 0.0], bounds=([-np.inf, -np.inf], [np.inf, np.inf]))
|
||||
assert result.success
|
||||
Reference in New Issue
Block a user