SpectrumFit (xsnap.SpectrumFit)#

class SpectrumFit(abund='aspl', seed=None, mute=False)#

Bases: object

A 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

models#

Model expressions applied.

Type:

list[str]

obstime#

Observation time DataFrame with columns ['data','obs_time','obs_time_err'] plus ['time_since_explosion','time_since_explosion_err'] if tExplosion given when calculating obstime.

Type:

pandas.DataFrame or None

tExplosion#

Supernova time of explosion in MJD.

Type:

float or None

pha#

Loaded PHA file paths.

Type:

list[str]

detection#

Associated SourceDetection object.

Type:

SourceDetection or None

__iadd__(pha)#

Allow spec += pha syntax 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 SpectrumFit instance, but with the pha file loaded.

__init__(abund='aspl', seed=None, mute=False)#

Initialize of the SpectrumFit class

Parameters:
  • abund (str, optional) – Abundance table for XSPEC. Defaults to "aspl".

  • seed (int, optional) – Random seed for reproducibility. Defaults to None.

  • mute (bool, optional) – Mute XSPEC output, i.e. set xspec.Xset.chatter = 0. Defaults to False

Raises:

RuntimeError – If the xspec executable 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.

Parameters:
  • nIterations (int, optional) – Number of fit iterations. Defaults to 1000.

  • statMethod (str, optional) – Type of fit statistic method. Valid names: 'chi', 'cstat', 'lstat', 'pgstat', 'pstat', 'whittle'. Defaults to "cstat".

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, optional) – Lower energy bound in keV. Defaults to 0.3.

  • high_energy (float, optional) – Upper energy bound in keV. Defaults to 10.0.

  • errMCMC (int, optional) – Number of MCMC error iterations. Defaults to 1000.

  • CI (float, optional) – Confidence interval percentage. Defaults to 68.0.

  • unabsorbed (bool, optional) – If True, compute unabsorbed flux as well. Defaults to True.

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 (pandas.DataFrame) – Must contain ['data','model','flux','lo_flux_err','hi_flux_err'].

  • model_name (str, optional) – Override per-row model names. Defaults to None.

  • distance (float, optional) – Distance in Mpc. Required if redshift is None. Defaults to None.

  • redshift (float, optional) – Redshift. Required if distance is None. Defaults to None.

  • lo_dist_err (float, optional) – Lower uncertainty of distance in Mpc. Defaults to None.

  • hi_dist_err (float, optional) – Upper uncertainty of distance in Mpc. Defaults to None.

  • lo_z_err (float, optional) – Lower uncertainty of redshift. Defaults to None.

  • hi_z_err (float, optional) – Upper uncertainty of redshift. Defaults to None.

  • H0 (float, optional) – Hubble constant in km/s/Mpc. Defaults to 70.0.

  • replace (bool, optional) – If True, overwrite existing lumin. Defaults to False.

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 distance is not supplied, it is inferred from redshift via 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:
  • error_args (str or list) – The same arguments passed to xspec.Fit.error(). Details on the arguments can be found here.

  • replace (bool, optional) – If True, overwrite existing params. Defaults to False.

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, optional) – Supernova time of explosion in MJD. Defaults to None.

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'] if tExplosion given.

Raises:

ValueError – If computed time_since_explosion is 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, optional) – Load into a new group if True. Defaults to False.

  • clear (bool, optional) – Clear existing data before loading. Defaults to False.

  • bad (bool, optional) – Ignore bad channels if True. Defaults to True.

  • detection (SourceDetection, optional) – Detection object to attach. Defaults to None.

Raises:
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, optional) – If True, clear existing models. Defaults to True.

  • data (int, optional) – Index of PHA header to use for RA/Dec in computing nH. Defaults to 0.

  • **kwargs – Component parameters in component_Param format, e.g., TBabs_nH="0.059 -1" or powerlaw_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
  1. 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
)
  1. An absorbed Thermal-bremsstrahlung model (with TBabs.nH calculated 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, optional) – Plot command string (e.g., "data", "ldata"), same command as in XSPEC. Defaults to "data".

  • device (str, optional) – XSPEC plot device. If "/null", plot via matplotlib. Defaults to "/null".

  • xAxis (str, optional) – Units for the x-axis. Valid options: "channel", "keV", "MeV", "GeV", "Hz", "angstrom", "cm", "micron", "nm" (case-insensitive). Defaults to "keV".

  • fileName (str, optional) – 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 to None.

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 FakeIt command from XSPEC. Will populate fluxes and counts

Parameters:
  • nIterations (int, optional) – Number of fit iterations. Defaults to 1000.

  • statMethod (str, optional) – Type of fit statistic method. Valid names: 'chi', 'cstat', 'lstat', 'pgstat', 'pstat', 'whittle'. Defaults to "cstat".

  • low_energy (float, optional) – Lower energy bound in keV. Defaults to 0.3.

  • high_energy (float, optional) – Upper energy bound in keV. Defaults to 10.0.

  • unabsorbed (bool, optional) – If True, compute unabsorbed flux as well. Defaults to True.

  • plot (bool, optional) – If True, plot the simulated data. Defaults to True.

  • 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'].