socca.fitting¶
- class socca.fitting.fitter(img, mod)¶
Bases:
objectMain inference engine for fitting astronomical models to image data.
The fitter class orchestrates Bayesian inference using nested sampling (dynesty, nautilus) or MCMC (numpyro) methods. It manages likelihood computation, prior transformations, and sampler execution.
- __init__(img, mod)[source]¶
Initialize the fitter with an image and model.
Sets up the fitting infrastructure by extracting noise properties, parameter labels, and initializing the plotting interface.
- Parameters:
- Variables:
img (Image) – Reference to the input image object.
mod (Model) – Reference to the input model object.
mask (ndarray) – Boolean mask from the noise model indicating valid pixels.
pdfnoise (callable) – Log-probability density function from the noise model.
pdfkwarg (list of str) – Parameter names expected by the noise PDF function.
labels (list of str) – Parameter names for the fitted parameters.
units (list of str) – Physical units for each fitted parameter.
plot (Plotter) – Plotting interface for visualization of results.
- bmc(verbose=True)[source]¶
Compute Bayesian model comparison estimators.
Calculates the Bayes factor and effective detection significance for model comparison against the null model (data only). Optionally computes prior-deboosted values if prior evidence is available.
- Parameters:
verbose (bool, optional) – If True, print the computed statistics. Default is True.
- Returns:
lnBF_raw (float) – Natural logarithm of the raw Bayes factor (model vs. null).
seff_raw (float) – Effective Gaussian detection significance for raw Bayes factor, computed as
sign(ln BF) * sqrt(2 * |ln BF|).lnBF_cor (float or None) – Natural logarithm of the prior-deboosted Bayes factor. None if prior evidence was not computed.
seff_cor (float or None) – Effective significance for prior-deboosted Bayes factor. None if prior evidence was not computed.
Warning
- UserWarning
If prior evidence (logz_prior) is None, warns that prior deboosting cannot be applied.
Notes
The raw Bayes factor compares the model evidence to the null model evidence (data-only). The prior-deboosted Bayes factor additionally accounts for the prior volume to avoid Occam’s razor penalty when the prior is uninformative.
The effective significance approximates the detection significance in terms of Gaussian standard deviations using the Wilks’ theorem approximation:
sigma_eff = sign(ln BF) * sqrt(2 * |ln BF|).
- dump(filename)[source]¶
Save the fitter object to a pickle file.
Serializes the entire fitter object state including samples, weights, sampler objects, and all attributes to a file using dill for enhanced pickling support.
- Parameters:
filename (str or Path) – Output file path. If the filename does not have a pickle extension (.pickle, .pkl, .pck), “.pickle” is appended automatically.
Notes
Uses dill instead of pickle to handle complex objects like JAX-compiled functions and lambda functions. The file is written with the highest protocol for optimal compression.
See also
loadLoad a fitter object from a pickle file.
- getmodel(what='all', component=None, usebest=True, img=None, doresp=False, doexp=False)[source]¶
Generate best-fit or median model from sampling results.
Computes model realizations using either the weighted median parameters or by marginalizing over all posterior samples.
- Parameters:
what (str or list of str, optional) –
Which model component(s) to return. Options include:
”all” : return all components (raw, smooth, background)
”raw” : raw model before convolution
”smo”/”smooth”/”smoothed”/”conv”/”convolved” : model after PSF convolution
”bkg”/”background” : background component
Default is “all”.
component (None, str, int, list, or Profile, optional) –
Model component(s) to include in the computation. Can be:
None: Include all model components (default)
str: Single component name (e.g., ‘comp_00’)
int: Component index (e.g., 0 for the first component)
list: Multiple components as names, indices, or Profile objects
Profile: Object with id attribute specifying the component
This is useful for generating images of individual model components. Default is None (all components).
usebest (bool, optional) – If True, compute model at weighted median parameters. If False, compute median model by marginalizing over all samples. Default is True.
img (Image, optional) – Image object to use for model computation. If None, uses self.img. Default is None.
doresp (bool, optional) – Whether to apply instrument response. Default is False.
doexp (bool, optional) – Whether to apply exposure map. Default is False.
- Returns:
model_raw (ndarray) – Raw model before convolution. Returned if “all” or “raw” is requested.
model_smooth (ndarray) – Model after convolution and background subtraction. Returned if “all” or a smoothed variant is requested.
model_background (ndarray) – Background component. Returned if “all” or “bkg” is requested.
- Raises:
ValueError – If an unknown model component name is provided in what.
Notes
For optimizer results, only usebest=True mode is supported. The weighted median uses importance weights for nested sampling results. When usebest=False, the method marginalizes over all posterior samples to compute the median model, which can be computationally expensive for large sample sets.
Examples
>>> # Get full model with all components >>> mraw, msmo, mbkg = fit.getmodel() >>> # Get only the first component >>> mraw, msmo, mbkg = fit.getmodel(component=0) >>> # Get specific components by name >>> mraw, msmo, mbkg = fit.getmodel(component=['comp_00', 'comp_02'])
- parameters()[source]¶
Print best-fit parameters with uncertainties.
Computes and prints the weighted median (50th percentile) and asymmetric uncertainties (16th and 84th percentiles) for each fitted parameter, grouped by model component.
The output format is:
comp_00 ------- param : best-fit [+upper/-lower]
where upper = 84th percentile - median and lower = median - 16th percentile.
Notes
Requires that the sampler has been run and samples are available. Uses importance weights for nested sampling results.
- run(method='nautilus', checkpoint=None, resume=True, getzprior=False, **kwargs)[source]¶
Execute Bayesian inference using the specified sampling method.
- Parameters:
method (str, optional) – Sampling method: ‘nautilus’, ‘dynesty’, or ‘numpyro’. Default is ‘nautilus’.
checkpoint (str, optional) – Path to checkpoint file for saving/loading sampler state.
resume (bool, optional) – Whether to resume from checkpoint if available. Default is True.
getzprior (bool, optional) – Whether to compute log-evidence prior normalization. Default is False.
**kwargs (dict) – Additional keyword arguments passed to the sampler.
- savemodel(name, component=None, **kwargs)[source]¶
Save best-fit or median model to a FITS file.
Generates a model image using getmodel() and writes it to a FITS file with the WCS header from the input image preserved.
- Parameters:
name (str or Path) – Output FITS filename. The ‘.fits’ extension is added automatically if not present.
component (None, str, int, list, or Profile, optional) –
Model component(s) to include in the saved image. Can be:
None: Include all model components (default)
str: Single component name (e.g., ‘comp_00’)
int: Component index (e.g., 0 for the first component)
list: Multiple components as names, indices, or Profile objects
Profile: Object with id attribute specifying the component
This is useful for saving images of individual model components. Default is None (all components).
**kwargs (dict) –
Additional keyword arguments passed to getmodel(). Common options include:
- whatstr, optional
Model component to save. Default is ‘convolved’. Options: ‘raw’, ‘convolved’/’smoothed’, ‘background’.
- usebestbool, optional
If True (default), use weighted median parameters. If False, compute median of model realizations.
- dorespbool, optional
Apply response correction. Default is False.
- doexpbool, optional
Apply exposure map. Default is False.
See also
Examples
>>> # Save the PSF-convolved model >>> fit.savemodel('best_fit_model.fits') >>> >>> # Save the raw (unconvolved) model >>> fit.savemodel('raw_model.fits', what='raw') >>> >>> # Save model computed by marginalizing over samples >>> fit.savemodel('median_model.fits', usebest=False) >>> >>> # Save multiple components as a multi-slice FITS >>> fit.savemodel('all_components.fits', what=['raw', 'convolved']) >>> >>> # Save only the first component >>> fit.savemodel('component_0.fits', component=0)
- socca.fitting.load(filename)¶
Load a fitter object from a pickle file.
Deserializes a previously saved fitter object, restoring all samples, weights, sampler objects, and attributes.
- Parameters:
filename (str or Path) – Path to the pickle file created by fitter.dump().
- Returns:
fit – Restored fitter object with all attributes and state.
- Return type:
Notes
Uses dill for deserialization to handle complex objects like JAX-compiled functions. The loaded fitter object is fully functional and can be used for plotting, model generation, and further analysis.
See also
fitter.dumpSave a fitter object to a pickle file.
Examples
>>> fit = load('results.pickle') >>> mraw, msmo, mbkg = fit.getmodel()