gwexpy.fitting
The gwexpy.fitting module provides advanced fitting functionality using iminuit.
Overview
Least Squares Fitting: Supports real and complex data
GLS (Generalized Least Squares): Fitting with covariance matrix consideration
MCMC: Bayesian estimation using emcee
Integrated Pipeline: One-liner API for bootstrap → GLS → MCMC workflow
Classes and Functions
Main Functions
Name |
Description |
|---|---|
|
Fit a Series object |
|
Integrated spectrum analysis pipeline |
Classes
Name |
Description |
|---|---|
|
Class to store fit results |
|
GLS cost function class |
|
Cost function for real data |
|
Cost function for complex data |
fit_series
fit_series(
series,
model,
x_range=None,
sigma=None,
cov=None,
cost_function=None,
p0=None,
limits=None,
fixed=None,
**kwargs
)
Parameters
Name |
Type |
Description |
|---|---|---|
|
Series |
Data to fit |
|
callable / str |
Model function or name (“gaussian”, “power_law”, etc.) |
|
tuple |
Fit range (xmin, xmax) |
|
array / scalar |
Errors (ignored if |
|
BifrequencyMap / ndarray |
Covariance matrix (for GLS) |
|
callable |
Custom cost function (highest priority) |
|
dict / list |
Initial parameter values |
|
dict |
Parameter limits {“A”: (0, 100)} |
|
list |
Parameter names to fix |
Returns
FitResult object
Example
from gwexpy.frequencyseries import FrequencySeries
from gwexpy.fitting import fit_series
# Prepare data
fs = FrequencySeries(y, frequencies=frequencies)
# Basic fit
result = fit_series(fs, "power_law", p0={"A": 10, "alpha": -1.5})
# GLS fit (with covariance matrix)
result = fit_series(fs, "power_law", cov=covariance_matrix, p0={"A": 10, "alpha": -1.5})
# Check results
print(result.params)
print(result.errors)
result.plot()
fit_bootstrap_spectrum
fit_bootstrap_spectrum(
data_or_spectrogram,
model_fn,
freq_range=None,
method="median",
rebin_width=None,
block_size=None,
ci=0.68,
window="hann",
fftlength=None,
overlap=None,
n_boot=1000,
initial_params=None,
bounds=None,
fixed=None,
run_mcmc=False,
mcmc_walkers=32,
mcmc_steps=5000,
mcmc_burn_in=500,
plot=True,
progress=True,
)
Parameters
Name |
Type |
Description |
|---|---|---|
|
TimeSeries / Spectrogram |
Input data |
|
callable |
Model function |
|
tuple |
Frequency range for fitting |
|
str |
Bootstrap averaging method (“median” / “mean”) |
|
float |
Frequency rebinning width (Hz) |
|
float / Quantity / ‘auto’ |
Block duration in seconds for block bootstrap |
|
float |
Confidence interval (default: 0.68) |
|
str |
Window function for FFT (default: “hann”) |
|
float or Quantity |
FFT segment length in seconds (default: None, auto-calculated) |
|
float or Quantity |
Overlap length in seconds (default: None, window-dependent) |
|
int |
Number of bootstrap iterations |
|
dict |
Initial parameters |
|
dict |
Parameter limits |
|
bool |
Whether to run MCMC |
|
int |
Number of MCMC steps |
|
bool |
Whether to plot results |
Returns
FitResult object (with additional attributes):
psd: Bootstrap PSDcov: Covariance BifrequencyMapbootstrap_method: Averaging method used
Example
from gwexpy.fitting import fit_bootstrap_spectrum
def power_law(f, A, alpha):
return A * f**alpha
result = fit_bootstrap_spectrum(
spectrogram,
model_fn=power_law,
freq_range=(5, 50),
rebin_width=0.5,
block_size=2.0, # 2 seconds
initial_params={"A": 10, "alpha": -1.5},
run_mcmc=True,
mcmc_steps=3000,
)
# Results
print(result.params)
print(result.parameter_intervals) # MCMC confidence intervals
result.plot_corner()
FitResult
Class to store fit results.
Properties
Name |
Type |
Description |
|---|---|---|
|
dict |
Best-fit parameters |
|
dict |
Parameter errors |
|
float |
χ² value |
|
int |
Degrees of freedom |
|
float |
Reduced χ² |
|
ndarray |
GLS covariance inverse |
|
dict |
MCMC percentiles (16, 50, 84) |
|
ndarray |
Full MCMC chain |
|
ndarray |
MCMC samples (after burn-in) |
Methods
Name |
Description |
|---|---|
|
Plot data and fit curve |
|
Bode plot (for complex data) |
|
Run MCMC |
|
Corner plot |
|
Fit plot with confidence band |
Example
result = fit_series(fs, "power_law", p0={"A": 10, "alpha": -1.5})
# Basic info
print(result) # Minuit output
print(f"χ²/dof = {result.reduced_chi2:.2f}")
# Plotting
result.plot()
# MCMC
result.run_mcmc(n_steps=5000, burn_in=500)
print(result.parameter_intervals)
result.plot_corner()
result.plot_fit_band()
GeneralizedLeastSquares
GLS cost function using covariance inverse.
class GeneralizedLeastSquares:
errordef = 1.0 # Minuit.LEAST_SQUARES
def __init__(self, x, y, cov_inv, model):
...
def __call__(self, *args) -> float:
# χ² = r.T @ cov_inv @ r
...
@property
def ndata(self) -> int:
...
Example
from gwexpy.fitting import GeneralizedLeastSquares, fit_series
from iminuit import Minuit
# Direct usage
def linear(x, a, b):
return a * x + b
gls = GeneralizedLeastSquares(x, y, cov_inv, linear)
m = Minuit(gls, a=1, b=0)
m.migrad()
# Via fit_series
result = fit_series(ts, linear, cost_function=gls, p0={"a": 1, "b": 0})
Built-in Models
Models available in gwexpy.fitting.models:
Name |
Formula |
Parameters |
|---|---|---|
|
A * exp(-(x-μ)²/(2σ²)) |
A, mu, sigma |
|
A * x^α |
A, alpha |
|
A _ exp(-t/τ) _ cos(2πft + φ) |
A, tau, f, phi |
|
c₀ + c₁x + c₂x² + … |
p0, p1, … |
|
A / ((x-x₀)² + γ²) |
A, x0, gamma |
|
A * exp(-x/τ) |
A, tau |
Dependencies
iminuit: Requiredemcee: Required for MCMC functionalitycorner: Required for corner plots
Unit & Model Semantics
gwexpy.fitting ensures unit consistency between data and models:
Unit Propagation: When a model is evaluated via
result.model(x), it automatically respects the units of the input data.If input
xis in \(Hz\), the model evaluates using frequency units.The output
yretains the unit of the fitted data (e.g., \(m\), \(V^2/Hz\)).
Parameter Access:
result.params['name']returns an object with.valueand.errorattributes, decoupling the numerical value from statistical uncertainty.