SpectrumFit (xsnap.SpectrumFit)#
Methods |
Attributes |
|---|---|
|
|
- class SpectrumFit(abund='aspl', seed=None, mute=False)#
Bases:
objectA class to handle a single XSPEC spectral fit.
- fluxes#
Stored absorbed and unabsorbed flux DataFrames, keyed “absorbed” and “unabsorbed”, with columns are
['data', 'model', 'flux', 'lo_flux_err', 'hi_flux_err', 'phot', 'lo_phot_err', 'hi_phot_err']- Type:
dict[str, pandas.DataFrame] or None
- lumin#
Stored luminosity DataFrame with columns
['data','model','lumin','lo_lumin_err','hi_lumin_err'].- Type:
pandas.DataFrame or None
- params#
Parameter values and uncertainties with columns
['data','model', '<component>_<param>', 'lo_<component>_<param>_err', 'hi_<component>_<param>_err'].- Type:
pandas.DataFrame or None
- counts#
Count-rate DataFrame with columns
['data','model','net_rate','net_err','total_rate','model_rate'].- Type:
pandas.DataFrame or None
- obstime#
Observation time DataFrame with columns
['data','obs_time','obs_time_err']plus['time_since_explosion','time_since_explosion_err']iftExplosiongiven when calculatingobstime.- Type:
pandas.DataFrame or None
- detection#
Associated
SourceDetectionobject.- Type:
SourceDetectionor None
- __iadd__(pha)#
Allow
spec += phasyntax to load a new PHA file.- Parameters:
pha (str) – Path to the PHA file to load. The PHA file must be a grouped PHA file or the background and response file must have the same name as the PHA file for PyXspec to automatically get the background and response file.
- Returns:
- selfSpectrumFit
The same
SpectrumFitinstance, but with the pha file loaded.
- __init__(abund='aspl', seed=None, mute=False)#
Initialize of the
SpectrumFitclass- Parameters:
- Raises:
RuntimeError – If the
xspecexecutable is not found in$PATH.
- clear()#
Clear all loaded data, models, and derived results.
- fit(nIterations=1000, statMethod='cstat')#
Fit the model to the loaded data through XSPEC.
- get_counts()#
Return a DataFrame of count rates for each loaded spectrum.
- Returns:
- Count ratespandas.DataFrame
Count rates wrapped in DataFrame table with columns
['data','model','net_rate','net_err','total_rate','model_rate'].
- Raises:
RuntimeError – If no spectra are loaded.
- get_fluxes(low_energy=0.3, high_energy=10.0, errMCMC=1000, CI=68.0, unabsorbed=True)#
Calculate absorbed (and optionally unabsorbed) fluxes for each spectrum.
- Parameters:
low_energy (
float) – Lower energy bound in keV. Defaults to0.3.high_energy (
float) – Upper energy bound in keV. Defaults to10.0.errMCMC (
float) – Number of MCMC error iterations. Defaults to1000.CI (
float) – Confidence interval percentage. Defaults to68.0.unabsorbed (
bool) – If True, compute unabsorbed flux as well. Defaults toTrue.
- Returns:
- Fluxesdict[str, pandas.DataFrame]
The same absorbed and unabsorbed flux DataFrames as the one in :py:attr`fluxes` with columns
['data', 'model', 'flux', 'lo_flux_err', 'hi_flux_err', 'phot', 'lo_phot_err', 'hi_phot_err'].
- Raises:
RuntimeError – If no spectra loaded or missing absorber for unabsorbed flux.
- get_lumin(fluxes, model_name=None, distance=None, redshift=None, lo_dist_err=None, hi_dist_err=None, lo_z_err=None, hi_z_err=None, H0=70.0, replace=False)#
Compute luminosities from given fluxes.
- Parameters:
fluxes (
DataFrame) – Must contain['data','model','flux','lo_flux_err','hi_flux_err'].model_name (
str) – Override per-row model names. Defaults toNone.distance (
float) – Distance in Mpc. Required if redshift is None. Defaults toNone.redshift (
float) – Redshift. Required if distance isNone. Defaults toNone.lo_dist_err (
float) – Lower uncertainty of distance in Mpc. Defaults toNone.hi_dist_err (
float) – Upper uncertainty of distance in Mpc. Defaults toNone.lo_z_err (
float) – Lower uncertainty of redshift. Defaults toNone.hi_z_err (
float) – Upper uncertainty of redshift. Defaults toNone.H0 (
float) – Hubble constant in km/s/Mpc. Defaults to70.0.replace (
bool) – If True, overwrite existinglumin. Defaults toFalse.
- Returns:
- Luminositypandas.DataFrame
Luminosity wrapped in DataFrame table with columns
['data','model','lumin','lo_lumin_err','hi_lumin_err'].
- Raises:
ValueError – If neither distance nor redshift is provided.
Note
If
distanceis not supplied, it is inferred fromredshiftvia the Doppler relation:\[\begin{split}v = \begin{cases} c\,z, & z \ll 1, \\ c\,\frac{(1 + z)^2 - 1}{(1 + z)^2 + 1}, & \text{otherwise.} \end{cases}\end{split}\]and then:
\[d = \frac{v}{H_0} \ (\mathrm{Mpc}).\]- References:
Hogg, D. W. (1999). Distance measures in cosmology. arXiv:astro-ph/9905116
- get_params(error_args, replace=False)#
Compute best-fit parameters and their uncertainties and store them.
- Parameters:
- Returns:
- Parameterspandas.DataFrame
Best-fit parameters and uncertainties wrapped in a DataFrame table with columns
['data','model', '<component>_<param>', 'lo_<component>_<param>_err', 'hi_<component>_<param>_err'].
- get_time(tExplosion=None)#
Build a DataFrame of observation times and, if provided, time since explosion.
- Parameters:
tExplosion (
float) – Supernova time of explosion in MJD. Defaults toNone.- Returns:
- Observation timespandas.DataFrame
Observation times wrapped in DataFrame table with columns
['data','obs_time','obs_time_err']plus['time_since_explosion','time_since_explosion_err']iftExplosiongiven.
- Raises:
ValueError – If computed
time_since_explosionis negative.
- ignore(ignore=None)#
Ignore specified data channels in XSPEC.
- Parameters:
ignore (str, optional) – same ignore command as in XSPEC. Defaults to
None.
- load_data(pha, newGroup=False, clear=False, bad=True, detection=None)#
Load a grouped PHA file into XSPEC.
- Parameters:
pha (str) – Path to the PHA file. Path to the PHA file to load. The PHA file must be a grouped PHA file or the background and response file must have the same name as the PHA file for PyXspec to automatically get the background and response file.
newGroup (
bool) – Load into a new group ifTrue. Defaults toFalse.clear (
bool) – Clear existing data before loading. Defaults toFalse.bad (
bool) – Ignore bad channels ifTrue. Defaults toTrue.detection (
SourceDetection|None) – Detection object to attach. Defaults toNone.
- Raises:
ValueError – If
phais None.FileNotFoundError – If the PHA file or its directory does not exist.
- set_model(model_string, clear=True, data=0, **kwargs)#
Build and configure the XSPEC model for all data groups.
- Parameters:
model_string (
str) – XSPEC model expression (e.g., “tbabs*pow”).clear (
bool) – IfTrue, clear existing models. Defaults to True.data (
int) – Index of PHA header to use for RA/Dec in computing nH. Defaults to0.**kwargs – Component parameters in
component_Paramformat, e.g.,TBabs_nH="0.059 -1"orpowerlaw_PhoIndex=2.
- Raises:
KeyError – If RA/Dec cannot be found in the PHA header when computing nH.
RuntimeError – If HEADAS or nH tool invocation fails.
ValueError – If a kwarg key is not “Component_Param”.
AttributeError – If the specified component does not exist in the model.
- Example usage
An absorbed power-law model
SpectrumFit.set_model( "tbabs*ztbabs*pow", Tbabs_nH="0.059 -1", # component TBabs, parameter nH zTBabs_nH=0.5, # component zTBabs, parameter nH zTBabs_Redshift=0, # component zTBabs, parameter Redshift powerlaw_PhoIndex=2, # component powerlaw, parameter PhoIndex powerlaw_norm=1 # component powerlaw, parameter norm )
An absorbed Thermal-bremsstrahlung model (with
TBabs.nHcalculated automatically from HEASoft)
SpectrumFit.set_model( "tbabs*ztbabs*pow", data=1, # which pha data to get the RA/Dec from. To get the TBabs nH parameter, default is 0. zTBabs_nH=0.5, # component zTBabs, parameter nH zTBabs_Redshift=0, # component zTBabs, parameter Redshift powerlaw_PhoIndex=2, # component powerlaw, parameter PhoIndex powerlaw_norm=1 # component powerlaw, parameter norm )
- set_plot(args='data', device='/null', xAxis='keV', fileName='plot.png')#
Configure and execute an XSPEC plot.
- Parameters:
args (
str) – Plot command string (e.g.,"data", "ldata"), same command as in XSPEC. Defaults to"data".device (
str) – XSPEC plot device. If"/null", plot via matplotlib. Defaults to"/null".xAxis (
str) – Units for the x-axis. Valid options:"channel", "keV", "MeV", "GeV", "Hz", "angstrom", "cm", "micron", "nm"(case-insensitive). Defaults to"keV".fileName (
str) – Base filename for saving the plot PNG. Defaults to"plot".
- Raises:
Exception – When invalid xAxis or device string is parsed.
- Returns:
- Plottuple(matplotlib.figure.Figure, matplotlib.axes.Axes) or None
If
device == "/null", returns the Figure and Axes so the user can customize further. Otherwise, returns None.
- set_rebin(minSig=None, maxBins=None, groupNum=None, errType=None)#
Set rebinning parameters for XSPEC plots.
- Parameters:
minSig (float, optional) – Minimum significance per bin. Defaults to
None.maxBins (int, optional) – Maximum number of bins. Defaults to
None.groupNum (int, optional) – Specific plot group number to rebin. Defaults to
None.errType (str, optional) – Error type for rebinning. Valid entries are
"quad", "sqrt", "poiss-1","poiss-2", "poiss-3". Defaults toNone.
- show()#
Display the currently loaded data and models in XSPEC format. Wouldn’t work if XSPEC is muted, i.e.
xspec.Xset.chatter = 0.
- simulate(nIterations=1000, statMethod='cstat', low_energy=0.3, high_energy=10.0, unabsorbed=True, plot=True, kwargs_plot='data', device_plot='/svg')#
Simulate and count flux upper-limits using the
FakeItcommand from XSPEC. Will populatefluxesandcounts- Parameters:
nIterations (
int) – Number of fit iterations. Defaults to1000.statMethod (
str) – Type of fit statistic method. Valid names:'chi', 'cstat', 'lstat', 'pgstat', 'pstat', 'whittle'. Defaults to"cstat".low_energy (
float) – Lower energy bound in keV. Defaults to0.3.high_energy (
float) – Upper energy bound in keV. Defaults to10.0.unabsorbed (
bool) – IfTrue, compute unabsorbed flux as well. Defaults toTrue.plot (bool, optional) – If
True, plot the simulated data. Defaults toTrue.kwargs_plot (str, optional) – Plot command string (e.g.,
"data", "ldata"). Defaults to"data".device_plot (str, optional) – XSPEC plot device. If
"/null", plot via matplotlib. Defaults to"/svg".
- Raises:
RuntimeError – When there are no model set, When there are no spectrum loaded, When cannot compute unabsorbed flux due to no tbabs/ztbabs attribute in the model.
- Returns:
- Flux upper-limitsdict[str, pandas.DataFrame]
The same absorbed and unabsorbed flux DataFrames as the one in :py:attr`fluxes` with columns
['data', 'model', 'flux', 'lo_flux_err', 'hi_flux_err', 'phot', 'lo_phot_err', 'hi_phot_err'].