products

products.base module

class xga.products.base.BaseProduct(path, obs_id, instrument, stdout_str, stderr_str, gen_cmd, extra_info=None)[source]

Bases: object

The super class for all SAS generated products in XGA. Stores relevant file path information, parses the std_err output of the generation process, and stores the instrument and ObsID that the product was generated for.

Parameters
  • path (str) – The path to where the product file SHOULD be located.

  • obs_id (str) – The ObsID related to the product being declared.

  • instrument (str) – The instrument related to the product being declared.

  • stdout_str (str) – The stdout from calling the terminal command.

  • stderr_str (str) – The stderr from calling the terminal command.

  • gen_cmd (str) – The command used to generate the product.

  • extra_info (dict) – This allows the XGA processing steps to store some temporary extra information in this object for later use by another processing step. It isn’t intended for use by a user and will only be accessible when defining a BaseProduct.

property usable

Returns whether this product instance should be considered usable for an analysis.

Returns

A boolean flag describing whether this product should be used.

Return type

bool

property path

Property getter for the attribute containing the path to the product.

Returns

The product path.

Return type

str

parse_stderr()[source]

This method parses the stderr associated with the generation of a product into errors confirmed to have come from SAS, and other unidentifiable errors. The SAS errors are returned with the actual error name, the error message, and the SAS routine that caused the error.

Returns

A list of dictionaries containing parsed, confirmed SAS errors, another containing SAS warnings, and another list of unidentifiable errors that occured in the stderr.

Return type

Tuple[List[Dict], List[Dict], List]

property sas_errors

Property getter for the confirmed SAS errors associated with a product.

Returns

The list of confirmed SAS errors.

Return type

List[Dict]

property sas_warnings

Property getter for the confirmed SAS warnings associated with a product.

Returns

The list of confirmed SAS warnings.

Return type

List[Dict]

raise_errors()[source]

Method to raise the errors parsed from std_err string.

property obs_id

Property getter for the ObsID of this image. Admittedly this information is implicit in the location this object is stored in a source object, but I think it worth storing directly as a property as well.

Returns

The XMM ObsID of this image.

Return type

str

property instrument

Property getter for the instrument used to take this image. Admittedly this information is implicit in the location this object is stored in a source object, but I think it worth storing directly as a property as well.

Returns

The XMM instrument used to take this image.

Return type

str

property type

Property getter for the string identifier for the type of product this object is, mostly useful for internal methods of source objects.

Returns

The string identifier for this type of object.

Return type

str

property errors

Property getter for non-SAS errors detected during the generation of a product.

Returns

A list of errors that aren’t related to SAS.

Return type

List[str]

property energy_bounds

Getter method for the energy_bounds property, which returns the rest frame energy band that this product was generated in.

Returns

Tuple containing the lower and upper energy limits as Astropy quantities.

Return type

Tuple[Quantity, Quantity]

property src_name

Method to return the name of the object a product is associated with. The product becomes aware of this once it is added to a source object.

Returns

The name of the source object this product is associated with.

Return type

str

property not_usable_reasons

Whenever the usable flag of a product is set to False (indicating you shouldn’t use the product), a string indicating the reason is added to a list, which this property returns.

Returns

A list of reasons why this product is unusable.

Return type

List

property sas_command

A property that returns the original SAS command used to generate this object.

Returns

String containing the command.

Return type

str

class xga.products.base.BaseAggregateProduct(file_paths, prod_type, obs_id, instrument)[source]

Bases: object

A base class for any XGA products that are an aggregate of an XGA SAS product, for instance this is sub-classed to make the AnnularSpectra class. Users really shouldn’t be instantiating these for themselves.

Parameters
  • file_paths (list) – The file paths of the main files for a given aggregate product.

  • prod_type (str) – The product type of the individual elements.

  • obs_id (str) – The ObsID related to the product.

  • instrument (str) – The instrument related to the product.

property src_name

Method to return the name of the object a product is associated with. The product becomes aware of this once it is added to a source object. This is overridden in the AnnularSpectra class.

Returns

The name of the source object this product is associated with.

Return type

str

property obs_id

Property getter for the ObsID of this image. Admittedly this information is implicit in the location this object is stored in a source object, but I think it worth storing directly as a property as well.

Returns

The XMM ObsID of this image.

Return type

str

property instrument

Property getter for the instrument used to take this image. Admittedly this information is implicit in the location this object is stored in a source object, but I think it worth storing directly as a property as well.

Returns

The XMM instrument used to take this image.

Return type

str

property type

Property getter for the string identifier for the type of product this object is, mostly useful for internal methods of source objects.

Returns

The string identifier for this type of object.

Return type

str

property usable

Property getter for the boolean variable that tells you whether all component products have been found to be usable.

Returns

Boolean variable, are all component products usable?

Return type

bool

property energy_bounds

Getter method for the energy_bounds property, which returns the rest frame energy band that this product was generated in, if relevant.

Returns

Tuple containing the lower and upper energy limits as Astropy quantities.

Return type

Tuple[Quantity, Quantity]

property sas_errors

Equivelant to the BaseProduct sas_errors property, but reports any SAS errors stored in the component products.

Returns

A list of SAS errors related to component products.

Return type

List

property errors

Equivelant to the BaseProduct errors property, but reports any non-SAS errors stored in the component products.

Returns

A list of non-SAS errors related to component products.

Return type

List

property unprocessed_stderr

Equivelant to the BaseProduct sas_errors unprocessed_stderr, but returns a list of all the unprocessed standard error outputs.

Returns

List of stderr outputs.

Return type

List

class xga.products.base.BaseProfile1D(radii, values, centre, source_name, obs_id, inst, radii_err=None, values_err=None, associated_set_id=None, set_storage_key=None, deg_radii=None, x_norm=<Quantity 1.>, y_norm=<Quantity 1.>)[source]

Bases: object

The superclass for all 1D radial profile products, with built in fitting, viewing, and result retrieval functionality. Classes derived from BaseProfile1D can be added together to create Aggregate Profiles.

Parameters
  • radii (Quantity) – The radii at which the y values of this profile have been measured.

  • values (Quantity) – The y values of this profile.

  • centre (Quantity) – The central coordinate the profile was generated from.

  • source_name (str) – The name of the source this profile is associated with.

  • obs_id (str) – The observation which this profile was generated from.

  • inst (str) – The instrument which this profile was generated from.

  • radii_err (Quantity) – Uncertainties on the radii.

  • values_err (Quantity) – Uncertainties on the values.

  • associated_set_id (int) – The set ID of the AnnularSpectra that generated this - if applicable. If this value is supplied a set_storage_key value must also be supplied.

  • set_storage_key (str) – Must be present if associated_set_id is, this is the storage key which the associated AnnularSpectra generates to place itself in XGA’s storage structure.

  • deg_radii (Quantity) – A slightly unfortunate variable that is required only if radii is not in units of degrees, or if no set_storage_key is passed. It should be a quantity containing the radii values converted to degrees, and allows this object to construct a predictable storage key.

  • x_norm (Quantity) – An astropy quantity to use to normalise the x-axis values, this is only used when plotting if the user tells the view method that they wish for the plot to use normalised x-axis data.

  • y_norm (Quantity) – An astropy quantity to use to normalise the y-axis values, this is only used when plotting if the user tells the view method that they wish for the plot to use normalised y-axis data.

emcee_fit(model, num_steps, num_walkers, progress_bar, show_warn, num_samples)[source]

A fitting function to fit an XGA model instance to the data in this profile using the emcee affine-invariant MCMC sampler, this should be called through .fit() for full functionality. An initial run of curve_fit is used to find start parameters for the sampler, though if that fails a maximum likelihood estimate is run, and if that fails the method will revert to using the start parameters set in the model instance.

Parameters
  • model (BaseModel1D) – The model to be fit to the data, you cannot pass a model name for this argument.

  • num_steps (int) – The number of steps each chain should take.

  • num_walkers (int) – The number of walkers to be run for the ensemble sampler.

  • progress_bar (bool) – Whether a progress bar should be displayed.

  • show_warn (bool) – Should warnings be printed out, otherwise they are just stored in the model instance (this also happens if show_warn is True).

  • num_samples (int) – The number of random samples to take from the posterior distributions of the model parameters.

Returns

The model instance, and a boolean flag as to whether this was a successful fit or not.

Return type

Tuple[BaseModel1D, bool]

nlls_fit(model, num_samples, show_warn)[source]

A function to fit an XGA model instance to the data in this profile using the non-linear least squares curve_fit routine from scipy, this should be called through .fit() for full functionality

Parameters
  • model (BaseModel1D) – An instance of the model to be fit to this profile.

  • num_samples (int) – The number of random samples to be drawn and stored in the model parameter distribution property.

  • show_warn (bool) – Should warnings be printed out, otherwise they are just stored in the model instance (this also happens if show_warn is True).

Returns

The model (with best fit parameters stored within it), and a boolean flag as to whether the fit was successful or not.

Return type

Tuple[BaseModel1D, bool]

fit(model, method='mcmc', num_samples=10000, num_steps=30000, num_walkers=20, progress_bar=True, show_warn=True)[source]

Method to fit a model to this profile’s data, then store the resulting model parameter results. Each profile can store one instance of a type of model per fit method. So for instance you could fit both a ‘beta’ and ‘double_beta’ model to a surface brightness profile with curve_fit, and then you could fit ‘double_beta’ again with MCMC.

If any of the parameters of the passed model have a uniform prior associated, and the chosen method is curve_fit, then those priors will be used to place bounds on those parameters.

Parameters
  • model (str/BaseModel1D) – Either an instance of an XGA model to be fit to this profile, or the name of a profile (e.g. ‘beta’, or ‘simple_vikhlinin_dens’).

  • method (str) – The fit method to use, either ‘curve_fit’, ‘mcmc’, or ‘odr’.

  • num_samples (int) – The number of random samples to draw to create the parameter distributions that are saved in the model.

  • num_steps (int) – Only applicable if using MCMC fitting, the number of steps each walker should take.

  • num_walkers (int) – Only applicable if using MCMC fitting, the number of walkers to initialise for the ensemble sampler.

  • progress_bar (bool) – Only applicable if using MCMC fitting, should a progress bar be shown.

  • show_warn (bool) – Should warnings be printed out, otherwise they are just stored in the model instance (this also happens if show_warn is True).

Returns

The fitted model object. The fitted model is also stored within the profile object.

Return type

BaseModel1D

allowed_models(table_format='fancy_grid')[source]

This is a convenience function to tell the user what models can be used to fit a profile of the current type, what parameters are expected, and what the defaults are.

Parameters

table_format (str) – The desired format of the allowed models table. This is passed to the tabulate module (allowed formats can be found here - https://pypi.org/project/tabulate/), and alters the way the printed table looks.

get_model_fit(model, method)[source]

A get method for fitted model objects associated with this profile. Models for which the fit failed will also be returned, but a warning will be shown to inform the user that the fit failed.

Parameters
  • model (str) – The name of the model to retrieve.

  • method (str) – The method which was used to fit the model.

Returns

An instance of an XGA model object that was fitted to this profile and updated with the parameter values.

Return type

BaseModel1D

add_model_fit(model, method)[source]

There are rare circumstances where XGA processes might wish to add a model to a profile from the outside, which is what this method allows you to do.

Parameters
  • model (BaseModel1D) – The XGA model object to add to the profile.

  • method (str) – The method used to fit the model.

get_sampler(model)[source]

A get method meant to retrieve the MCMC ensemble sampler used to fit a particular model (supplied by the user). Checks are applied to the supplied model, to make sure that it is valid for the type of profile, that a good fit has actually been performed, and that the fit was performed with Emcee and not another method.

Parameters

model (str) – The name of the model for which to retrieve the sampler.

Returns

The Emcee sampler used to fit the user supplied model.

Return type

em.EnsembleSampler

get_chains(model, discard=True, flatten=True, thin=1)[source]

Get method for the sampler chains of an MCMC fit to the user supplied model. get_sampler is called to retrieve the sampler object, as well as perform validity checks on the model name.

Parameters
  • model (str) – The name of the model for which to retrieve the chains.

  • discard (bool/int) – Whether steps should be discarded for burn-in. If True then the cut off decided using the auto-correlation time will be used. If an integer is passed then this will be used as the number of steps to discard, and if False then no steps will be discarded.

  • flatten (bool) – Should the chains of the multiple walkers be flattened into one chain per parameter.

  • thin (int) – The thinning that should be applied to the chains. The default is 1, which means no thinning is applied.

Returns

The requested chains.

Return type

np.ndarray

view_chains(model, discard=True, thin=1, figsize=None)[source]

Simple view method to quickly look at the MCMC chains for a given model fit.

Parameters
  • model (str) – The name of the model for which to view the MCMC chains.

  • discard (bool/int) – Whether steps should be discarded for burn-in. If True then the cut off decided using the auto-correlation time will be used. If an integer is passed then this will be used as the number of steps to discard, and if False then no steps will be discarded.

  • thin (int) – The thinning that should be applied to the chains. The default is 1, which means no thinning is applied.

  • figsize (Tuple) – Desired size of the figure, if None will be set automatically.

view_corner(model, figsize=8, 8)[source]

A convenient view method to examine the corner plot of the parameter posterior distributions.

Parameters
  • model (str) – The name of the model for which to view the corner plot.

  • figsize (Tuple) – The desired figure size.

view_getdist_corner(model, settings={}, figsize=10, 10)[source]

A view method to see a corner plot generated with the getdist module, using flattened chains with burn-in removed (whatever the getdist message might say).

Parameters
  • model (str) – The name of the model for which to view the corner plot.

  • settings (dict) – The settings dictionary for a getdist MCSample.

  • figsize (tuple) – A tuple to set the size of the figure.

generate_data_realisations(num_real, truncate_zero=False)[source]

A method to generate random realisations of the data points in this profile, using their y-axis values and uncertainties. This can be useful for error propagation for instance, and does not require a model fit to work. This method assumes that the y-errors are 1-sigma, which isn’t necessarily the case.

Parameters
  • num_real (int) – The number of random realisations to generate.

  • truncate_zero (bool) – Should the data realisations be truncated at zero, default is False. This could be used for generating realisations of profiles where negative values are not physical.

Returns

An N x R astropy quantity, where N is the number of realisations and R is the number of radii at which there are data points in this profile.

Return type

Quantity

get_view(fig, main_ax, xscale='log', yscale='log', xlim=None, ylim=None, models=True, back_sub=True, just_models=False, custom_title=None, draw_rads={}, x_norm=False, y_norm=False, x_label=None, y_label=None, data_colour='black', model_colour='seagreen', show_legend=True, show_residual_ax=True, draw_vals={}, auto_legend=True, joined_points=False, axis_formatters=None)[source]

A get method for an axes (or multiple axes) showing this profile and model fits. The idea of this get method is that, whilst it is used by the view() method, it can also be called by external methods that wish to use the profile plot in concert with other views.

param Figure fig

The figure which has been set up for this profile plot.

param Axes main_ax

The matplotlib axes on which to show the image.

param str xscale

The scaling to be applied to the x axis, default is log.

param str yscale

The scaling to be applied to the y axis, default is log.

param Tuple xlim

The limits to be applied to the x axis, upper and lower, default is to let matplotlib decide by itself.

param Tuple ylim

The limits to be applied to the y axis, upper and lower, default is to let matplotlib decide by itself.

param str models

Should the fitted models to this profile be plotted, default is True

param bool back_sub

Should the plotted data be background subtracted, default is True.

param bool just_models

Should ONLY the fitted models be plotted? Default is False

param str custom_title

A plot title to replace the automatically generated title, default is None.

param dict draw_rads

A dictionary of extra radii (as astropy Quantities) to draw onto the plot, where the dictionary key they are stored under is what they will be labelled. e.g. {‘r500’: Quantity(), ‘r200’: Quantity()}

param bool x_norm

Controls whether the x-axis of the profile is normalised by another value, the default is False, in which case no normalisation is applied. If it is set to True then it will attempt to use the internal normalisation value (which can be set with the x_norm property), and if a quantity is passed it will attempt to normalise using that.

param bool y_norm

Controls whether the y-axis of the profile is normalised by another value, the default is False, in which case no normalisation is applied. If it is set to True then it will attempt to use the internal normalisation value (which can be set with the y_norm property), and if a quantity is passed it will attempt to normalise using that.

param str x_label

Custom label for the x-axis (excluding units, which will be added automatically).

param str y_label

Custom label for the y-axis (excluding units, which will be added automatically).

param str data_colour

Used to set the colour of the data points.

param str model_colour

Used to set the colour of a model fit.

param bool show_legend

Whether the legend should be displayed or not. Default is True.

param bool show_residual_ax

Controls whether a lower axis showing the residuals between data and model (if a model is fitted and being shown) is displayed. Default is True.

param dict draw_vals

A dictionary of extra y-values (as astropy quantities) to draw onto the plot, where the dictionary key they are stored under is what they will be labelled (keys can be LaTeX formatted); e.g. {r’$T_{

m{X,500}}$’: Quantity(6, ‘keV’)}. Quantities with uncertainties may also be

passed, and the error regions will be shaded; e.g. {r’$T_{

m{X,500}}$’: Quantity([6, 0.2, 0.3], ‘keV’)},

where 0.2 is the negative error, and 0.3 is the positive error.

param bool auto_legend

If True, and show_legend has also been set to True, then the ‘best’ legend location will be defined by matplotlib, otherwise, if False, the legend will be added to the right hand side of the plot outside the main axes.

param bool joined_points

If True, the data in the profile will be plotted as a line, rather than points, as will any uncertainty regions.

param dict axis_formatters

A dictionary of formatters that can be applied to the profile plot. The keys can have the following values; ‘xmajor’, ‘xminor’, ‘ymajor’, and ‘yminor’. The values associated with the keys should be instantiated matplotlib formatters.

view(figsize=10, 7, xscale='log', yscale='log', xlim=None, ylim=None, models=True, back_sub=True, just_models=False, custom_title=None, draw_rads={}, x_norm=False, y_norm=False, x_label=None, y_label=None, data_colour='black', model_colour='seagreen', show_legend=True, show_residual_ax=True, draw_vals={}, auto_legend=True, joined_points=False, axis_formatters=None)[source]

A method that allows us to view the current profile, as well as any models that have been fitted to it, and their residuals. The models are plotted by generating random model realisations from the parameter distributions, then plotting the median values, with 1sigma confidence limits.

param Tuple figsize

The desired size of the figure, the default is (10, 7)

param str xscale

The scaling to be applied to the x axis, default is log.

param str yscale

The scaling to be applied to the y axis, default is log.

param Tuple xlim

The limits to be applied to the x axis, upper and lower, default is to let matplotlib decide by itself.

param Tuple ylim

The limits to be applied to the y axis, upper and lower, default is to let matplotlib decide by itself.

param str models

Should the fitted models to this profile be plotted, default is True

param bool back_sub

Should the plotted data be background subtracted, default is True.

param bool just_models

Should ONLY the fitted models be plotted? Default is False

param str custom_title

A plot title to replace the automatically generated title, default is None.

param dict draw_rads

A dictionary of extra radii (as astropy Quantities) to draw onto the plot, where the dictionary key they are stored under is what they will be labelled. e.g. ({‘r500’: Quantity(), ‘r200’: Quantity()}

param bool x_norm

Controls whether the x-axis of the profile is normalised by another value, the default is False, in which case no normalisation is applied. If it is set to True then it will attempt to use the internal normalisation value (which can be set with the x_norm property), and if a quantity is passed it will attempt to normalise using that.

param bool y_norm

Controls whether the y-axis of the profile is normalised by another value, the default is False, in which case no normalisation is applied. If it is set to True then it will attempt to use the internal normalisation value (which can be set with the y_norm property), and if a quantity is passed it will attempt to normalise using that.

param str x_label

Custom label for the x-axis (excluding units, which will be added automatically).

param str y_label

Custom label for the y-axis (excluding units, which will be added automatically).

param str data_colour

Used to set the colour of the data points.

param str model_colour

Used to set the colour of a model fit.

param bool show_legend

Whether the legend should be displayed or not. Default is True.

param bool show_residual_ax

Controls whether a lower axis showing the residuals between data and model (if a model is fitted and being shown) is displayed. Default is True.

param dict draw_vals

A dictionary of extra y-values (as astropy quantities) to draw onto the plot, where the dictionary key they are stored under is what they will be labelled (keys can be LaTeX formatted); e.g. {r’$T_{

m{X,500}}$’: Quantity(6, ‘keV’)}. Quantities with uncertainties may also be

passed, and the error regions will be shaded; e.g. {r’$T_{

m{X,500}}$’: Quantity([6, 0.2, 0.3], ‘keV’)},

where 0.2 is the negative error, and 0.3 is the positive error.

param bool auto_legend

If True, and show_legend has also been set to True, then the ‘best’ legend location will be defined by matplotlib, otherwise, if False, the legend will be added to the right hand side of the plot outside the main axes.

param bool joined_points

If True, the data in the profile will be plotted as a line, rather than points, as will any uncertainty regions.

param dict axis_formatters

A dictionary of formatters that can be applied to the profile plot. The keys can have the following values; ‘xmajor’, ‘xminor’, ‘ymajor’, and ‘yminor’. The values associated with the keys should be instantiated matplotlib formatters.

save_view(save_path, figsize=10, 7, xscale='log', yscale='log', xlim=None, ylim=None, models=True, back_sub=True, just_models=False, custom_title=None, draw_rads={}, x_norm=False, y_norm=False, x_label=None, y_label=None, data_colour='black', model_colour='seagreen', show_legend=True, show_residual_ax=True, draw_vals={}, auto_legend=True, joined_points=False, axis_formatters=None)[source]

A method that allows us to save a view of the current profile, as well as any models that have been fitted to it, and their residuals. The models are plotted by generating random model realisations from the parameter distributions, then plotting the median values, with 1sigma confidence limits.

This method will not display a figure, just save it at the supplied save_path.

param str save_path

The path (including file name) where you wish to save the profile view.

param Tuple figsize

The desired size of the figure, the default is (10, 7)

param str xscale

The scaling to be applied to the x axis, default is log.

param str yscale

The scaling to be applied to the y axis, default is log.

param Tuple xlim

The limits to be applied to the x axis, upper and lower, default is to let matplotlib decide by itself.

param Tuple ylim

The limits to be applied to the y axis, upper and lower, default is to let matplotlib decide by itself.

param str models

Should the fitted models to this profile be plotted, default is True

param bool back_sub

Should the plotted data be background subtracted, default is True.

param bool just_models

Should ONLY the fitted models be plotted? Default is False

param str custom_title

A plot title to replace the automatically generated title, default is None.

param dict draw_rads

A dictionary of extra radii (as astropy Quantities) to draw onto the plot, where the dictionary key they are stored under is what they will be labelled. e.g. ({‘r500’: Quantity(), ‘r200’: Quantity()}

param bool x_norm

Controls whether the x-axis of the profile is normalised by another value, the default is False, in which case no normalisation is applied. If it is set to True then it will attempt to use the internal normalisation value (which can be set with the x_norm property), and if a quantity is passed it will attempt to normalise using that.

param bool y_norm

Controls whether the y-axis of the profile is normalised by another value, the default is False, in which case no normalisation is applied. If it is set to True then it will attempt to use the internal normalisation value (which can be set with the y_norm property), and if a quantity is passed it will attempt to normalise using that.

param str x_label

Custom label for the x-axis (excluding units, which will be added automatically).

param str y_label

Custom label for the y-axis (excluding units, which will be added automatically).

param str data_colour

Used to set the colour of the data points.

param str model_colour

Used to set the colour of a model fit.

param bool show_legend

Whether the legend should be displayed or not. Default is True.

param bool show_residual_ax

Controls whether a lower axis showing the residuals between data and model (if a model is fitted and being shown) is displayed. Default is True.

param dict draw_vals

A dictionary of extra y-values (as astropy quantities) to draw onto the plot, where the dictionary key they are stored under is what they will be labelled (keys can be LaTeX formatted); e.g. {r’$T_{

m{X,500}}$’: Quantity(6, ‘keV’)}. Quantities with uncertainties may also be

passed, and the error regions will be shaded; e.g. {r’$T_{

m{X,500}}$’: Quantity([6, 0.2, 0.3], ‘keV’)},

where 0.2 is the negative error, and 0.3 is the positive error.

param bool auto_legend

If True, and show_legend has also been set to True, then the ‘best’ legend location will be defined by matplotlib, otherwise, if False, the legend will be added to the right hand side of the plot outside the main axes.

param bool joined_points

If True, the data in the profile will be plotted as a line, rather than points, as will any uncertainty regions.

param dict axis_formatters

A dictionary of formatters that can be applied to the profile plot. The keys can have the following values; ‘xmajor’, ‘xminor’, ‘ymajor’, and ‘yminor’. The values associated with the keys should be instantiated matplotlib formatters.

save(save_path=None)[source]

This method pickles and saves the profile object. This will be called automatically when the profile is initialised, and when changes are made to the profile (such as when a model is fitted). The save file is a pickled version of this object.

Parameters

save_path (str) – The path where this profile should be saved. By default this is None, which means this method will use the save_path attribute of the profile.

property save_path

Property getter that assembles the default XGA save path of this profile. The file name contains limited information; the type of profile, the source name, and a random integer.

Returns

The default XGA save path for this profile.

Return type

str

property good_model_fits

A list of the names of models that have been successfully fitted to the profile.

Returns

A list of model names.

Return type

Dict

property radii

Getter for the radii passed in at init. These radii correspond to radii where the values were measured.

Returns

Astropy quantity array of radii.

Return type

Quantity

property radii_err

Getter for the uncertainties on the profile radii.

Returns

Astropy quantity array of radii uncertainties, or a None value if no radii_err where passed.

Return type

Quantity

property fit_radii

This property gives the user a sanitised set of radii that is safe to use for fitting to XGA models, by which I mean if the first element is zero, then it will be replaced by a value slightly above zero that won’t cause divide by zeros in the fit process.

If the radius units are convertible to kpc then the zero value will be set to the equivalent of 1kpc, if they have pixel units then it will be set to one pixel, and if they are equivalent to degrees then it will be set to 1e−5 degrees. The value for degrees is loosely based on the value of 1kpc at a redshift of 1.

Returns

A Quantity with a set of radii that are ‘safe’ for fitting

Return type

Quantity

property radii_unit

Getter for the unit of the radii passed by the user at init.

Returns

An astropy unit object.

Return type

Unit

property annulus_bounds

Getter for the original boundary radii of the annuli this profile may have been generated from. Only available if radii errors were passed on init.

Returns

An astropy quantity containing the boundary radii of the annuli, or None if not available.

Return type

Quantity

property values

Getter for the values passed by user at init.

Returns

Astropy quantity array of values.

Return type

Quantity

property values_err

Getter for uncertainties on the profile values.

Returns

Astropy quantity array of values uncertainties, or a None value if no values_err where passed.

Return type

Quantity

property values_unit

Getter for the unit of the values passed by the user at init.

Returns

An astropy unit object.

Return type

Unit

property background

Getter for the background associated with the profile values. If no background is set this will be zero.

Returns

Astropy scalar quantity.

Return type

Quantity

property centre

Property that returns the central coordinate that the profile was generated from.

Returns

An astropy quantity of the central coordinate

Return type

Quantity

property type

Getter for a string representing the type of profile stored in this object.

Returns

String description of profile.

Return type

str

property src_name

Getter for the name attribute of this profile, what source object it was derived from.

Returns

Return type

object

property obs_id

Property getter for the ObsID this profile was made from. Admittedly this information is implicit in the location this object is stored in a source object, but I think it worth storing directly as a property as well.

Returns

XMM ObsID string.

Return type

str

property instrument

Property getter for the instrument this profile was made from. Admittedly this information is implicit in the location this object is stored in a source object, but I think it worth storing directly as a property as well.

directly as a property as well. :return: XMM instrument name string. :rtype: str

property energy_bounds

Getter method for the energy_bounds property, which returns the rest frame energy band that this profile was generated from

Returns

Tuple containing the lower and upper energy limits as Astropy quantities.

Return type

Union[Tuple[Quantity, Quantity], Tuple[None, None]]

property set_ident

If this profile was generated from an annular spectrum, this will contain the set_id of that annular spectrum.

Returns

The integer set ID of the annular spectrum that generated this, or None if it wasn’t generated from an AnnularSpectra object.

Return type

int

property y_axis_label

Property to return the name used for labelling the y-axis in any plot generated by a profile object.

Returns

The y_axis label.

Return type

str

property associated_set_storage_key

This property provides the storage key of the associated AnnularSpectra object, if the profile was generated from an AnnularSpectra. If it was not then a None value is returned.

Returns

The storage key of the associated AnnularSpectra, or None if not applicable.

Return type

str

property deg_radii

The radii in degrees if available.

Returns

An astropy quantity containing the radii in degrees, or None.

Return type

Quantity

property storage_key

This property returns the storage key which this object assembles to place the profile in an XGA source’s storage structure. If the profile was generated from an AnnularSpectra then the key is based on the properties of the AnnularSpectra, otherwise it is based upon the properties of the specific profile.

Returns

String storage key.

Return type

str

property usable

Whether the profile object can be considered usable or not, reasons for this decision will vary for different profile types.

Returns

A boolean variable.

Return type

bool

property x_norm

The normalisation value for x-axis data passed on the definition of the this profile object.

Returns

An astropy quantity containing the normalisation value.

Return type

Quantity

property y_norm

The normalisation value for y-axis data passed on the definition of the this profile object.

Returns

An astropy quantity containing the normalisation value.

Return type

Quantity

property fit_options

Returns the supported fit options for XGA profiles.

Returns

List of supported fit options.

Return type

List[str]

property nice_fit_names

Returns nicer looking names for the supported fit options of XGA profiles.

Returns

List of nice fit options.

Return type

List[str]

property outer_radius

Property that returns the outer radius used for the generation of this profile.

Returns

The outer radius used in the generation of the profile.

Return type

Quantity

class xga.products.base.BaseAggregateProfile1D(profiles)[source]

Bases: object

Quite a simple class that is generated when multiple 1D radial profile objects are added together. The purpose of instances of this class is simply to make it easy to view 1D radial profiles on the same axes.

Parameters

profiles (list) – A list of profile objects (of the same type) to include in this aggregate profile.

property radii_unit

Getter for the unit of the radii passed by the user at init.

Returns

An astropy unit object.

Return type

Unit

property values_unit

Getter for the unit of the values passed by the user at init.

Returns

An astropy unit object.

Return type

Unit

property type

Getter for a string representing the type of profile stored in this object.

Returns

String description of profile.

Return type

str

property profiles

This property is for the constituent profiles that makes up this aggregate profile.

Returns

A list of the profiles that make up this object.

Return type

List[BaseProfile1D]

property energy_bounds

Getter method for the energy_bounds property, which returns the rest frame energy band that the component profiles of this object were generated from.

Returns

Tuple containing the lower and upper energy limits as Astropy quantities.

Return type

Union[Tuple[Quantity, Quantity], Tuple[None, None]]

property x_norms

The collated x normalisation values for the constituent profiles of this aggregate profile.

Returns

A list of astropy quantities which represent the x-normalisations of the different profiles.

Return type

List[Quantity]

property y_norms

The collated y normalisation values for the constituent profiles of this aggregate profile.

Returns

A list of astropy quantities which represent the y-normalisations of the different profiles.

Return type

List[Quantity]

view(figsize=10, 7, xscale='log', yscale='log', xlim=None, ylim=None, model=None, back_sub=True, show_legend=True, just_model=False, custom_title=None, draw_rads={}, x_norm=False, y_norm=False, x_label=None, y_label=None, save_path=None, draw_vals={}, auto_legend=True, axis_formatters=None, show_residual_ax=True, joined_points=False)[source]

A method that allows us to see all the profiles that make up this aggregate profile, plotted on the same figure.

param Tuple figsize

The desired size of the figure, the default is (10, 7)

param str xscale

The scaling to be applied to the x axis, default is log.

param str yscale

The scaling to be applied to the y axis, default is log.

param Tuple xlim

The limits to be applied to the x axis, upper and lower, default is to let matplotlib decide by itself.

param Tuple ylim

The limits to be applied to the y axis, upper and lower, default is to let matplotlib decide by itself.

param str model

The name of the model fit to display, default is None. If the model hasn’t been fitted, or it failed, then it won’t be displayed.

param bool back_sub

Should the plotted data be background subtracted, default is True.

param bool show_legend

Should a legend with source names be added to the figure, default is True.

param bool just_model

Should only the models, not the data, be plotted. Default is False.

param str custom_title

A plot title to replace the automatically generated title, default is None.

param dict draw_rads

A dictionary of extra radii (as astropy Quantities) to draw onto the plot, where the dictionary key they are stored under is what they will be labelled. e.g. ({‘r500’: Quantity(), ‘r200’: Quantity()}. If normalise_x option is also used, and the x-norm values are not the same for each profile, then draw_rads will be disabled.

param bool x_norm

Should the x-axis values be normalised with the x_norm value passed on the definition of the constituent profile objects.

param bool y_norm

Should the y-axis values be normalised with the y_norm value passed on the definition of the constituent profile objects.

param str x_label

Custom label for the x-axis (excluding units, which will be added automatically).

param str y_label

Custom label for the y-axis (excluding units, which will be added automatically).

param str save_path

The path where the figure produced by this method should be saved. Default is None, in which case the figure will not be saved.

param dict draw_vals

A dictionary of extra y-values (as astropy quantities) to draw onto the plot, where the dictionary key they are stored under is what they will be labelled (keys can be LaTeX formatted); e.g. {r’$T_{

m{X,500}}$’: Quantity(6, ‘keV’)}. Quantities with uncertainties may also be

passed, and the error regions will be shaded; e.g. {r’$T_{

m{X,500}}$’:

Quantity([6, 0.2, 0.3], ‘keV’)}, where 0.2 is the negative error, and 0.3 is the positive error. Finally, plotting colour may be specified by setting the value to a list, with the first entry being the quantity, and the second being a colour; e.g. {r’$T_{

m{X,500}}$’: [Quantity([6, 0.2, 0.3], ‘keV’), ‘tab:blue’]}.
param bool auto_legend

If True, and show_legend has also been set to True, then the ‘best’ legend location will be defined by matplotlib, otherwise, if False, the legend will be added to the right hand side of the plot outside the main axes.

param dict axis_formatters

A dictionary of formatters that can be applied to the profile plot. The keys can have the following values; ‘xmajor’, ‘xminor’, ‘ymajor’, and ‘yminor’. The values associated with the keys should be instantiated matplotlib formatters.

param bool show_residual_ax

Controls whether a lower axis showing the residuals between data and model (if a model is fitted and being shown) is displayed. Default is True.

param bool joined_points

If True, the data in the profiles will be plotted as a line, rather than points, as will any uncertainty regions.

products.misc module

class xga.products.misc.EventList(path, obs_id, instrument, stdout_str, stderr_str, gen_cmd)[source]

Bases: xga.products.base.BaseProduct

A product class for event lists, largely just used as a means to store information about the event list.

Parameters
  • path (str) – The path to where the event list file SHOULD be located.

  • obs_id (str) – The ObsID related to the event list being declared.

  • instrument (str) – The instrument related to the event list being declared.

  • stdout_str (str) – The stdout from calling the terminal command.

  • stderr_str (str) – The stderr from calling the terminal command.

  • gen_cmd (str) – The command used to generate the event list.

products.phot module

class xga.products.phot.Image(path, obs_id, instrument, stdout_str, stderr_str, gen_cmd, lo_en, hi_en, regs='', matched_regs=None, smoothed=False, smoothed_info=None, obs_inst_combs=None)[source]

Bases: xga.products.base.BaseProduct

This class stores image data from X-ray observations. It also allows easy, direct, access to that data, and implements many helpful methods with extra functionality (including coordinate transforms, peak finders, and a powerful view method).

Parameters
  • path (str) – The path to where the product file SHOULD be located.

  • obs_id (str) – The ObsID related to the Image being declared.

  • instrument (str) – The instrument related to the Image being declared.

  • stdout_str (str) – The stdout from calling the terminal command.

  • stderr_str (str) – The stderr from calling the terminal command.

  • gen_cmd (str) – The command used to generate the product.

  • lo_en (Quantity) – The lower energy bound used to generate this product.

  • hi_en (Quantity) – The upper energy bound used to generate this product.

  • regs (str/List[SkyRegion/PixelRegion]/dict) – A region list file path, a list of region objects, or a dictionary of region lists with ObsIDs as dictionary keys.

  • matched_regs (dict/SkyRegion/PixelRegion) – Similar to the regs argument, but in this case for a region that has been designated as ‘matched’, i.e. is the subject of a current analysis. This should either be supplied as a single region object, or as a dictionary of region objects with ObsIDs as keys, or None values if there is no match. Such a dictionary can be retrieved from a source using the ‘matched_regions’ property. Default is None.

  • smoothed (bool) – Has this image been smoothed, default is False. This information can also be set after the instantiation of an image.

  • smoothed_info (dict/Kernel) – Information on how the image was smoothed, given either by the Astropy kernel used or a dictionary of information (required structure detailed in parse_smoothing). Default is None

  • obs_inst_combs (List[List]) – Supply a list of lists of ObsID-Instrument combinations if the image is combined and wasn’t made by emosaic (e.g. [[‘0404910601’, ‘pn’], [‘0404910601’, ‘mos1’], [‘0404910601’, ‘mos2’], [‘0201901401’, ‘pn’], [‘0201901401’, ‘mos1’], [‘0201901401’, ‘mos2’]].

static parse_smoothing(info)[source]

Parses smoothing information that has been passed into the Image object, either on init or afterwards. If an Astropy kernel is provided then the name, and kernel parameter, will be extracted. If a dictionary is provided then it must have a) ‘method’ key with the name of the smoothing method, and b) a ‘pars’ key with another dictionary of all the parameters involved in smoothing; e.g. {‘method’: ‘Gaussian2DKernel’, ‘pars’: {‘amplitude’: 0.63, ‘x_mean’: 0.0, ‘y_mean’: 0.0, ‘x_stddev’: 0.5,

‘y_stddev’: 0.5, ‘theta’: 0.0}}

Parameters

info (dict/Kernel) – The information dictionary or astropy kernel used for the smoothing.

Returns

The name of the kernel/method and parameter information

Return type

Tuple[str, dict]

property smoothing_info

If the image has been smoothed, then this property getter will return information on the smoothing done.

Returns

A dictionary of information on the smoothing applied (if any). Default is None if no smoothing applied.

Return type

dict

property smoothed_method

The name of the smoothing method (or kernel) that has been applied.

Returns

Name of method/kernel, default is None if no smoothing has been applied.

Return type

str

property smoothed

Property describing whether an image product has been smoothed or not.

Returns

Has the product been smoothed.

Return type

bool

property storage_key

The key under which this object should be stored in a source’s product structure. Contains information about various aspects of the Image/RateMap/ExpMap.

Returns

The storage key.

Return type

str

property obs_inst_combos

This property getter will provide ObsID-Instrument information on the constituent images that make up this total image (if it is combined), otherwise it will just provide the single ObsID-Instrument combo.

Returns

A list of lists of ObsID-Instrument combinations, or a list containing one ObsID and one instrument.

Return type

list

property obs_ids

Property getter for the ObsIDs that are involved in this image, if combined. Otherwise will return a list with one element, the single relevant ObsID.

Returns

List of ObsIDs involved in this image.

Return type

list

property instruments

Equivelant to the BaseSource instruments property, this will return a dictionary of ObsIDs with lists of instruments that are associated with them in a combined image. If the image is not combined then an equivelant dictionary with one key (the ObsID), with the associated value being a list with one entry (the instrument).

Returns

A dictionary of ObsIDs and their associated instruments

Return type

dict

property inventory_entry

This allows an Image product to generate its own entry for the XGA file generation inventory.

Returns

The new line entry for the inventory.

Return type

pd.Series

property regions

Property getter for regions associated with this image.

Returns

Returns a dictionary of regions, if they have been associated with this object.

Return type

Dict[PixelRegion]

property matched_regions

Property getter for any regions which have been designated a ‘match’ in the current analysis, if they have been set.

Returns

Returns a dictionary of matched regions, if they have been associated with this object.

Return type

Dict[PixelRegion]

property shape

Property getter for the resolution of the image. Standard XGA settings will make this 512x512.

Returns

The shape of the numpy array describing the image.

Return type

Tuple[int, int]

property data

Property getter for the actual image data, in the form of a numpy array. Doesn’t include any of the other stuff you get in a fits image, thats found in the hdulist property.

Returns

A numpy array of shape self.shape containing the image data.

Return type

np.ndarray

property data_unit

The unit of the data associated with this photometric product.

Returns

An astropy unit object describing the units of this objects’ data.

Return type

Unit

property radec_wcs

Property getter for the WCS that converts back and forth between pixel values and RA-DEC coordinates. This one is the only WCS guaranteed to not-None.

Returns

The WCS object for RA and DEC.

Return type

wcs.WCS

property skyxy_wcs

Property getter for the WCS that converts back and forth between pixel values and XMM XY Sky coordinates.

Returns

The WCS object for XMM X and Y sky coordinates.

Return type

wcs.WCS

property detxy_wcs

Property getter for the WCS that converts back and forth between pixel values and XMM DETXY detector coordinates.

Returns

The WCS object for XMM DETX and DETY detector coordinates.

Return type

wcs.WCS

property header

Property getter allowing access to the astropy fits header object created when the image was read in.

Returns

The header of the primary data table of the image that was read in.

Return type

FITSHDR

coord_conv(coords, output_unit)[source]

This will use the loaded WCSes, and astropy coordinates (including custom ones defined for this module), to perform common coordinate conversions for this product object.

Parameters
  • coords (Quantity) – The input coordinates quantity to convert, in units of either deg, pix, xmm_sky, or xmm_det (xmm_sky and xmm_det are defined for this module).

  • output_unit (Unit/str) – The astropy unit to convert to, can be either deg, pix, xmm_sky, or xmm_det (xmm_sky and xmm_det are defined for this module).

Returns

The converted coordinates.

Return type

Quantity

property psf_corrected

Tells the user (and XGA), whether an Image based object has been PSF corrected or not.

Returns

Boolean flag, True means this object has been PSF corrected, False means it hasn’t

Return type

bool

property psf_algorithm

If this object has been PSF corrected, this property gives the name of the algorithm used.

Returns

The name of the algorithm used to correct for PSF effects, or None if the object hasn’t been PSF corrected.

Return type

Union[str, None]

property psf_bins

If this object has been PSF corrected, this property gives the number of bins that the X and Y axes were divided into to generate the PSFGrid.

Returns

The number of bins in X and Y for which PSFs were generated, or None if the object hasn’t been PSF corrected.

Return type

Union[int, None]

property psf_iterations

If this object has been PSF corrected, this property gives the number of iterations that the algorithm went through to create this image.

Returns

The number of iterations the PSF correction algorithm went through, or None if the object hasn’t been PSF corrected.

Return type

Union[int, None]

property psf_model

If this object has been PSF corrected, this property gives the name of the PSF model used.

Returns

The name of the PSF model used to correct for PSF effects, or None if the object hasn’t been PSF corrected.

Return type

Union[str, None]

get_count(at_coord)[source]

A simple method that converts the given coordinates to pixels, then finds the number of counts at those coordinates.

Parameters

at_coord (Quantity) – Coordinate at which to find the number of counts.

Returns

The counts at the supplied coordinates.

Return type

Quantity

simple_peak(mask, out_unit=Unit('deg'))[source]

Simplest possible way to find the position of the peak of X-ray emission in an Image. This method takes a mask in the form of a numpy array, which allows the user to mask out parts of the ratemap that shouldn’t be searched (outside of a certain region, or within point sources for instance).

Results from this can be less valid than the RateMap implementation (especially if the object you care about is off-axis), as that takes into account vignetting corrected exposure times.

Parameters
  • mask (np.ndarray) – A numpy array used to weight the data. It should be 0 for pixels that aren’t to be searched, and 1 for those that are.

  • out_unit (UnitBase/str) – The desired output unit of the peak coordinates, the default is degrees.

Returns

An astropy quantity containing the coordinate of the X-ray peak of this ratemap (given the user’s mask), in units of out_unit, as specified by the user. A null value is also returned in place of the boolean flag describing whether the coordinates are near an edge or not that RateMap returns.

Return type

Tuple[Quantity, None]

get_view(ax, cross_hair=None, mask=None, chosen_points=None, other_points=None, zoom_in=False, manual_zoom_xlims=None, manual_zoom_ylims=None, radial_bins_pix=array([], dtype=float64), back_bin_pix=None, stretch=<astropy.visualization.stretch.LogStretch object>, mask_edges=True, view_regions=False, ch_thickness=0.8)[source]

The method that creates and populates the view axes, separate from actual view so outside methods can add a view to other matplotlib axes.

Parameters
  • ax (Axes) – The matplotlib axes on which to show the image.

  • cross_hair (Quantity) – An optional parameter that can be used to plot a cross hair at the coordinates. Up to two cross-hairs can be plotted, as any more can be visually confusing. If passing two, each row of a quantity is considered to be a separate coordinate pair.

  • mask (np.ndarray) – Allows the user to pass a numpy mask and view the masked data if they so choose.

  • chosen_points (np.ndarray) – A numpy array of a chosen point cluster from a hierarchical peak finder.

  • other_points (list) – A list of numpy arrays of point clusters that weren’t chosen by the hierarchical peak finder.

  • zoom_in (bool) – Sets whether the figure limits should be set automatically so that borders with no data are reduced.

  • manual_zoom_xlims (tuple) – If set, this will override the automatic zoom in and manually set a part of the x-axis to limit the image to, default is None. Pass a tuple with two elements, first being the lower limit, second the upper limit. Variable zoom_in must still be true for these limits to be applied.

  • manual_zoom_ylims (tuple) – If set, this will override the automatic zoom in and manually set a part of the y-axis to limit the image to, default is None. Pass a tuple with two elements, first being the lower limit, second the upper limit. Variable zoom_in must still be true for these limits to be applied.

  • radial_bins_pix (np.ndarray) – Radii (in units of pixels) of annuli to plot on top of the image, will only be triggered if a cross_hair coordinate is also specified, as this acts as the central coordinate of the annuli. If two cross-hair coordinates are specified, the first will be used as the centre.

  • back_bin_pix (np.ndarray) – The inner and outer radii (in pixel units) of the annulus used to measure the background value for a given profile, will only be triggered if a cross_hair coordinate is also specified, as this acts as the central coordinate of the annuli. If two cross-hair coordinates are specified, the first will be used as the centre.

  • stretch (BaseStretch) – The astropy scaling to use for the image data, default is log.

  • mask_edges (bool) – If viewing a RateMap, this variable will control whether the chip edges are masked to remove artificially bright pixels, default is True.

  • view_regions (bool) – If regions have been associated with this object (either on init or using the ‘regions’ property setter, should they be displayed. Default is False.

  • ch_thickness (float) – The desired linewidth of the crosshair(s), can be useful to increase this in certain circumstances. Default is 0.8.

Returns

A populated figure displaying the view of the data.

Return type

Axes

view(cross_hair=None, mask=None, chosen_points=None, other_points=None, figsize=(10, 8), zoom_in=False, manual_zoom_xlims=None, manual_zoom_ylims=None, radial_bins_pix=array([], dtype=float64), back_bin_pix=None, stretch=<astropy.visualization.stretch.LogStretch object>, mask_edges=True, view_regions=False, ch_thickness=0.8)[source]

Powerful method to view this Image/RateMap/Expmap, with different options that can be used for eyeballing and producing figures for publication.

Parameters
  • cross_hair (Quantity) – An optional parameter that can be used to plot a cross hair at the coordinates. Up to two cross-hairs can be plotted, as any more can be visually confusing. If passing two, each row of a quantity is considered to be a separate coordinate pair.

  • mask (np.ndarray) – Allows the user to pass a numpy mask and view the masked data if they so choose.

  • chosen_points (np.ndarray) – A numpy array of a chosen point cluster from a hierarchical peak finder.

  • other_points (list) – A list of numpy arrays of point clusters that weren’t chosen by the hierarchical peak finder.

  • figsize (Tuple) – Allows the user to pass a custom size for the figure produced by this method.

  • zoom_in (bool) – Sets whether the figure limits should be set automatically so that borders with no data are reduced.

  • manual_zoom_xlims (tuple) – If set, this will override the automatic zoom in and manually set a part of the x-axis to limit the image to, default is None. Pass a tuple with two elements, first being the lower limit, second the upper limit. Variable zoom_in must still be true for these limits to be applied.

  • manual_zoom_ylims (tuple) – If set, this will override the automatic zoom in and manually set a part of the y-axis to limit the image to, default is None. Pass a tuple with two elements, first being the lower limit, second the upper limit. Variable zoom_in must still be true for these limits to be applied.

  • radial_bins_pix (np.ndarray) – Radii (in units of pixels) of annuli to plot on top of the image, will only be triggered if a cross_hair coordinate is also specified and contains only one coordinate.

  • back_bin_pix (np.ndarray) – The inner and outer radii (in pixel units) of the annulus used to measure the background value for a given profile, will only be triggered if a cross_hair coordinate is also specified and contains only one coordinate.

  • stretch (BaseStretch) – The astropy scaling to use for the image data, default is log.

  • mask_edges (bool) – If viewing a RateMap, this variable will control whether the chip edges are masked to remove artificially bright pixels, default is True.

  • view_regions (bool) – If regions have been associated with this object (either on init or using the ‘regions’ property setter, should they be displayed. Default is False.

  • ch_thickness (float) – The desired linewidth of the crosshair(s), can be useful to increase this in certain circumstances. Default is 0.8.

save_view(save_path, cross_hair=None, mask=None, chosen_points=None, other_points=None, figsize=(10, 8), zoom_in=False, manual_zoom_xlims=None, manual_zoom_ylims=None, radial_bins_pix=array([], dtype=float64), back_bin_pix=None, stretch=<astropy.visualization.stretch.LogStretch object>, mask_edges=True, view_regions=False, ch_thickness=0.8)[source]

This is entirely equivalent to the view() method, but instead of displaying the view it will save it to a path of your choosing.

Parameters
  • save_path (str) – The path (including file name) where you wish to save the view.

  • cross_hair (Quantity) – An optional parameter that can be used to plot a cross hair at the coordinates. Up to two cross-hairs can be plotted, as any more can be visually confusing. If passing two, each row of a quantity is considered to be a separate coordinate pair.

  • mask (np.ndarray) – Allows the user to pass a numpy mask and view the masked data if they so choose.

  • chosen_points (np.ndarray) – A numpy array of a chosen point cluster from a hierarchical peak finder.

  • other_points (list) – A list of numpy arrays of point clusters that weren’t chosen by the hierarchical peak finder.

  • figsize (Tuple) – Allows the user to pass a custom size for the figure produced by this method.

  • zoom_in (bool) – Sets whether the figure limits should be set automatically so that borders with no data are reduced.

  • manual_zoom_xlims (tuple) – If set, this will override the automatic zoom in and manually set a part of the x-axis to limit the image to, default is None. Pass a tuple with two elements, first being the lower limit, second the upper limit. Variable zoom_in must still be true for these limits to be applied.

  • manual_zoom_ylims (tuple) – If set, this will override the automatic zoom in and manually set a part of the y-axis to limit the image to, default is None. Pass a tuple with two elements, first being the lower limit, second the upper limit. Variable zoom_in must still be true for these limits to be applied.

  • radial_bins_pix (np.ndarray) – Radii (in units of pixels) of annuli to plot on top of the image, will only be triggered if a cross_hair coordinate is also specified and contains only one coordinate.

  • back_bin_pix (np.ndarray) – The inner and outer radii (in pixel units) of the annulus used to measure the background value for a given profile, will only be triggered if a cross_hair coordinate is also specified and contains only one coordinate.

  • stretch (BaseStretch) – The astropy scaling to use for the image data, default is log.

  • mask_edges (bool) – If viewing a RateMap, this variable will control whether the chip edges are masked to remove artificially bright pixels, default is True.

  • view_regions (bool) – If regions have been associated with this object (either on init or using the ‘regions’ property setter, should they be displayed. Default is False.

  • ch_thickness (float) – The desired linewidth of the crosshair(s), can be useful to increase this in certain circumstances. Default is 0.8.

edit_regions(figsize=(7, 7), cmap='gnuplot2', reg_save_path=None, cross_hair=None, radial_bins_pix=<Quantity [] pix>, back_bin_pix=None)[source]

This allows for displaying, interacting with, editing, and adding new regions to an image. These can then be saved as a new region file. It also allows for the dynamic adjustment of which regions are displayed, the scaling of the image, and smoothing, in order to make placing new regions as simple as possible. If a save path for region files is passed, then it will be possible to save new region files in RA-Dec coordinates.

Parameters
  • figsize (Tuple) – Allows the user to pass a custom size for the figure produced by this class.

  • cmap (str) – The colour map to use for displaying the image. Default is gnuplot2.

  • reg_save_path (str) – A string that will have ObsID values added before ‘.reg’ to construct save paths for the output region lists (if that feature is activated by the user). Default is None, in which case saving will be disabled.

  • cross_hair (Quantity) – An optional parameter that can be used to plot a cross hair at the coordinates. Up to two cross-hairs can be plotted, as any more can be visually confusing. If passing two, each row of a quantity is considered to be a separate coordinate pair.

  • radial_bins_pix (Quantity) – Radii (in units of pixels) of annuli to plot on top of the image, will only be triggered if a cross_hair coordinate is also specified and contains only one coordinate.

  • back_bin_pix (Quantity) – The inner and outer radii (in pixel units) of the annulus used to measure the background value for a given profile, will only be triggered if a cross_hair coordinate is also specified and contains only one coordinate.

dynamic_view(figsize=(7, 7), cmap='gnuplot2', cross_hair=None, radial_bins_pix=<Quantity [] pix>, back_bin_pix=None)[source]

This allows for displaying regions on an image. It also allows for the dynamic adjustment of which regions are displayed, the scaling of the image, and smoothing.

Parameters
  • figsize (Tuple) – Allows the user to pass a custom size for the figure produced by this class.

  • cmap (str) – The colour map to use for displaying the image. Default is gnuplot2.

  • cross_hair (Quantity) – An optional parameter that can be used to plot a cross hair at the coordinates. Up to two cross-hairs can be plotted, as any more can be visually confusing. If passing two, each row of a quantity is considered to be a separate coordinate pair.

  • radial_bins_pix (Quantity) – Radii (in units of pixels) of annuli to plot on top of the image, will only be triggered if a cross_hair coordinate is also specified and contains only one coordinate.

  • back_bin_pix (Quantity) – The inner and outer radii (in pixel units) of the annulus used to measure the background value for a given profile, will only be triggered if a cross_hair coordinate is also specified and contains only one coordinate.

class xga.products.phot.ExpMap(path, obs_id, instrument, stdout_str, stderr_str, gen_cmd, lo_en, hi_en, obs_inst_combs=None)[source]

Bases: xga.products.phot.Image

A very simple subclass of the Image product class - designed to allow for easy interaction with exposure maps.

Parameters
  • path (str) – The path to where the product file SHOULD be located.

  • obs_id (str) – The ObsID related to the ExpMap being declared.

  • instrument (str) – The instrument related to the ExpMap being declared.

  • stdout_str (str) – The stdout from calling the terminal command.

  • stderr_str (str) – The stderr from calling the terminal command.

  • gen_cmd (str) – The command used to generate the product.

  • lo_en (Quantity) – The lower energy bound used to generate this product.

  • hi_en (Quantity) – The upper energy bound used to generate this product.

  • obs_inst_combs (List[List]) – Supply a list of lists of ObsID-Instrument combinations if the image is combined and wasn’t made by emosaic (e.g. [[‘0404910601’, ‘pn’], [‘0404910601’, ‘mos1’], [‘0404910601’, ‘mos2’], [‘0201901401’, ‘pn’], [‘0201901401’, ‘mos1’], [‘0201901401’, ‘mos2’]].

get_exp(at_coord)[source]

A simple method that converts the given coordinates to pixels, then finds the exposure time at those coordinates.

Parameters

at_coord (Quantity) – A pair of coordinates to find the exposure time for.

Returns

The exposure time at the supplied coordinates.

Return type

Quantity

get_count(*args, **kwargs)[source]

Inherited method from Image superclass, disabled as does not make sense in an exposure map.

property smoothing_info

As exposure maps cannot be smoothed, this property overrides the Image smoothing_info getter, and returns None.

Returns

None, as exposure maps cannot be smoothed.

Return type

None

class xga.products.phot.RateMap(xga_image, xga_expmap, regs='', matched_regs=None)[source]

Bases: xga.products.phot.Image

A very powerful class which allows interactions with ‘RateMaps’, though these are not directly generated by SAS, they are images divided by matching exposure maps, to provide a count rate image.

Parameters
  • xga_image (Image) – The image component of the RateMap.

  • xga_expmap (ExpMap) – The exposure map component of the RateMap.

  • regs (str/List[SkyRegion/PixelRegion]/dict) – A region list file path, a list of region objects, or a dictionary of region lists with ObsIDs as dictionary keys.

  • matched_regs (dict/SkyRegion/PixelRegion) – Similar to the regs argument, but in this case for a region that has been designated as ‘matched’, i.e. is the subject of a current analysis. This should either be supplied as a single region object, or as a dictionary of region objects with ObsIDs as keys, or None values if there is no match. Such a dictionary can be retrieved from a source using the ‘matched_regions’ property. Default is None.

property shape

Property getter for the resolution of the ratemap. Standard XGA settings will make this 512x512.

Returns

The shape of the numpy array describing the ratemap.

Return type

Tuple[int, int]

property data

Property getter for ratemap data, overrides the method in the base Image class. This is because the ratemap class has a _construct_on_demand method that creates the ratemap data, which needs to be called instead of _read_on_demand.

Returns

A numpy array of shape self.shape containing the ratemap data.

Return type

np.ndarray

get_rate(at_coord)[source]

A simple method that converts the given coordinates to pixels, then finds the rate (in photons per second) and returns it.

Parameters

at_coord (Quantity) – A pair of coordinates to find the photon rate for.

Returns

The photon rate at the supplied coordinates.

Return type

Quantity

get_count(at_coord)[source]

A simple method that converts the given coordinates to pixels, then finds the number of counts at those coordinates.

Parameters

at_coord (Quantity) – Coordinate at which to find the number of counts.

Returns

The counts at the supplied coordinates.

Return type

Quantity

get_exp(at_coord)[source]

A simple method that converts the given coordinates to pixels, then finds the exposure time at those coordinates.

Parameters

at_coord (Quantity) – A pair of coordinates to find the exposure time for.

Returns

The exposure time at the supplied coordinates.

Return type

Quantity

simple_peak(mask, out_unit=Unit('deg'))[source]

Simplest possible way to find the position of the peak of X-ray emission in a ratemap. This method takes a mask in the form of a numpy array, which allows the user to mask out parts of the ratemap that shouldn’t be searched (outside of a certain region, or within point sources for instance).

Parameters
  • mask (np.ndarray) – A numpy array used to weight the data. It should be 0 for pixels that aren’t to be searched, and 1 for those that are.

  • out_unit (UnitBase/str) – The desired output unit of the peak coordinates, the default is degrees.

Returns

An astropy quantity containing the coordinate of the X-ray peak of this ratemap (given the user’s mask), in units of out_unit, as specified by the user. Also returned is a boolean flag that tells the caller if the peak is near a chip edge.

Return type

Tuple[Quantity, bool]

clustering_peak(mask, out_unit=Unit('deg'), top_frac=0.05, max_dist=5, clean_point_clusters=False)[source]

An experimental peak finding function that cuts out the top 5% (by default) of array elements (by value), and runs a hierarchical clustering algorithm on their positions. The motivation for this is that the cluster peak will likely be contained in that top 5%, and the only other pixels that might be involved are remnants of poorly removed point sources. So when clusters have been formed, we can take the one with the most entries, and find the maximal pixel of that cluster. Should be consistent with simple_peak under ideal circumstances.

Parameters
  • mask (np.ndarray) – A numpy array used to weight the data. It should be 0 for pixels that aren’t to be searched, and 1 for those that are.

  • out_unit (UnitBase/str) – The desired output unit of the peak coordinates, the default is degrees.

  • top_frac (float) – The fraction of the elements (ordered in descending value) that should be used to generate clusters, and thus be considered for the cluster centre.

  • max_dist (float) – The maximum distance criterion for the hierarchical clustering algorithm, in pixels.

  • clean_point_clusters (bool) – If this is set to true then the point clusters which are not believed to host the peak pixel will be cleaned, meaning that if they have less than 4 pixels associated with them then they will be removed.

Returns

An astropy quantity containing the coordinate of the X-ray peak of this ratemap (given the user’s mask), in units of out_unit, as specified by the user. Finally, the coordinates of the points in the chosen cluster are returned, as is a list of all the coordinates of all the other clusters.

Return type

Tuple[Quantity, bool]

convolved_peak(mask, redshift, cosmology, out_unit=Unit('deg'))[source]

A very experimental peak finding algorithm, credit for the idea and a lot of the code in this function go to Lucas Porth. A radial profile (for instance a project king profile for clusters) is convolved with the ratemap, using a suitable radius for the object type (so for a cluster r might be ~1000kpc). As such objects that are similar to this profile will be boosted preferentially over objects that aren’t, making it less likely that we accidentally select the peak brightness pixel from a point source remnant or something similar. The convolved image is then masked to only look at the area of interest, and the peak brightness pixel is found.

Parameters
  • mask (np.ndarray) – A numpy array used to weight the data. It should be 0 for pixels that aren’t to be searched, and 1 for those that are.

  • redshift (float) – The redshift of the source that we wish to find the X-ray peak of.

  • cosmology – An astropy cosmology object.

  • out_unit (UnitBase) – The desired output unit of the peak coordinates, the default is degrees.

Returns

An astropy quantity containing the coordinate of the X-ray peak of this ratemap (given the user’s mask), in units of out_unit, as specified by the user.

Return type

Tuple[Quantity, bool]

near_edge(coord)[source]

Uses the edge mask generated for RateMap objects to determine if the passed coordinates are near an edge/chip gap. If the coordinates are within +- 2 pixels of an edge the result will be true.

Parameters

coord (Quantity) – The coordinates to check.

Returns

A boolean flag as to whether the coordinates are near an edge.

Return type

bool

signal_to_noise(source_mask, back_mask, exp_corr=True, allow_negative=False)[source]

A signal to noise calculation method which takes information on source and background regions, then uses that to calculate a signal to noise for the source. This was primarily motivated by the desire to produce valid SNR values for combined data, where uneven exposure times across the combined field of view could cause issues with the usual approach of just summing the counts in the region images and scaling by area. This method can also measure signal to noises without exposure time correction.

Parameters
  • source_mask (np.ndarray) – The mask which defines the source region, ideally with interlopers removed.

  • back_mask (np.ndarray) – The mask which defines the background region, ideally with interlopers removed.

  • exp_corr (bool) – Should signal to noises be measured with exposure time correction, default is True. I recommend that this be true for combined observations, as exposure time could change quite dramatically across the combined product.

  • allow_negative (bool) – Should pixels in the background subtracted count map be allowed to go below zero, which results in a lower signal to noise (and can result in a negative signal to noise).

Returns

A signal to noise value for the source region.

Return type

float

background_subtracted_counts(source_mask, back_mask)[source]

This method uses a user-supplied source and background mask (alongside knowledge of the sensor layout drawn from the exposure map) to calculate the number of background-subtracted counts within the source region of the image used to construct this RateMap.

The exposure map is used to construct a sensor mask, so that we know where the chip gaps are and take them into account when calculating the ratio of areas of the source region to the background region. This is why this method is built into the RateMap rather than Image class.

Parameters
  • source_mask (np.ndarray) – The mask which defines the source region, ideally with interlopers removed.

  • back_mask (np.ndarray) – The mask which defines the background region, ideally with interlopers removed.

Returns

The background subtracted counts in the source region.

Return type

Quantity

property edge_mask

Returns the edge mask calculated for this RateMap in the form of a numpy array

Returns

A boolean numpy array in the same shape as the RateMap.

Return type

ndarray

property sensor_mask

Returns the detector map calculated for this RateMap. Values of 1 mean on chip, values of 0 mean off chip.

Returns

A boolean numpy array in the same shape as the RateMap.

Return type

ndarray

property expmap_path

Similar to the path property, but for the exposure map that went into this ratemap.

Returns

The exposure map path.

Return type

str

property image

This property allows the user to access the input Image object for this ratemap.

Returns

The input XGA Image object used to create this ratemap.

Return type

Image

property expmap

This property allows the user to access the input ExpMap object for this ratemap.

Returns

The input XGA ExpMap object used to create this ratemap.

Return type

ExpMap

property regions

Property getter for regions associated with this ratemap.

Returns

Returns a dictionary of regions, if they have been associated with this object.

Return type

Dict[PixelRegion]

property matched_regions

Property getter for any regions which have been designated a ‘match’ in the current analysis, if they have been set.

Returns

Returns a dictionary of matched regions, if they have been associated with this object.

Return type

Dict[PixelRegion]

class xga.products.phot.PSF(path, psf_model, obs_id, instrument, stdout_str, stderr_str, gen_cmd)[source]

Bases: xga.products.phot.Image

A subclass of image that is a wrapper for 2D images of PSFs that can be generated by SAS. This can be used to view the PSF and is used in other analyses to correct images.

Parameters
  • path (str) – The path to where the product file SHOULD be located.

  • psf_model (str) – The model used for the generation of the PSF.

  • obs_id (str) – The ObsID related to the PSF being declared.

  • instrument (str) – The instrument related to the PSF being declared.

  • stdout_str (str) – The stdout from calling the terminal command.

  • stderr_str (str) – The stderr from calling the terminal command.

  • gen_cmd (str) – The command used to generate the product.

get_val(at_coord)[source]

A simple method that converts the given coordinates to pixels, then finds the PSF value at those coordinates.

Parameters

at_coord (Quantity) – A pair of coordinates to find the PSF value time for.

Returns

The PSF value at the supplied coordinates.

Return type

Quantity

resample(im_prod, half_side_length)[source]

This method resamples a psfgen created PSF image to the same scale as the passed Image object. This is very important because psfgen makes these PSF images with a standard pixel size of 1 arcsec x 1 arcsec, and it can’t be changed when calling the routine. Thankfully, due to the wonders of WCS, it is possible to construct a new array with the same pixel size as a given image. Very important for when we want to deconvolve with an image and correct for the PSF.

Parameters
  • im_prod (Image) –

  • half_side_length (Quantity) –

Returns

The resampled PSF.

Return type

np.ndarray

property ra_dec

A property that fetches the RA-DEC that the PSF was generated at.

Returns

An astropy quantity of the ra and dec that the PSF was generated at.

Return type

Quantity

property model

This is the model that was used to generate this PSF.

Returns

XMM SAS psfgen model name.

Return type

str

class xga.products.phot.PSFGrid(file_paths, bins, psf_model, x_bounds, y_bounds, obs_id, instrument, stdout_str, stderr_str, gen_cmd)[source]

Bases: xga.products.base.BaseAggregateProduct

Parameters
  • file_paths (list) – The file paths of the individual PSF files for this grid.

  • bins (int) – The number of bins per side of the grid.

  • psf_model (str) – The model used to generate PSFs.

  • x_bounds (np.ndarray) – The upper and lower x boundaries of the bins in image pixel coordinates.

  • y_bounds (np.ndarray) – The upper and lower y boundaries of the bins in image pixel coordinates.

  • obs_id (str) – The ObsID for which this PSFGrid was generated.

  • instrument (str) – The instrument for which this PSFGrid was generated.

  • stdout_str (str) – The stdout from calling the terminal command.

  • stderr_str (str) – The stderr from calling the terminal command.

  • gen_cmd (str) – The commands used to generate the products.

property num_bins

Getter for the number of bins in X and Y that this PSFGrid has PSF objects for.

Returns

The number of bins per side used to generate this PSFGrid

Return type

int

property model

This is the model that was used to generate the component PSFs in this PSFGrid.

Returns

XMM SAS psfgen model name.

Return type

str

property x_bounds

The x lower (column 0) and x upper (column 1) bounds of the PSFGrid bins. :return: N x 2 numpy array, where N is the total number of PSFGrid bins. :rtype: np.ndarray

property y_bounds

The y lower (column 0) and y upper (column 1) bounds of the PSFGrid bins.

Returns

N x 2 numpy array, where N is the total number of PSFGrid bins.

Return type

np.ndarray

property grid_locs

A 3D quantity containing the central position of each PSF in the grid.

Returns

A 3D Quantity

Return type

unload_data()[source]

A convenience method that will iterate through the component PSFs of this object and remove their data from memory using the data property deleter. This ensures that, if the data needs to be accessed again, the call to .data will read in the PSFs and all will be well, hopefully.

products.profile module

class xga.products.profile.SurfaceBrightness1D(rt, radii, values, centre, pix_step, min_snr, outer_rad, radii_err=None, values_err=None, background=None, pixel_bins=None, back_pixel_bin=None, ann_areas=None, deg_radii=None, min_snr_succeeded=True)[source]

Bases: xga.products.base.BaseProfile1D

This class provides an interface to radially symmetric X-ray surface brightness profiles of extended objects.

Parameters
  • rt (RateMap) – The RateMap from which this SB profile was generated.

  • radii (Quantity) – The radii at which surface brightness has been measured.

  • values (Quantity) – The surface brightnesses that have been measured.

  • centre (Quantity) – The central coordinate the profile was generated from.

  • pix_step (int) – The width of each annulus in pixels used to generate this profile.

  • min_snr (float) – The minimum signal to noise imposed upon this profile.

  • outer_rad (Quantity) – The outer radius of this profile.

  • radii_err (Quantity) – Uncertainties on the radii.

  • values_err (Quantity) – Uncertainties on the values.

  • background (Quantity) – The background brightness value.

  • pixel_bins (np.ndarray) – An optional argument that provides the pixel bins used to create the profile.

  • back_pixel_bin (np.ndarray) – An optional argument that provides the pixel bin used for the background calculation of this profile.

  • ann_areas (Quantity) – The area of the annuli.

  • deg_radii (Quantity) – A slightly unfortunate variable that is required only if radii is not in units of degrees, or if no set_storage_key is passed. It should be a quantity containing the radii values converted to degrees, and allows this object to construct a predictable storage key.

  • min_snr_succeeded (bool) – A boolean flag describing whether re-binning was successful or not.

property pix_step

Property that returns the integer pixel step size used to generate the annuli that make up this profile.

Returns

The pixel step used to generate the surface brightness profile.

Return type

int

property min_snr

Property that returns minimum signal to noise value that was imposed upon this profile during generation.

Returns

The minimum signal to noise value used to generate this profile.

Return type

float

property psf_corrected

Tells the user (and XGA), whether the RateMap this brightness profile was generated from has been PSF corrected or not.

Returns

Boolean flag, True means this object has been PSF corrected, False means it hasn’t

Return type

bool

property psf_algorithm

If the RateMap this brightness profile was generated from has been PSF corrected, this property gives the name of the algorithm used.

Returns

The name of the algorithm used to correct for PSF effects, or None if there was no PSF correction.

Return type

Union[str, None]

property psf_bins

If the RateMap this brightness profile was generated from has been PSF corrected, this property gives the number of bins that the X and Y axes were divided into to generate the PSFGrid.

Returns

The number of bins in X and Y for which PSFs were generated, or None if the object

hasn’t been PSF corrected. :rtype: Union[int, None]

property psf_iterations

If the RateMap this brightness profile was generated from has been PSF corrected, this property gives the number of iterations that the algorithm went through.

Returns

The number of iterations the PSF correction algorithm went through, or None if there has been

no PSF correction. :rtype: Union[int, None]

property psf_model

If the RateMap this brightness profile was generated from has been PSF corrected, this property gives the name of the PSF model used.

Returns

The name of the PSF model used to correct for PSF effects, or None if there has been no

PSF correction. :rtype: Union[str, None]

property min_snr_succeeded

If True then the minimum signal to noise re-binning that can be applied to surface brightness profiles by some functions was successful, if False then it failed and the profile with no re-binning is stored here.

Returns

A boolean flag describing whether re-binning was successful or not.

Return type

bool

property pixel_bins

The annuli radii used to generate this profile, assuming they were passed on initialisation, otherwise None.

Returns

Numpy array containing the pixel bins used to measure this radial brightness profile.

Return type

np.ndarray

property back_pixel_bin

The annulus used to measure the background for this profile, assuming they were passed on initialisation, otherwise None.

Returns

Numpy array containing the pixel bin used to measure the background.

Return type

np.ndarray

property areas

Returns the areas of the annuli used to make this profile as an astropy Quantity.

Returns

Astropy non-scalar quantity containing the areas.

Return type

Quantity

check_match(rt, centre, pix_step, min_snr, outer_rad)[source]

A method for external use to check whether this profile matches the requested configuration of surface brightness profile, put here just because I imagine it’ll be used in quite a few places.

Parameters
  • rt (RateMap) – The RateMap to compare to this profile.

  • centre (Quantity) – The central coordinate to compare to this profile.

  • pix_step (int) – The width of each annulus in pixels to compare to this profile.

  • min_snr (float) – The minimum signal to noise to compare to this profile.

  • outer_rad (Quantity) – The outer radius to compare to this profile.

Returns

Whether this profile matches the passed parameters or not.

Return type

bool

class xga.products.profile.GasMass1D(radii, values, centre, source_name, obs_id, inst, dens_method, associated_prof, radii_err=None, values_err=None, deg_radii=None)[source]

Bases: xga.products.base.BaseProfile1D

This class provides an interface to a cumulative gas mass profile of a Galaxy Cluster.

Parameters
  • radii (Quantity) – The radii at which gas mass has been measured.

  • values (Quantity) – The gas mass that have been measured.

  • centre (Quantity) – The central coordinate the profile was generated from.

  • source_name (str) – The name of the source this profile is associated with.

  • obs_id (str) – The observation which this profile was generated from.

  • inst (str) – The instrument which this profile was generated from.

  • dens_method (str) – A keyword describing the method used to generate the density profile that was used to measure this gas mass profile.

  • associated_prof (SurfaceBrightness1D/APECNormalisation1D) – The profile that the gas density profile was measured from.

  • radii_err (Quantity) – Uncertainties on the radii.

  • values_err (Quantity) – Uncertainties on the values.

  • deg_radii (Quantity) – A slightly unfortunate variable that is required only if radii is not in units of degrees, or if no set_storage_key is passed. It should be a quantity containing the radii values converted to degrees, and allows this object to construct a predictable storage key.

property density_method

Gives the user the method used to generate the density profile used to make this gas mass profile.

Returns

The string describing the method

Return type

str

property generation_profile

Provides the profile from which the density profile used to make this gas mass profile was measured. Either a surface brightness profile if measured using SB methods, or an APEC normalisation profile if inferred from annular spectra.

Returns

The profile from which the density profile that made this profile was measured.

Return type

Union[SurfaceBrightness1D, APECNormalisation1D]

class xga.products.profile.GasDensity3D(radii, values, centre, source_name, obs_id, inst, dens_method, associated_prof, radii_err=None, values_err=None, associated_set_id=None, set_storage_key=None, deg_radii=None)[source]

Bases: xga.products.base.BaseProfile1D

This class provides an interface to a gas density profile of a galaxy cluster.

Parameters
  • radii (Quantity) – The radii at which gas density has been measured.

  • values (Quantity) – The gas densities that have been measured.

  • centre (Quantity) – The central coordinate the profile was generated from.

  • source_name (str) – The name of the source this profile is associated with.

  • obs_id (str) – The observation which this profile was generated from.

  • inst (str) – The instrument which this profile was generated from.

  • dens_method (str) – A keyword describing the method used to generate this density profile.

  • associated_prof (SurfaceBrightness1D/APECNormalisation1D) – The profile that this gas density profile was measured from.

  • radii_err (Quantity) – Uncertainties on the radii.

  • values_err (Quantity) – Uncertainties on the values.

  • associated_set_id (int) – The set ID of the AnnularSpectra that generated this - if applicable. It is possible for a Gas Density profile to be generated from spectral or photometric information.

  • set_storage_key (str) – Must be present if associated_set_id is, this is the storage key which the associated AnnularSpectra generates to place itself in XGA’s store structure.

  • deg_radii (Quantity) – A slightly unfortunate variable that is required only if radii is not in units of degrees, or if no set_storage_key is passed. It should be a quantity containing the radii values converted to degrees, and allows this object to construct a predictable storage key.

gas_mass(model, outer_rad, inner_rad=None, conf_level=68.2, fit_method='mcmc', radius_err=None)[source]

A method to calculate and return the gas mass (with uncertainties). This method uses the model to generate a gas mass distribution (using the fit parameter distributions from the fit performed using the model), then measures the median mass, along with lower and upper uncertainties.

Passing uncertainties on the outer (and inner) radii for the gas mass calculation is supported, with such uncertainties assumed to be representing a Gaussian distribution. Radii distributions will be drawn from a Gaussian, though any radii that are negative will be set to zero, so it could be a truncated Gaussian.

Parameters
  • model (str) – The name of the model from which to derive the gas mass.

  • outer_rad (Quantity) – The radius to measure the gas mass out to. Only one radius may be passed at a time.

  • inner_rad (Quantity) – The inner radius within which to measure the gas mass, this enables measuring core-excised gas masses. Default is None, which equates to zero. If passing separate uncertainties for inner and outer radii using `radius_err’, the inner radius error must be the second entry.

  • conf_level (float) – The confidence level to use to calculate the mass errors

  • fit_method (str) – The method that was used to fit the model, default is ‘mcmc’.

  • radius_err (Quantity) – A standard deviation on radius, which will be taken into account during the calculation of gas mass. If both an inner and outer radius have been passed, then you may pass either a single standard deviation value for both, or a Quantity with two entries. THE FIRST being the outer radius error, THE SECOND being inner radius error.

Returns

A Quantity containing three values (mass, -err, +err), and another Quantity containing the entire mass distribution from the whole realisation.

Return type

Tuple[Quantity, Quantity]

property density_method

Gives the user the method used to generate this density profile.

Returns

The string describing the method

Return type

str

property generation_profile

Provides the profile from which this density profile was measured. Either a surface brightness profile if measured using SB methods, or an APEC normalisation profile if inferred from annular spectra.

Returns

The profile from which the densities were measured.

Return type

Union[SurfaceBrightness1D, APECNormalisation1D]

view_gas_mass_dist(model, outer_rad, conf_level=68.2, figsize=8, 8, bins='auto', colour='lightslategrey', fit_method='mcmc')[source]

A method which will generate a histogram of the gas mass distribution that resulted from the gas mass calculation at the supplied radius. If the mass for the passed radius has already been measured it, and the mass distribution, will be retrieved from the storage of this product rather than re-calculated.

Parameters
  • model (str) – The name of the model from which to derive the gas mass.

  • outer_rad (Quantity) – The radius within which to calculate the gas mass.

  • conf_level (float) – The confidence level for the mass uncertainties, this doesn’t affect the distribution, only the vertical lines indicating the measured value of gas mass.

  • colour (str) – The desired colour of the histogram.

  • figsize (tuple) – The desired size of the histogram figure.

  • bins (int/str) – The argument to be passed to plt.hist, either a number of bins or a binning algorithm name.

  • fit_method (str) – The method that was used to fit the model, default is ‘mcmc’.

gas_mass_profile(model, radii=None, deg_radii=None, fit_method='mcmc')[source]

A method to calculate and return a gas mass profile.

Parameters
  • model (str) – The name of the model from which to derive the gas mass.

  • radii (Quantity) – The radii at which to measure gas masses. The default is None, in which case the radii at which this density profile has data points will be used.

  • deg_radii (Quantity) – The equivelant radii to radii but in degrees, required for defining a profile. The default is None, but if custom radii are passed then this variable must be passed too.

  • fit_method (str) – The method that was used to fit the model, default is ‘mcmc’.

Returns

A cumulative gas mass distribution.

Return type

GasMass1D

class xga.products.profile.ProjectedGasTemperature1D(radii, values, centre, source_name, obs_id, inst, radii_err=None, values_err=None, associated_set_id=None, set_storage_key=None, deg_radii=None)[source]

Bases: xga.products.base.BaseProfile1D

A profile product meant to hold a radial profile of projected X-ray temperature, as measured from a set of annular spectra by XSPEC. These are typically only defined by XGA methods.

Parameters
  • radii (Quantity) – The radii at which the projected gas temperatures have been measured, this should be in a proper radius unit, such as kpc.

  • values (Quantity) – The projected gas temperatures that have been measured.

  • centre (Quantity) – The central coordinate the profile was generated from.

  • source_name (str) – The name of the source this profile is associated with.

  • obs_id (str) – The observation which this profile was generated from.

  • inst (str) – The instrument which this profile was generated from.

  • radii_err (Quantity) – Uncertainties on the radii.

  • values_err (Quantity) – Uncertainties on the values.

  • associated_set_id (int) – The set ID of the AnnularSpectra that generated this - if applicable.

  • set_storage_key (str) – Must be present if associated_set_id is, this is the storage key which the associated AnnularSpectra generates to place itself in XGA’s store structure.

  • deg_radii (Quantity) – A slightly unfortunate variable that is required only if radii is not in units of degrees, or if no set_storage_key is passed. It should be a quantity containing the radii values converted to degrees, and allows this object to construct a predictable storage key.

class xga.products.profile.APECNormalisation1D(radii, values, centre, source_name, obs_id, inst, radii_err=None, values_err=None, associated_set_id=None, set_storage_key=None, deg_radii=None)[source]

Bases: xga.products.base.BaseProfile1D

A profile product meant to hold a radial profile of XSPEC normalisation, as measured from a set of annular spectra by XSPEC. These are typically only defined by XGA methods. This is a useful profile because it allows to not only infer 3D profiles of temperature and metallicity, but can also allow us to infer the 3D density profile.

Parameters
  • radii (Quantity) – The radii at which the APEC normalisations have been measured, this should be in a proper radius unit, such as kpc.

  • values (Quantity) – The APEC normalisations that have been measured.

  • centre (Quantity) – The central coordinate the profile was generated from.

  • source_name (str) – The name of the source this profile is associated with.

  • obs_id (str) – The observation which this profile was generated from.

  • inst (str) – The instrument which this profile was generated from.

  • radii_err (Quantity) – Uncertainties on the radii.

  • values_err (Quantity) – Uncertainties on the values.

  • associated_set_id (int) – The set ID of the AnnularSpectra that generated this - if applicable.

  • set_storage_key (str) – Must be present if associated_set_id is, this is the storage key which the associated AnnularSpectra generates to place itself in XGA’s store structure.

  • deg_radii (Quantity) – A slightly unfortunate variable that is required only if radii is not in units of degrees, or if no set_storage_key is passed. It should be a quantity containing the radii values converted to degrees, and allows this object to construct a predictable storage key.

gas_density_profile(redshift, cosmo, abund_table='angr', num_real=10000, sigma=1, num_dens=True)[source]

A method to calculate the gas density profile from the APEC normalisation profile, which in turn was measured from XSPEC fits of an AnnularSpectra. This method supports the generation of both number density and mass density profiles through the use of the num_dens keyword.

Parameters
  • redshift (float) – The redshift of the source that this profile was generated from.

  • cosmo – The chosen cosmology.

  • abund_table (str) – The abundance table to used for the conversion from n_e x n_H to n_e^2 during density calculation. Default is the famous Anders & Grevesse table.

  • num_real (int) – The number of data realisations which should be generated to infer density errors.

  • sigma (int) – What sigma of error should the density profile be created with, the default is 1σ.

  • num_dens (bool) – If True then a number density profile will be generated, otherwise a mass density profile

will be generated. :return: The gas density profile which has been calculated from the APEC normalisation profile. :rtype: GasDensity3D

emission_measure_profile(redshift, cosmo, abund_table='angr', num_real=100, sigma=2)[source]

A method to calculate the emission measure profile from the APEC normalisation profile, which in turn was measured from XSPEC fits of an AnnularSpectra.

Parameters
  • redshift (float) – The redshift of the source that this profile was generated from.

  • cosmo – The chosen cosmology.

  • abund_table (str) – The abundance table to used for the conversion from n_e x n_H to n_e^2 during density calculation. Default is the famous Anders & Grevesse table.

  • num_real (int) – The number of data realisations which should be generated to infer emission measure errors.

  • sigma (int) – What sigma of error should the density profile be created with, the default is 2σ.

Returns

Return type

class xga.products.profile.EmissionMeasure1D(radii, values, centre, source_name, obs_id, inst, radii_err=None, values_err=None, associated_set_id=None, set_storage_key=None, deg_radii=None)[source]

Bases: xga.products.base.BaseProfile1D

A profile product meant to hold a radial profile of X-ray emission measure.

Parameters
  • radii (Quantity) – The radii at which the emission measures have been measured, this should be in a proper radius unit, such as kpc.

  • values (Quantity) – The emission measures that have been measured.

  • centre (Quantity) – The central coordinate the profile was generated from.

  • source_name (str) – The name of the source this profile is associated with.

  • obs_id (str) – The observation which this profile was generated from.

  • inst (str) – The instrument which this profile was generated from.

  • radii_err (Quantity) – Uncertainties on the radii.

  • values_err (Quantity) – Uncertainties on the values.

  • associated_set_id (int) – The set ID of the AnnularSpectra that generated this - if applicable.

  • set_storage_key (str) – Must be present if associated_set_id is, this is the storage key which the associated AnnularSpectra generates to place itself in XGA’s store structure.

  • deg_radii (Quantity) – A slightly unfortunate variable that is required only if radii is not in units of degrees, or if no set_storage_key is passed. It should be a quantity containing the radii values converted to degrees, and allows this object to construct a predictable storage key.

class xga.products.profile.ProjectedGasMetallicity1D(radii, values, centre, source_name, obs_id, inst, radii_err=None, values_err=None, associated_set_id=None, set_storage_key=None, deg_radii=None)[source]

Bases: xga.products.base.BaseProfile1D

A profile product meant to hold a radial profile of projected X-ray metallicities/abundances, as measured from a set of annular spectra by XSPEC. These are typically only defined by XGA methods.

Parameters
  • radii (Quantity) – The radii at which the projected gas metallicity have been measured, this should be in a proper radius unit, such as kpc.

  • values (Quantity) – The projected gas metallicity that have been measured.

  • centre (Quantity) – The central coordinate the profile was generated from.

  • source_name (str) – The name of the source this profile is associated with.

  • obs_id (str) – The observation which this profile was generated from.

  • inst (str) – The instrument which this profile was generated from.

  • radii_err (Quantity) – Uncertainties on the radii.

  • values_err (Quantity) – Uncertainties on the values.

  • associated_set_id (int) – The set ID of the AnnularSpectra that generated this - if applicable.

  • set_storage_key (str) – Must be present if associated_set_id is, this is the storage key which the associated AnnularSpectra generates to place itself in XGA’s store structure.

  • deg_radii (Quantity) – A slightly unfortunate variable that is required only if radii is not in units of degrees, or if no set_storage_key is passed. It should be a quantity containing the radii values converted to degrees, and allows this object to construct a predictable storage key.

class xga.products.profile.GasTemperature3D(radii, values, centre, source_name, obs_id, inst, radii_err=None, values_err=None, associated_set_id=None, set_storage_key=None, deg_radii=None)[source]

Bases: xga.products.base.BaseProfile1D

A profile product meant to hold a 3D radial profile of X-ray temperature, as measured by some form of de-projection applied to a projected temperature profile.

Parameters
  • radii (Quantity) – The radii at which the gas temperatures have been measured, this should be in a proper radius unit, such as kpc.

  • values (Quantity) – The gas temperatures that have been measured.

  • centre (Quantity) – The central coordinate the profile was generated from.

  • source_name (str) – The name of the source this profile is associated with.

  • obs_id (str) – The observation which this profile was generated from.

  • inst (str) – The instrument which this profile was generated from.

  • radii_err (Quantity) – Uncertainties on the radii.

  • values_err (Quantity) – Uncertainties on the values.

  • associated_set_id (int) – The set ID of the AnnularSpectra that generated this - if applicable.

  • set_storage_key (str) – Must be present if associated_set_id is, this is the storage key which the associated AnnularSpectra generates to place itself in XGA’s store structure.

  • deg_radii (Quantity) – A slightly unfortunate variable that is required only if radii is not in units of degrees, or if no set_storage_key is passed. It should be a quantity containing the radii values converted to degrees, and allows this object to construct a predictable storage key.

class xga.products.profile.BaryonFraction(radii, values, centre, source_name, obs_id, inst, radii_err=None, values_err=None, associated_set_id=None, set_storage_key=None, deg_radii=None)[source]

Bases: xga.products.base.BaseProfile1D

A profile product which will hold a profile showing how the baryon fraction of a galaxy cluster changes with radius. These profiles are typically generated from a HydrostaticMass profile product instance.

Parameters
  • radii (Quantity) – The radii at which the baryon fracion have been measured, this should be in a proper radius unit, such as kpc.

  • values (Quantity) – The baryon fracions that have been measured.

  • centre (Quantity) – The central coordinate the profile was generated from.

  • source_name (str) – The name of the source this profile is associated with.

  • obs_id (str) – The observation which this profile was generated from.

  • inst (str) – The instrument which this profile was generated from.

  • radii_err (Quantity) – Uncertainties on the radii.

  • values_err (Quantity) – Uncertainties on the values.

  • associated_set_id (int) – The set ID of the AnnularSpectra that generated this - if applicable.

  • set_storage_key (str) – Must be present if associated_set_id is, this is the storage key which the associated AnnularSpectra generates to place itself in XGA’s store structure.

  • deg_radii (Quantity) – A slightly unfortunate variable that is required only if radii is not in units of degrees, or if no set_storage_key is passed. It should be a quantity containing the radii values converted to degrees, and allows this object to construct a predictable storage key.

class xga.products.profile.HydrostaticMass(temperature_profile, temperature_model, density_profile, density_model, radii, radii_err, deg_radii, fit_method='mcmc', num_walkers=20, num_steps=20000, num_samples=10000, show_warn=True, progress=True)[source]

Bases: xga.products.base.BaseProfile1D

A profile product which uses input GasTemperature3D and GasDensity3D profiles to generate a hydrostatic mass profile, which in turn can be used to measure the hydrostatic mass at a particular radius. In contrast to other profile objects, this one calculates the y values itself, as such any radii may be passed.

Parameters
  • temperature_profile (GasTemperature3D) – The XGA 3D temperature profile to take temperature information from.

  • temperature_model (str/BaseModel1D) – The model to fit to the temperature profile, either a name or an instance of an XGA temperature model class.

  • density_profile (GasDensity3D) – The XGA 3D density profile to take density information from.

  • density_model (str/BaseModel1D) – The model to fit to the density profile, either a name or an instance of an XGA density model class.

  • radii (Quantity) – The radii at which to measure the hydrostatic mass for the declaration of the profile.

  • radii_err (Quantity) – The uncertainties on the radii.

  • deg_radii (Quantity) – The radii values, but in units of degrees. This is required to set up a storage key for the profile to be filed in an XGA source.

  • fit_method (str) – The name of the fit method to use for the fitting of the profiles, default is ‘mcmc’.

  • num_walkers (int) – If the fit method is ‘mcmc’ then this will set the number of walkers for the emcee sampler to set up.

  • num_steps (list/int) – If the fit method is ‘mcmc’ this will set the number of steps for each sampler to take. If a single number is passed then that number of steps is used for both profiles, otherwise if a list is passed the first entry is used for the temperature fit, and the second for the density fit.

  • num_samples (int) – The number of random samples to be drawn from the posteriors of the fit results.

  • show_warn (bool) – Should warnings thrown during the fitting processes be shown.

  • progress (bool) – Should fit progress bars be shown.

mass(radius, conf_level=68.2, radius_err=None)[source]

A method which will measure a hydrostatic mass and hydrostatic mass uncertainty within the given radius/radii. No corrections are applied to the values calculated by this method, it is just the vanilla hydrostatic mass.

If the models for temperature and density have analytical solutions to their derivative wrt to radius then those will be used to calculate the gradients at radius, but if not then a numerical method will be used for which dx will be set to radius/1e+6.

Parameters
  • radius (Quantity) – An astropy quantity containing the radius/radii that you wish to calculate the mass within.

  • conf_level (float) – The confidence level for the mass uncertainties, the default is 68.2% (~1σ).

  • radius_err (Quantity) – A standard deviation on radius, which will be taken into account during the calculation of hydrostatic mass.

Returns

An astropy quantity containing the mass/masses, lower and upper uncertainties, and another containing the mass realisation distribution.

Return type

Union[Quantity, Quantity]

annular_mass(outer_radius, inner_radius, conf_level=68.2)[source]

Calculate the hydrostatic mass contained within a specific 3D annulus, bounded by the outer and inner radius supplied to this method. Annular mass is calculated by measuring the mass within the inner and outer radii, and then subtracting the inner from the outer. Also supports calculating multiple annular masses when inner_radius and outer_radius are non-scalar.

WARNING - THIS METHOD INVOLVES SUBTRACTING TWO MASS DISTRIBUTIONS, WHICH CAN’T NECESSARILY BE APPROXIMATED AS GAUSSIAN DISTRIBUTIONS, AS SUCH RESULTS FROM THIS METHOD SHOULD BE TREATED WITH SOME SUSPICION.

Parameters
  • outer_radius (Quantity) – Astropy containing outer radius (or radii) for the annulus (annuli) within which you wish to measure the mass. If calculating multiple annular masses, the length of outer_radius must be the same as inner_radius.

  • inner_radius (Quantity) – Astropy containing inner radius (or radii) for the annulus (annuli) within which you wish to measure the mass. If calculating multiple annular masses, the length of inner_radius must be the same as outer_radius.

  • conf_level (float) – The confidence level for the mass uncertainties, the default is 68.2% (~1σ).

Returns

An astropy quantity containing a mass distribution(s). Quantity will become two-dimensional when multiple sets of inner and outer radii are passed by the user.

Return type

Quantity

view_mass_dist(radius, conf_level=68.2, figsize=8, 8, bins='auto', colour='lightslategrey')[source]

A method which will generate a histogram of the mass distribution that resulted from the mass calculation at the supplied radius. If the mass for the passed radius has already been measured it, and the mass distribution, will be retrieved from the storage of this product rather than re-calculated.

Parameters
  • radius (Quantity) – An astropy quantity containing the radius/radii that you wish to calculate the mass within.

  • conf_level (float) – The confidence level for the mass uncertainties, the default is 68.2% (~1σ).

  • bins (int/str) – The argument to be passed to plt.hist, either a number of bins or a binning algorithm name.

  • colour (str) – The desired colour of the histogram.

  • figsize (tuple) – The desired size of the histogram figure.

baryon_fraction(radius, conf_level=68.2)[source]

A method to use the hydrostatic mass information of this profile, and the gas density information of the input gas density profile, to calculate a baryon fraction within the given radius.

Parameters
  • radius (Quantity) – An astropy quantity containing the radius/radii that you wish to calculate the baryon fraction within.

  • conf_level (float) – The confidence level for the mass uncertainties, the default is 68.2% (~1σ).

Returns

An astropy quantity containing the baryon fraction, -ve error, and +ve error, and another quantity containing the baryon fraction distribution.

Return type

Tuple[Quantity, Quantity]

view_baryon_fraction_dist(radius, conf_level=68.2, figsize=8, 8, bins='auto', colour='lightslategrey')[source]

A method which will generate a histogram of the baryon fraction distribution that resulted from the mass calculation at the supplied radius. If the baryon fraction for the passed radius has already been measured it, and the baryon fraction distribution, will be retrieved from the storage of this product rather than re-calculated.

Parameters
  • radius (Quantity) – An astropy quantity containing the radius/radii that you wish to calculate the baryon fraction within.

  • conf_level (float) – The confidence level for the mass uncertainties, the default is 68.2% (~1σ).

  • bins (int/str) – The argument to be passed to plt.hist, either a number of bins or a binning algorithm name.

  • figsize (tuple) – The desired size of the histogram figure.

  • colour (str) – The desired colour of the histogram.

baryon_fraction_profile()[source]

A method which uses the baryon_fraction method to construct a baryon fraction profile at the radii of this HydrostaticMass profile. The uncertainties on the baryon fraction are calculated at the 1σ level.

Returns

An XGA BaryonFraction object.

Return type

BaryonFraction

overdensity_radius(delta, redshift, cosmo, init_lo_rad=<Quantity 100. kpc>, init_hi_rad=<Quantity 3500. kpc>, init_step=<Quantity 100. kpc>, out_unit=Unit("kpc"))[source]

This method uses the mass profile to find the radius that corresponds to the user-supplied overdensity - common choices for cluster analysis are Δ=2500, 500, and 200. Overdensity radii are defined as the radius at which the density is Δ times the critical density of the Universe at the cluster redshift.

This method takes a numerical approach to the location of the requested radius. Though we have calculated analytical hydrostatic mass models for common choices of temperature and density profile models, there are no analytical solutions for R.

When an overdensity radius is being calculated, we initially measure masses for a range of radii between init_lo_rad - init_hi_rad in steps of init_step. From this we find the two radii that bracket the radius where average density - Delta*critical density = 0. Between those two radii we perform the same test with another range of radii (in steps of 1 kpc this time), finding the radius that corresponds to the minimum density difference value.

Parameters
  • delta (int) – The overdensity factor for which a radius is to be calculated.

  • redshift (float) – The redshift of the cluster.

  • cosmo – The cosmology in which to calculate the overdensity. Should be an astropy cosmology instance.

  • init_lo_rad (Quantity) – The lower radius bound for the first radii array generated to find the wide brackets around the requested overdensity radius. Default value is 100 kpc.

  • init_hi_rad (Quantity) – The upper radius bound for the first radii array generated to find the wide brackets around the requested overdensity radius. Default value is 3500 kpc.

  • init_step (Quantity) – The step size for the first radii array generated to find the wide brackets around the requested overdensity radius. Default value is 100 kpc, recommend that you don’t set it smaller than 10 kpc.

  • out_unit (Unit/str) – The unit that this method should output the radius with.

Returns

The calculated overdensity radius.

Return type

Quantity

diagnostic_view(src=None, figsize=None)[source]

This method produces a figure with the most important products that went into the creation of this HydrostaticMass profile, for the purposes of quickly checking that everything looks sensible. The maximum number of plots included is five; mass profile, temperature profile, density profile, surface brightness profile, and ratemap. The RateMap will only be included if the source that this profile was generated from is passed.

Parameters
  • src (GalaxyCluster) – The GalaxyCluster source that this HydrostaticMass profile was generated from.

  • figsize (tuple) – A tuple that sets the size of the diagnostic plot, default is None in which case it is set automatically.

save_diagnostic_view(save_path, src=None, figsize=None)[source]

This method saves a figure (without displaying) with the most important products that went into the creation of this HydrostaticMass profile, for the purposes of quickly checking that everything looks sensible. The maximum number of plots included is five; mass profile, temperature profile, density profile, surface brightness profile, and ratemap. The RateMap will only be included if the source that this profile was generated from is passed.

Parameters
  • save_path (str) – The path and filename where the diagnostic figure should be saved.

  • src (GalaxyCluster) – The GalaxyCluster source that this HydrostaticMass profile was generated from.

  • figsize (tuple) – A tuple that sets the size of the diagnostic plot, default is None in which case it is set automatically.

property temperature_profile

A method to provide access to the 3D temperature profile used to generate this hydrostatic mass profile.

Returns

The input temperature profile.

Return type

GasTemperature3D

property density_profile

A method to provide access to the 3D density profile used to generate this hydrostatic mass profile.

Returns

The input density profile.

Return type

GasDensity3D

property temperature_model

A method to provide access to the model that was fit to the temperature profile.

Returns

The fit temperature model.

Return type

BaseModel1D

property density_model

A method to provide access to the model that was fit to the density profile.

Returns

The fit density profile.

Return type

BaseModel1D

rad_check(rad)[source]

Very simple method that prints a warning if the radius is outside the range of data covered by the density or temperature profiles.

Parameters

rad (Quantity) – The radius to check.

class xga.products.profile.SpecificEntropy(temperature_profile, temperature_model, density_profile, density_model, radii, radii_err, deg_radii, fit_method='mcmc', num_walkers=20, num_steps=20000, num_samples=10000, show_warn=True, progress=True)[source]

Bases: xga.products.base.BaseProfile1D

A profile product which uses input GasTemperature3D and GasDensity3D profiles to generate a specific entropy profile. Functionally this is extremely similar to the HydrostaticMass profile class, as it calculates the y values itself, rather than them being part of the declaration.

Parameters
  • temperature_profile (GasTemperature3D) – The XGA 3D temperature profile to take temperature information from.

  • temperature_model (str/BaseModel1D) – The model to fit to the temperature profile, either a name or an instance of an XGA temperature model class.

  • density_profile (GasDensity3D) – The XGA 3D density profile to take density information from.

  • density_model (str/BaseModel1D) – The model to fit to the density profile, either a name or an instance of an XGA density model class.

  • radii (Quantity) – The radii at which to measure the entropy for the declaration of the profile.

  • radii_err (Quantity) – The uncertainties on the radii.

  • deg_radii (Quantity) – The radii values, but in units of degrees. This is required to set up a storage key for the profile to be filed in an XGA source.

  • fit_method (str) – The name of the fit method to use for the fitting of the profiles, default is ‘mcmc’.

  • num_walkers (int) – If the fit method is ‘mcmc’ then this will set the number of walkers for the emcee sampler to set up.

  • num_steps (list/int) – If the fit method is ‘mcmc’ this will set the number of steps for each sampler to take. If a single number is passed then that number of steps is used for both profiles, otherwise if a list is passed the first entry is used for the temperature fit, and the second for the density fit.

  • num_samples (int) – The number of random samples to be drawn from the posteriors of the fit results.

  • show_warn (bool) – Should warnings thrown during the fitting processes be shown.

  • progress (bool) – Should fit progress bars be shown.

entropy(radius, conf_level=68.2)[source]

A method which will measure a specific entropy and specific entropy uncertainty within the given radius/radii.

If the models for temperature and density have analytical solutions to their derivative wrt to radius then those will be used to calculate the gradients at radius, but if not then a numerical method will be used for which dx will be set to radius/1e+6.

Parameters
  • radius (Quantity) – An astropy quantity containing the radius/radii that you wish to calculate the mass within.

  • conf_level (float) – The confidence level for the entropy uncertainties, the default is 68.2% (~1σ).

Returns

An astropy quantity containing the entropy/entropies, lower and upper uncertainties, and another containing the mass realisation distribution.

Return type

Union[Quantity, Quantity]

view_entropy_dist(radius, conf_level=68.2, figsize=8, 8, bins='auto', colour='lightslategrey')[source]

A method which will generate a histogram of the entropy distribution that resulted from the entropy calculation at the supplied radius. If the entropy for the passed radius has already been measured it, and the entropy distribution, will be retrieved from the storage of this product rather than re-calculated.

Parameters
  • radius (Quantity) – An astropy quantity containing the radius/radii that you wish to calculate the entropy at.

  • conf_level (float) – The confidence level for the entropy uncertainties, the default is 68.2% (~1σ).

  • bins (int/str) – The argument to be passed to plt.hist, either a number of bins or a binning algorithm name.

  • colour (str) – The desired colour of the histogram.

  • figsize (tuple) – The desired size of the histogram figure.

property temperature_profile

A method to provide access to the 3D temperature profile used to generate this entropy profile.

Returns

The input temperature profile.

Return type

GasTemperature3D

property density_profile

A method to provide access to the 3D density profile used to generate this entropy profile.

Returns

The input density profile.

Return type

GasDensity3D

property temperature_model

A method to provide access to the model that was fit to the temperature profile.

Returns

The fit temperature model.

Return type

BaseModel1D

property density_model

A method to provide access to the model that was fit to the density profile.

Returns

The fit density profile.

Return type

BaseModel1D

rad_check(rad)[source]

Very simple method that prints a warning if the radius is outside the range of data covered by the density or temperature profiles.

Parameters

rad (Quantity) – The radius to check.

class xga.products.profile.Generic1D(radii, values, centre, source_name, obs_id, inst, y_axis_label, prof_type, radii_err=None, values_err=None, associated_set_id=None, set_storage_key=None, deg_radii=None)[source]

Bases: xga.products.base.BaseProfile1D

A 1D profile product meant to hold profiles which have been dynamically generated by XSPEC profile fitting of models that I didn’t build into XGA. It can also be used to make arbitrary profiles using external data.

Parameters
  • centre (Quantity) – The central coordinate the profile was generated from.

  • source_name (str) – The name of the source this profile is associated with.

  • obs_id (str) – The observation which this profile was generated from.

  • inst (str) – The instrument which this profile was generated from.

  • y_axis_label (str) – The label to apply to the y-axis of any plots generated from this profile.

  • prof_type (str) – This is a string description of the profile, used to store it in an XGA source (with _profile appended). For instance the prof_type of a ProjectedGasTemperature1D instance is 1d_proj_temperature, and it would be stored under 1d_proj_temperature_profile.

  • radii_err (Quantity) – Uncertainties on the radii.

  • values_err (Quantity) – Uncertainties on the values.

  • associated_set_id (int) – The set ID of the AnnularSpectra that generated this - if applicable.

  • set_storage_key (str) – Must be present if associated_set_id is, this is the storage key which the associated AnnularSpectra generates to place itself in XGA’s store structure.

  • deg_radii (Quantity) – A slightly unfortunate variable that is required only if radii is not in units of degrees, or if no set_storage_key is passed. It should be a quantity containing the radii values converted to degrees, and allows this object to construct a predictable storage key.

products.relation module

class xga.products.relation.ScalingRelation(fit_pars, fit_par_errs, model_func, x_norm, y_norm, x_name, y_name, dim_hubb_ind=None, fit_method='unknown', x_data=None, y_data=None, x_err=None, y_err=None, x_lims=None, odr_output=None, chains=None, relation_name=None, relation_author='XGA', relation_year='2023', relation_doi='', scatter_par=None, scatter_chain=None, model_colour=None, point_names=None, third_dim_info=None, third_dim_name=None)[source]

Bases: object

This class is designed to store all information pertaining to a scaling relation fit, either performed by XGA or from literature. It also aims to make creating publication quality plots simple and easy.

Parameters
  • fit_pars (np.ndarray) – The results of the fit to a model that describes this scaling relation.

  • fit_par_errs (np.ndarray) – The uncertainties on the fit results for this scalin relation.

  • model_func – A Python function of the model which this scaling relation is described by. PLEASE NOTE, the function must be defined in the style used in xga.models.misc; i.e. powerlaw(x: np.ndarray, k: float, a: float), where the first argument is for x values, and the following arguments are all fit parameters.

  • x_norm (Quantity) – Quantity to normalise the x data by.

  • y_norm (Quantity) – Quantity to normalise the y data by.

  • x_name (str) – The name to be used for the x-axis of the plot (DON’T include the unit, that will be inferred from an astropy Quantity.

  • y_name (str) – The name to be used for the y-axis of the plot (DON’T include the unit, that will be inferred from an astropy Quantity.

  • dim_hubb_ind (float/int) – This is used to tell the ScalingRelation which power of E(z) has been applied to the y-axis data, this can then be used by the predict method to remove the E(z) contribution from predictions. The default is None.

  • fit_method (str) – The method used to fit this data, if known.

  • x_data (Quantity) – The x-data used to fit this scaling relation, if available. This should be the raw, un-normalised data.

  • y_data (Quantity) – The y-data used to fit this scaling relation, if available. This should be the raw, un-normalised data.

  • x_err (Quantity) – The x-errors used to fit this scaling relation, if available. This should be the raw, un-normalised data.

  • y_err (Quantity) – The y-errors used to fit this scaling relation, if available. This should be the raw, un-normalised data.

  • x_lims (Quantity) – The range of x values in which this relation is valid, default is None. If this information is supplied, please pass it as a Quantity array, with the first element being the lower bound and the second element being the upper bound.

  • odr_output (odr.Output) – The orthogonal distance regression output object associated with this relation’s fit, if available and applicable.

  • chains (np.ndarray) – The parameter chains associated with this relation’s fit, if available and applicable. They should be of shape N_stepxN_par, where N_steps is the number of steps (after burn-in is removed), and N_par is the number of parameters in the fit.

  • relation_name (str) – A suitable name for this relation.

  • relation_author (str) – The author who deserves credit for this relation.

  • relation_year (str) – The year this relation was produced, default is the current year.

  • relation_doi (str) – The DOI of the original paper this relation appeared in.

  • scatter_par (np.ndarray) – A parameter describing the intrinsic scatter of y|x. Optional as many fits don’t include this.

  • scatter_chain (np.ndarray) – A corresponding MCMC chain for the scatter parameter. Optional.

  • model_colour (str) – This variable can be used to set the colour that the fit should be displayed in when plotting. Setting it at definition or setting the property means that the colour doesn’t have to be set for every view method, and it will be remembered when multiple relations are viewed together.

  • point_names (np.ndarray/list) – The source names associated with the data points passed in to this scaling relation, can be used for diagnostic purposes (i.e. identifying which source an outlier belongs to).

  • third_dim_info (np.ndarray/Quantity) – A set of data points which represent a faux third dimension. They should not have been involved in the fitting process, and the relation should not be in three dimensions, but these can be used to colour the data points in a view method.

  • third_dim_name (str) – The name of the third dimension data.

property pars

The parameters that describe this scaling relation, along with their uncertainties. They are in the order in which they are expected to be passed into the model function.

Returns

A numpy array of the fit parameters and their uncertainties, first column are parameters, second column are uncertainties.

Return type

np.ndarray

property model_func

Provides the model function used to fit this relation.

Returns

The Python function of this relation’s model.

property x_name

A string containing the name of the x-axis of this relation.

Returns

A Python string containing the name.

Return type

str

property y_name

A string containing the name of the x-axis of this relation.

Returns

A Python string containing the name.

Return type

str

property dimensionless_hubble_parameter

This property should be set on the declaration of a scaling relation, and exists to tell the relation what power of E(z) has been applied to the y-axis data before fitting. This also helps the predict method remove the E(z) contribution (if any) from predictions.

Returns

The power of E(z) applied to the y-axis data before fitting. Default is None.

Return type

float/int

property x_norm

The astropy quantity containing the x-axis normalisation used during fitting.

Returns

An astropy quantity object.

Return type

Quantity

property y_norm

The astropy quantity containing the y-axis normalisation used during fitting.

Returns

An astropy quantity object.

Return type

Quantity

property x_unit

The astropy unit object relevant to the x-axis of this relation.

Returns

An Astropy Unit object.

Return type

Unit

property y_unit

The astropy unit object relevant to the y-axis of this relation.

Returns

An Astropy Unit object.

Return type

Unit

property x_data

An astropy Quantity of the x-data used to fit this relation, or an empty quantity if that data is not available. The first column is the data, the second is the uncertainties.

Returns

An Astropy Quantity object, containing the data and uncertainties.

Return type

Quantity

property y_data

An astropy Quantity of the y-data used to fit this relation, or an empty quantity if that data is not available. The first column is the data, the second is the uncertainties.

Returns

An Astropy Quantity object, containing the data and uncertainties.

Return type

Quantity

property x_lims

If the user passed an x range in which the relation is valid on initialisation, then this will return those limits in the same units as the x-axis.

Returns

A quantity containing upper and lower x limits, or None.

Return type

Quantity

property fit_method

A descriptor for the fit method used to generate this scaling relation.

Returns

A string containing the name of the fit method.

Return type

str

property name

A property getter for the name of the relation, this may not be unique in cases where no name was passed on declaration.

Returns

String containing the name of the relation.

Return type

str

property author

A property getter for the author of the relation, if not from literature it will be XGA.

Returns

String containing the name of the author.

Return type

str

property year

A property getter for the year that the relation was created/published, if not from literature it will be the current year.

Returns

String containing the year of publication/creation.

Return type

str

property doi

A property getter for the doi of the original paper of the relation, if not from literature it will an empty string.

Returns

String containing the doi.

Return type

str

property scatter_par

A getter for the scatter information.

Returns

The scatter parameter and its uncertainty. If no scatter information was passed on definition then this will return None.

Return type

np.ndarray

property scatter_chain

A getter for the scatter information chain.

Returns

The scatter chain. If no scatter information was passed on definition then this will return None.

Return type

np.ndarray

property chains

Property getter for the parameter chains.

Returns

The MCMC chains of the fit for this scaling relation, if they were passed. Otherwise None.

Return type

np.ndarray

property par_names

Getter for the parameter names.

Returns

The names of the model parameters.

Return type

List

property model_colour

Property getter for the model colour assigned to this relation. If it wasn’t set at definition or set via the property setter then it defaults to ‘tab:gray’.

Returns

The currently set model colour. If one wasn’t set on definition then we default to tab:gray.

Return type

str

property point_names

Returns an array of point names, with one entry per data point, and in the same order (unless the user passes a differently ordered name array than data array, there is no way we can detect that).

Returns

The names associated with the data points, if supplied on initialization. The default is None.

Return type

np.ndarray/None

property third_dimension_data

Returns a Quantity containing a third dimension of data associated with the data points (this can be used to colour the points in the view method), with one entry per data point, and in the same order (unless the user passes a differently ordered name array than data array, there is no way we can detect that).

Returns

The third dimension data associated with the data points, if supplied on initialization. The default is None.

Return type

Quantity/None

property third_dimension_name

Returns the name of the third data dimension passed to this relation on initialization.

Returns

The name of the third dimension, if supplied on initialization. The default is None.

Return type

Quantity/None

view_chains(figsize=None, colour=None)[source]

Simple view method to quickly look at the MCMC chains for a scaling relation fit.

Parameters
  • figsize (tuple) – Desired size of the figure, if None will be set automatically.

  • colour (str) – The colour that the chains should be in the plot. Default is None in which case the value of the model_colour property of the relation is used.

view_corner(figsize=10, 10, cust_par_names=None, colour=None, save_path=None)[source]

A convenient view method to examine the corner plot of the parameter posterior distributions.

Parameters
  • figsize (tuple) – The size of the figure.

  • cust_par_names (List[str]) – A list of custom parameter names. If the names include LaTeX code do not include $$ math environment symbols - you may also need to pass a string literal (e.g. r”sigma”). Do not include an entry for a scatter parameter.

  • colour (List[str]) – Colour for the contours. Default is None in which case the value of the model_colour property of the relation is used.

  • save_path (str) – The path where the figure produced by this method should be saved. Default is None, in which case the figure will not be saved.

predict(x_values, redshift=None, cosmo=None)[source]

This method allows for the prediction of y values from this scaling relation, you just need to pass in an appropriate set of x values. If a power of E(z) was applied to the y-axis data before fitting, and that information was passed on declaration (using ‘dim_hubb_ind’), then a redshift and cosmology are required to remove out the E(z) contribution.

Parameters
  • x_values (Quantity) – The x values to predict y values for.

  • redshift (float/np.ndarray) – The redshift(s) of the objects for which we wish to predict values. This is only necessary if the ‘dim_hubb_ind’ argument was set on declaration. Default is None.

  • cosmo (Cosmology) – The cosmology in which we wish to predict values. This is only necessary if the ‘dim_hubb_ind’ argument was set on declaration. Default is None.

Returns

The predicted y values.

Return type

Quantity

view(x_lims=None, log_scale=True, plot_title=None, figsize=10, 8, data_colour='black', model_colour=None, grid_on=False, conf_level=90, custom_x_label=None, custom_y_label=None, fontsize=15, legend_fontsize=13, x_ticks=None, x_minor_ticks=None, y_ticks=None, y_minor_ticks=None, save_path=None, label_points=False, point_label_colour='black', point_label_size=10, point_label_offset=0.01, 0.01, show_third_dim=True, third_dim_cmap='plasma')[source]

A method that produces a high quality plot of this scaling relation (including the data it is based upon, if available).

Parameters
  • x_lims (Quantity) – If not set, this method will attempt to take appropriate limits from the x-data this relation is based upon, if that data is not available an error will be thrown.

  • log_scale (bool) – If true then the x and y axes of the plot will be log-scaled.

  • plot_title (str) – A custom title to be used for the plot, otherwise one will be generated automatically.

  • figsize (tuple) – A custom figure size for the plot, default is (8, 8).

  • data_colour (str) – The colour to use for the data points in the plot, default is black.

  • model_colour (str) – The colour to use for the model in the plot. Default is None in which case the value of the model_colour property of the relation is used.

  • grid_on (bool) – If True then a grid will be included on the plot. Default is True.

  • conf_level (int) – The confidence level to use when plotting the model.

  • custom_x_label (str) – Passing a string to this variable will override the x axis label of this plot, including the unit string.

  • custom_y_label (str) – Passing a string to this variable will override the y axis label of this plot, including the unit string.

  • fontsize (float) – The fontsize for axis labels.

  • legend_fontsize (float) – The fontsize for text in the legend.

  • x_ticks (list) – Customise which major x-axis ticks and labels are on the figure, default is None in which case they are determined automatically.

  • x_minor_ticks (list) – Customise which minor x-axis ticks and labels are on the figure, default is None in which case they are determined automatically.

  • y_ticks (list) – Customise which major y-axis ticks and labels are on the figure, default is None in which case they are determined automatically.

  • y_minor_ticks (list) – Customise which minor y-axis ticks and labels are on the figure, default is None in which case they are determined automatically.

  • save_path (str) – The path where the figure produced by this method should be saved. Default is None, in which case the figure will not be saved.

  • label_points (bool) – If True, and source name information for each point was passed on the declaration of this scaling relation, then points will be accompanied by an index that can be used with the ‘point_names’ property to retrieve the source name for a point. Default is False.

  • point_label_colour (str) – The colour of the label text.

  • point_label_size (int) – The fontsize of the label text.

  • show_third_dim (bool) – Colour the data points by the third dimension data passed in on creation of this scaling relation, with a colour bar to communicate values. Only possible if data were passed to ‘third_dim_info’ on initialization. Default is False.

  • third_dim_cmap (str/Colormap) – The colour map which should be used for the third dimension data points. A matplotlib colour map name or a colour map object may be passed. Default is ‘plasma’. This essentially overwrites the ‘data_colour’ argument if show_third_dim is True.

  • float] point_label_offset (Tuple[float,) – A fractional offset (in display coordinates) applied to the data point coordinates to determine the location a label should be added. You can use this to fine-tune the label positions relative to their data point.

save(save_path)[source]

This method pickles and saves the scaling relation object. The save file is a pickled version of this object.

Parameters

save_path (str) – The path where this relation should be saved.

class xga.products.relation.AggregateScalingRelation(relations)[source]

Bases: object

This class is akin to the BaseAggregateProfile class, in that it is the result of a sum of ScalingRelation objects. References to the component objects will be stored within the structure of this class, and it primarily exists to allow plots with multiple relations to be generated.

Parameters

relations (List[ScalingRelation]) – A list of scaling relations objects to be combined in this object.

property relations

This returns the list of ScalingRelation instances that make up this aggregate scaling relation.

Returns

A list of ScalingRelation instances.

Return type

List[ScalingRelation]

property x_unit

The astropy unit object relevant to the x-axis of this relation.

Returns

An Astropy Unit object.

Return type

Unit

property y_unit

The astropy unit object relevant to the y-axis of this relation.

Returns

An Astropy Unit object.

Return type

Unit

view_corner(figsize=10, 10, cust_par_names=None, contour_colours=None, save_path=None)[source]

A corner plot viewing method that will combine chains from all the relations that make up this aggregate scaling relation and display them using getdist.

Parameters
  • figsize (tuple) – The size of the figure.

  • cust_par_names (List[str]) – A list of custom parameter names. If the names include LaTeX code do not include $$ math environment symbols - you may also need to pass a string literal (e.g. r”sigma”). Do not include an entry for a scatter parameter.

  • contour_colours (List[str]) – Custom colours for the contours, there should be one colour per scaling relation.

  • save_path (str) – The path where the figure produced by this method should be saved. Default is None, in which case the figure will not be saved.

view(x_lims=None, log_scale=True, plot_title=None, figsize=10, 8, colour_list=None, grid_on=False, conf_level=90, show_data=True, fontsize=15, legend_fontsize=13, x_ticks=None, x_minor_ticks=None, y_ticks=None, y_minor_ticks=None, save_path=None, data_colour_list=None, data_shape_list=None, custom_x_label=None, custom_y_label=None)[source]

A method that produces a high quality plot of the component scaling relations in this AggregateScalingRelation.

Parameters
  • x_lims (Quantity) – If not set, this method will attempt to take appropriate limits from the x-data this relation is based upon, if that data is not available an error will be thrown.

  • log_scale (bool) – If true then the x and y axes of the plot will be log-scaled.

  • plot_title (str) – A custom title to be used for the plot, otherwise one will be generated automatically.

  • figsize (tuple) – A custom figure size for the plot, default is (8, 8).

  • colour_list (list) – A list of matplotlib colours to use as a custom colour cycle.

  • grid_on (bool) – If True then a grid will be included on the plot. Default is True.

  • conf_level (int) – The confidence level to use when plotting the model.

  • show_data (bool) – Controls whether data points are shown on the view, as it can quickly become confusing with multiple relations on one axis.

  • fontsize (float) – The fontsize for axis labels.

  • legend_fontsize (float) – The fontsize for text in the legend.

  • x_ticks (list) – Customise which major x-axis ticks and labels are on the figure, default is None in which case they are determined automatically.

  • x_minor_ticks (list) – Customise which minor x-axis ticks and labels are on the figure, default is None in which case they are determined automatically.

  • y_ticks (list) – Customise which major y-axis ticks and labels are on the figure, default is None in which case they are determined automatically.

  • y_minor_ticks (list) – Customise which minor y-axis ticks and labels are on the figure, default is None in which case they are determined automatically.

  • save_path (str) – The path where the figure produced by this method should be saved. Default is None, in which case the figure will not be saved.

  • data_colour_list (list) – A list of matplotlib colours to use as a colour cycle specifically for data points. This should be used when you want data points to be a different colour to their model.

  • data_shape_list (list) – A list of matplotlib format shapes, to manually set the shapes of plotted data points.

  • custom_x_label (str) – Passing a string to this variable will override the x-axis label of this plot, including the unit string.

  • custom_y_label (str) – Passing a string to this variable will override the y-axis label of this plot, including the unit string.

products.spec module

class xga.products.spec.Spectrum(path, rmf_path, arf_path, b_path, central_coord, inn_rad, out_rad, obs_id, instrument, grouped, min_counts, min_sn, over_sample, stdout_str, stderr_str, gen_cmd, region=False, b_rmf_path='', b_arf_path='')[source]

Bases: xga.products.base.BaseProduct

This class is the XGA product responsible for storing an individual spectrum. Various qualities that can be measured from it (X-ray luminosity for example) can be associated with an instance of this object, as well as conversion factors that can be calculated from XSPEC. If a model has been fitted then the data and model can be viewed.

Parameters
  • path (str) – The path to the spectrum file.

  • rmf_path (str) – The path to the RMF generated for the spectrum file.

  • arf_path (str) – The path to the ARF generated for the spectrum file.

  • b_path (str) – The path to the background spectrum generated for the spectrum file.

  • central_coord (Quantity) – The central coordinate of the spectrum region.

  • inn_rad (Quantity) – The inner radius of the spectrum region.

  • out_rad (Quantity) – The outer radius of the spectrum region.

  • obs_id (str) – The ObsID from which this spectrum was generated.

  • instrument (str) – The instrument which this spectrum was generated.

  • grouped (bool) – Was this spectrum grouped?

  • min_counts (int) – The minimum counts applied for the grouping.

  • min_sn (float) – The minimum signal to noise applied for the grouping.

  • over_sample (int) – Level of oversampling applied to spectrum grouping.

  • stdout_str (str) – The stdout from the generation process.

  • stderr_str (str) – The stderr for the generation process.

  • gen_cmd (str) – The generation command for the spectrum stack.

  • region (bool) – Was this spectrum generated from a region in a region file?

  • b_rmf_path (str) – The path to the RMF generated for the background spectrum (if applicable, XGA no longer generates these by default, as XSPEC does not make use of them).

  • b_arf_path (str) – The path to the ARF generated for the background spectrum (if applicable, XGA no longer generates these by default, as XSPEC does not make use of them).

property header

The SPECTRUM table header of the source spectrum. This property was called header because I suspect this will be more the more useful of the two headers that a Spectrum instance allows you to access.

Return type

FITSHDR

Returns

The SPECTRUM fits table header.

property primary_header

The PRIMARY (overall) header of the source spectrum file.

Return type

FITSHDR

Returns

The PRIMARY (overall) fits file header.

property counts

The array of counts associated with each channel of the spectrum, with a second column containing the Poisson error.

Return type

Quantity

Returns

The counts quantity in units of ‘ct’.

property exposure

The weighted (from individual exposure times of different CCD chips) exposure time of the source spectrum, as used by XSPEC.

Return type

Quantity

Returns

The exposure time for the source spectrum, in units of seconds.

property count_rates

The array of counts/second associated with each channel of the spectrum. This takes the counts property and divides it by the EXPOSURE entry in the spectrum header. A second column containing uncertainty is included.

Return type

Quantity

Returns

The counts/second quantity in units of ‘ct/s’.

property channels

The array of instrument channels in the spectrum.

Return type

Quantity

Returns

An array of channels.

property energies

The array of instrument channels, converted to energy using information from the RMF.

Return type

Quantity

Returns

An array of channel energy midpoints, in keV.

property grouping

The grouping information from the spectrum. A 1 entry indicates the first channel in a group and -1 indicates a member of the current group.

Return type

np.ndarray

Returns

An array of group IDs.

property quality

The quality information from the spectrum. 0 = good quality, 1 is bad quality and 2 means dubious.

Return type

np.ndarray

Returns

An array of quality flags.

property back_header

The SPECTRUM table header of the background spectrum. This property was called header because I suspect this will be more the more useful of the two headers that a Spectrum instance allows you to access.

Return type

FITSHDR

Returns

The SPECTRUM fits table header.

property back_primary_header

The PRIMARY (overall) header of the background spectrum file.

Return type

FITSHDR

Returns

The PRIMARY (overall) fits file header.

property back_counts

The array of counts associated with each channel of the background spectrum, with a second column containing the Poisson error.

Return type

Quantity

Returns

The counts quantity in units of ‘ct’.

property back_exposure

The weighted (from individual exposure times of different CCD chips) exposure time of the background spectrum, as used by XSPEC.

Return type

Quantity

Returns

The exposure time for the background spectrum, in units of seconds.

property back_count_rates

The array of counts/second associated with each channel of the background spectrum. This takes the back_counts property and divides it by the EXPOSURE entry in the background spectrum header. A second column containing uncertainty is included.

Return type

Quantity

Returns

The counts/second quantity in units of ‘ct/s’.

property back_channels

The array of instrument channels in the background spectrum.

Return type

Quantity

Returns

An array of channels.

property back_grouping

The grouping information from the background spectrum

Return type

np.ndarray

Returns

An array of group IDs.

property back_quality

The quality information from the background spectrum. A 0 flag value means good quality, 1 means not good quality.

Return type

np.ndarray

Returns

An array of quality flags.

property eff_area

The discrete effective area curve of the telescope. These area values correspond to upper and lower energy bounds that can be accessed using the eff_area_lo_en and eff_area_hi_en properties

Return type

Quantity

Returns

A quantity containing the effective area values in units of cm^-2.

property eff_area_lo_en

The lower energy bounds for the effective area curve.

Return type

Quantity

Returns

A quantity containing the lower energy bounds for effective area values in units keV.

property eff_area_hi_en

The upper energy bounds for the effective area curve.

Return type

Quantity

Returns

A quantity containing the upper energy bounds for effective area values in units keV.

property rmf_channels

The channels present in the RMF EBOUND table, used for converting between channel and energy when used in conjunction with rmf_channels_lo_en and rmf_channels_hi_en.

Return type

np.ndarray

Returns

A numpy array containing the channels in the EBOUND table.

property rmf_channels_lo_en

The lower energy bounds for the RMF EBOUND channels.

Return type

Quantity

Returns

A quantity containing the lower energy bounds for RMF channels, in units keV.

property rmf_channels_hi_en

The upper energy bounds for the RMF EBOUND channels.

Return type

Quantity

Returns

A quantity containing the upper energy bounds for RMF channels, in units keV.

property rmf_redist_matrix

The contents of the RMF MATRIX table.

Return type

np.ndarray

Returns

A numpy array with names columns.

property path

This method returns the path to the spectrum file of this object.

Returns

The path to the spectrum file associated with this object.

Return type

str

property rmf

This method returns the path to the RMF file of the main spectrum of this object.

Returns

The path to the RMF file associated with the main spectrum of this object.

Return type

str

property arf

This method returns the path to the ARF file of the main spectrum of this object.

Returns

The path to the ARF file associated with the main spectrum of this object.

Return type

str

property background

This method returns the path to the background spectrum.

Returns

Path of the background spectrum.

Return type

str

property background_rmf

This method returns the path to the background spectrum’s RMF file.

Returns

The path the the background spectrum’s RMF.

Return type

str

property background_arf

This method returns the path to the background spectrum’s ARF file.

Returns

The path the the background spectrum’s ARF.

Return type

str

property storage_key

This property returns the storage key which this object assembles to place the Spectrum in an XGA source’s storage structure. The key is based on the properties of the spectrum, and some of the configuration options, and is basically human readable.

Returns

String storage key.

Return type

str

property central_coord

This property provides the central coordinates (RA-Dec) of the region that this spectrum was generated from.

Returns

Astropy quantity object containing the central coordinate in degrees.

Return type

Quantity

property shape

Returns the shape of the outer edge of the region this spectrum was generated from.

Returns

The shape (either circular or elliptical).

Return type

str

property inner_rad

Gives the inner radius (if circular) or radii (if elliptical - semi-major, semi-minor) of the region in which this spectrum was generated.

Returns

The inner radius(ii) of the region.

Return type

Quantity

property outer_rad

Gives the outer radius (if circular) or radii (if elliptical - semi-major, semi-minor) of the region in which this spectrum was generated.

Returns

The outer radius(ii) of the region.

Return type

Quantity

property grouped

A property stating whether SAS was told to group this spectrum during generation or not.

Returns

Boolean variable describing whether the spectrum is grouped or not

Return type

bool

property grouped_on

A property stating what metric this spectrum was grouped on.

Returns

String representation of the metric this spectrum was grouped on (None if not grouped).

Return type

str

property min_counts

A property stating the minimum number of counts allowed in a grouped channel.

Returns

The integer minimum number of counts per grouped channel (if this spectrum was grouped on minimum numbers of counts).

Return type

int

property min_sn

A property stating the minimum signal to noise allowed in a grouped channel.

Returns

The minimum signal to noise per grouped channel (if this spectrum was grouped on minimum signal to noise).

Return type

Union[float, int]

property over_sample

A property string stating the amount of oversampling applied by evselect during the spectrum generation process.

Returns

Oversampling applied during generation

Return type

float

property region

This property states whether this spectrum was generated directly from a region file region or not. If true then this isn’t from any arbitrary radii or an overdensity radius, but instead directly from a source finder.

Returns

A boolean flag describing if this is a region spectrum or not.

Return type

bool

property annulus_ident

This property returns the integer identifier of which annulus in a set this Spectrum is, if it is part of a set.

Returns

Integer annulus identifier, None if not part of a set.

Return type

object

property set_ident

This property returns the random id of the spectrum set this is a part of.

Returns

Set identifier, None if not part of a set.

Return type

int

add_fit_data(model, tab_line, plot_data)[source]

Method that adds information specific to a spectrum from an XSPEC fit to this object. This includes individual spectrum exposure and count rate, as well as calculated luminosities, and plotting information for data and model.

Parameters
  • model (str) – String representation of the XSPEC model fitted to the data.

  • tab_line – The line of the SPEC_INFO table produced by xga_extract.tcl that is relevant to this spectrum object.

  • plot_data (hdu.table.TableHDU) – The PLOT{N} table in the file produced by xga_extract.tcl that is relevant to this spectrum object.

get_luminosities(model, lo_en=None, hi_en=None)[source]

Returns the luminosities measured for this spectrum from a given model.

Parameters
  • model – Name of model to fetch luminosities for.

  • lo_en (Quantity) – The lower energy limit for the desired luminosity measurement.

  • hi_en (Quantity) – The upper energy limit for the desired luminosity measurement.

Returns

Luminosity measurement, either for all energy bands, or the one requested with the energy limit parameters. Luminosity measurements are presented as three column numpy arrays, with column 0 being the value, column 1 being err-, and column 2 being err+.

get_rate(model)[source]

Fetches the count rate for a particular model fitted to this spectrum.

Parameters

model – The model to fetch count rate for.

Returns

Count rate in counts per second.

Return type

Quantity

add_conv_factors(lo_ens, hi_ens, rates, lums, model)[source]

Method used to store countrate to luminosity conversion factors derived from fakeit spectra, as well as the actual countrate and luminosity measured in case the user wants to create a combined factor for multiple observations.

Parameters
  • lo_ens (np.ndarray) – A numpy array of string representations of the lower energy bounds for the cntrate and luminosity measurements.

  • hi_ens (np.ndarray) – A numpy array of string representations of the upper energy bounds for the cntrate and luminosity measurements.

  • rates (np.ndarray) – A numpy array of the rates measured for this arf/rmf combination for the energy ranges specified in lo_ens and hi_end.

  • lums (np.ndarray) – A numpy array of the luminosities measured for this arf/rmf combination for the energy ranges specified in lo_ens and hi_end.

  • model (str) – The name of the model used to calculate this factor.

get_conv_factor(lo_en, hi_en, model)[source]

Retrieves a conversion factor between count rate and luminosity for a given energy range, if one has been calculated.

Parameters
  • lo_en (Quantity) – The lower energy bound for the desired conversion factor.

  • hi_en (Quantity) – The upper energy bound for the desired conversion factor.

  • model (str) – The model used to generate the desired conversion factor.

Returns

The conversion factor, luminosity, and rate for the supplied model-energy combination.

Return type

Tuple[Quantity, Quantity, Quantity]

get_plot_data(model)[source]

Simply grabs the plot data dictionary for a given model, if the spectrum has had a fit performed on it.

Parameters

model (str) –

Returns

All information required to plot the data and model.

Return type

dict

conv_channel_energy(to_convert)[source]

This method will use RMF information to convert between channels and energy, and vice versa. If converting from channel to energy, the return will be the midpoint of the energy bin associated with that channel.

Parameters

to_convert (Quantity) – The input Quantity, either with units of energy, or no units (which will be taken to mean channels). Any channel input will be converted to an integer, floats are not valid.

Return type

Quantity

Returns

The converted value, either as a channel (for energy input) or an energy (for channel input).

get_grouped_data(count_rate=True)[source]

In many cases a spectrum is ‘grouped’ after generation, which involves combining sequential channels to increase the signal-to-noise. This method reads any grouping information in the spectrum associated with this object and returns the grouped data, along with everything necessary to use it. The properties that return counts, energy bins etc all give the raw data, unlike this method.

The spectrum quality information is used to filter the spectrum before grouping is applied, only channels with a quality flag of 0 are accepted.

Parameters

count_rate (bool) – Should the grouped spectrum data be returned as a count-rate, default is True. If set to False then grouped data will be returned as counts.

Return type

Tuple[Quantity, Quantity, Quantity, Quantity, Quantity, Quantity]

Returns

The source count-rates (or counts) with uncertainties, the background count-rates (or counts) with uncertainties, the lower energy bounds of the groups, the upper energy bounds of the groups, the channel midpoints of the groups (with width in a second column), the energy midpoints of the groups (with width in a second column).

view_arf(figsize=(8, 6), xscale='log', yscale='linear', lo_en=<Quantity 0.01 keV>, hi_en=<Quantity 16. keV>)[source]

Plots the response curve for this spectrum.

Parameters
  • figsize (tuple) – The desired size of the output figure.

  • xscale (str) – The xscale to use for the plot.

  • yscale (str) – The yscale to use for the plot.

  • lo_en (Quantity) – The lower energy limit for the x-axis. The default is 0.01 keV. This will be altered to reflect the minimum value of the energy scale for this curve if lo_en is smaller than the lowest energy bin.

  • hi_en (Quantity) – The upper energy limit for the x-axis. The default is 16.0 keV. This will be altered to reflect the maximum value of the energy scale for this curve if hi_en is greater than the highest energy bin.

view(figsize=(10, 7), lo_lim=<Quantity 0.3 keV>, hi_lim=<Quantity 7.9 keV>, back_sub=True, energy=True, src_colour='black', bck_colour='firebrick', grouped=True, xscale='log', yscale='linear', fontsize=14, show_model_fits=True, save_path=None)[source]

A method for viewing the data associated with this Spectrum instance.

A spectrum can be viewed prior to fitting, and this method will produce plots that should be the same as the XSPEC count/s/keV (or channel) spectrum views. If a model has been fit, and the user wishes to display it, then the ‘normalised count/s/keV’ that are plotted are extracted from the XSPEC data, rather than assembled in this method.

Parameters
  • figsize (tuple) – The desired size of the output figure, default is (10, 7).

  • lo_lim (Quantity) – The lower limit applied to the plot, either a unitless Quantity (representing channels) or an energy Quantity. Limits will be automatically converted to the units of the x-axis. Default is 0.3 keV, matching the default lower limit of the XGA implementation of XSPEC fitting.

  • hi_lim (Quantity) – The upper limit applied to the plot, either a unitless Quantity (representing channels) or an energy Quantity. Limits will be automatically converted to the units of the x-axis. Default is 7.9 keV, matching the default lower limit of the XGA implementation of XSPEC fitting.

  • back_sub (bool) – Whether the plotted data should have their background subtracted, default is True.

  • energy (bool) – Controls whether the x-axis is in units of energy, default is True. If False then channels are plotted instead.

  • src_colour (str) – The colour in which to plot the source spectrum. Default is ‘black’.

  • bck_colour (str) – The colour in which to plot the background spectrum. Default is ‘firebrick’ red.

  • grouped (bool) – Whether the grouped spectrum should be plotted, default is True. If the spectrum has not been grouped then this be automatically set to False.

  • xscale (str) – The scaling to be applied to the x-axis, default is ‘log’.

  • yscale (str) – The scaling to be applied to the y-axis, default is ‘linear’.

  • fontsize (int/float) – The fontsize for axis labels. The legend fontsize will be fontsize - 1. The title fontsize will be fontsize + 1. Default is 14.

  • show_model_fits (bool) – Whether any models fit to the spectrum by XSPEC should be shown. Default is True, but will be set to False if no fits have been performed.

  • save_path (str) – The path where the figure produced by this method should be saved. Default is None, in which case the figure will not be saved.

class xga.products.spec.AnnularSpectra(spectra)[source]

Bases: xga.products.base.BaseAggregateProduct

A class designed to hold a set of XGA spectra generated in concentric, circular annuli.

Parameters

spectra (List[Spectrum]) – A list of XGA spectrum objects which make up this set.

property src_name

Method to return the name of the object a product is associated with. The product becomes aware of this once it is added to a source object.

Returns

The name of the source object this product is associated with.

Return type

str

property central_coord

This property provides the central coordinates (RA-Dec) that this set of spectra was generated around.

Returns

Astropy quantity object containing the central coordinate in degrees.

Return type

Quantity

property num_annuli

A property getter for the number of annular spectra.

Returns

The number of annular spectra associated with this product.

Return type

int

property annulus_ids

The set of annulus IDs for this AnnularSpectra; i.e. for an AnnularSpectra with 4 annuli, this will return an array of 0, 1, 2, and 3.

Returns

The array of annulus IDs.

Return type

np.ndarray

background(obs_id, inst)[source]

This method returns the path to the background spectrum for a particular ObsID and instrument. It is the background associated with the outermost annulus of this object.

Parameters
  • obs_id (str) – The ObsID to get the background spectrum for.

  • inst (str) – The instrument to get the background spectrum for.

Returns

Path of the background spectrum.

Return type

str

background_rmf(obs_id, inst)[source]

This method returns the path to the background spectrum’s RMF for a particular ObsID and instrument. It is the RMF of the background associated with the outermost annulus of this object.

Parameters
  • obs_id (str) – The ObsID to get the background spectrum’s RMF for.

  • inst (str) – The instrument to get the background spectrum’ RMF for.

Returns

Path of the background spectrum RMF.

Return type

str

background_arf(obs_id, inst)[source]

This method returns the path to the background spectrum’s ARF for a particular ObsID and instrument. It is the ARF of the background associated with the outermost annulus of this object.

Parameters
  • obs_id (str) – The ObsID to get the background spectrum’s ARF for.

  • inst (str) – The instrument to get the background spectrum’ ARF for.

Returns

Path of the background spectrum ARF.

Return type

str

property obs_ids

A property of this spectrum set that details which ObsIDs have contributed spectra to this object.

Returns

A list of ObsIDs.

containing instruments associated with those ObsIDs. :rtype: dict

property instruments

A property of this spectrum set that details which ObsIDs and instruments have contributed spectra to this object.

Returns

A dictionary of lists, with the top level keys being ObsIDs, and the lists

containing instruments associated with those ObsIDs. :rtype: dict

get_spectra(annulus_ident, obs_id=None, inst=None)[source]

This is the getter for the spectra stored in the AnnularSpectra data storage structure. They can be retrieved based on annulus identifier, ObsID, and instrument.

Parameters
  • annulus_ident (int) – The annulus identifier to retrieve spectra for.

  • obs_id (str) – Optionally, a specific obs_id to search for can be supplied.

  • inst (str) – Optionally, a specific instrument to search for can be supplied.

Returns

List of matching spectra, or just a Spectrum object if one match is found.

Return type

Union[List[Spectrum], Spectrum]

property all_spectra

Simple extra wrapper for get_spectra that allows the user to retrieve every single spectrum associated with this AnnularSpectra instance, for all annulus IDs.

Returns

A list of every single spectrum associated with this object.

Return type

List[Spectrum]

property radii

A property to return all the boundary radii of the constituent annuli.

Returns

Astropy quantity of the radii.

Return type

Quantity

property annulus_centres

Returns the centres of all the annuli, in the original units the radii were passed in with.

Returns

An astropy quantity containing radii.

Return type

Quantity

property proper_radii

A property to return the boundary radii of the constituent annuli in kpc. This has to be set using the setter first, otherwise the value is None.

Returns

Astropy quantity of the proper radii.

Return type

Quantity

property proper_annulus_centres

Returns the centres of all the annuli, in the units of proper radii which the user has to have set through the property setter.

Returns

An astropy quantity containing radii, or None if no proper radii exist

Return type

Quantity

property set_ident

This property returns the ID of this set of spectra.

Returns

The integer ID of this set.

Return type

int

property storage_key

This property returns the storage key which this object assembles to place the AnnularSpectra in an XGA source’s storage structure. The key is based on the properties of the AnnularSpectra, and some of the configuration options, and is basically human readable.

Returns

String storage key.

Return type

str

property grouped

A property stating whether SAS was told to group the spectra in this set during generation or not.

Returns

Boolean variable describing whether the spectra are grouped or not

Return type

bool

property grouped_on

A property stating what metric the spectra in this set were grouped on.

Returns

String representation of the metric the spectra were grouped on (None if not grouped).

Return type

str

property min_counts

A property stating the minimum number of counts allowed in a grouped channel for the spectra in this set.

Returns

The integer minimum number of counts per grouped channel (if these spectra were grouped on minimum numbers of counts).

Return type

int

property min_sn

A property stating the minimum signal to noise allowed in a grouped channel for the spectra in this set.

Returns

The minimum signal to noise per grouped channel (if these spectra were grouped on minimum signal to noise).

Return type

Union[float, int]

property over_sample

A property string stating the amount of oversampling applied by evselect during the generation of the spectra in this set. e.g. if over_sample=3 then the minimum width of a group is 1/3 of the resolution FWHM at that energy.

Returns

Oversampling applied during generation.

Return type

float

add_cross_arf(arf, obs_id, inst, src_ann_id, cross_ann_id, set_ident)[source]

This method allows you to add cross-arfs generated for this annular spectrum to a storage structure in the object. That means that other processes that make use of them, such as spectral fitting, will be able to retrieve them from this object easily.

Parameters
  • arf (BaseProduct/str) – Either an XGA BaseProduct instance (which is what is produced by the generation process) or a string path to the cross-arf file. This should represent the ‘cross_ann_id’ contribution to the ‘src_ann_id’ spectrum.

  • obs_id (str) – The ObsID of the cross-arf - if ‘arf’ is a BaseProduct instance this argument will be compared the ObsID of the ‘arf’ object. It will also be checked to ensure that it is associated with this object.

  • inst (str) – The instrument of the cross-arf - if ‘arf’ is a BaseProduct instance this argument will be compared the instrument of the ‘arf’ object. It will also be checked to ensure that it is associated with the ObsID in this object.

  • src_ann_id (int) – The identifying number of the source annulus for this cross-arf.

  • cross_ann_id (int) – The identifying number of the ‘cross’ annulus for this cross-arf.

  • set_ident (int) – The set_ident that the cross-arf was generated for, it is checked against the set identifier of this object.

get_cross_arf_paths(obs_id, inst, src_ann_id, cross_ann_id=None)[source]

This method allows the user to retrieve cross-arf paths for a specific ObsID-instrument spectrum of an annulus. For instance, passing an ObsID and Instrument, along with a src_ann_id of 1, to an annular spectrum with four annuli, will return the paths to cross-arfs between annulus 1 and 0, annulus 1 and 2, and annulus 1 and 3 (labelling starts at zero). If a cross_ann_id is passed in addition to a src_ann_id, then that specific path will be retrieved (but still returned in a dictionary).

Parameters
  • obs_id (str) – The ObsID of the spectrum for which you wish to retrieve cross-arf paths.

  • inst (str) – The instrument of the spectrum for which you wish to retrieve cross-arf paths.

  • src_ann_id (int) – The annulus ID (e.g. 1) of the spectrum you wish to retrieve cross-arf paths for.

  • cross_ann_id (int) – Optionally you can specify the cross-arf annulus ID. The default is None, in which case all cross-arf paths for the given source annulus will be returned.

Returns

A dictionary with annulus IDs as keys, and cross-arf paths as values.

Return type

dict

get_cross_arf_lo_ens(obs_id, inst, src_ann_id, cross_ann_id=None)[source]

A method that will retrieve the lower energy bound data from cross-arfs associated with this annular spectrum. A set of cross-arf lower energy bounds can be retrieved for a particular source annulus, or an individual cross-arf for a particular source annulus, depending on user input. It is extremely likely that all lower energy bounds will be the same for a given instrument, but this is not assumed.

Parameters
  • obs_id (str) – The ObsID of the spectrum for which you wish to retrieve cross-arf lower energy bounds.

  • inst (str) – The instrument of the spectrum for which you wish to retrieve cross-arf lower energy bounds.

  • src_ann_id (int) – The annulus ID (e.g. 1) of the spectrum you wish to retrieve cross-arf lower energy bounds for.

  • cross_ann_id (int) – Optionally you can specify the cross-arf annulus ID. The default is None, in which case all lower energy bounds of cross-arfs for the given source annulus will be returned.

Returns

A dictionary with annulus IDs as keys, and astropy array quantities of lower energy bounds as values.

Return type

dict

get_cross_arf_hi_ens(obs_id, inst, src_ann_id, cross_ann_id=None)[source]

A method that will retrieve the upper energy bound data from cross-arfs associated with this annular spectrum. A set of cross-arf upper energy bounds can be retrieved for a particular source annulus, or an individual cross-arf for a particular source annulus, depending on user input. It is extremely likely that all upper energy bounds will be the same for a given instrument, but this is not assumed.

Parameters
  • obs_id (str) – The ObsID of the spectrum for which you wish to retrieve cross-arf upper energy bounds.

  • inst (str) – The instrument of the spectrum for which you wish to retrieve cross-arf upper energy bounds.

  • src_ann_id (int) – The annulus ID (e.g. 1) of the spectrum you wish to retrieve cross-arf upper energy bounds for.

  • cross_ann_id (int) – Optionally you can specify the cross-arf annulus ID. The default is None, in which case all upper energy bounds of cross-arfs for the given source annulus will be returned.

Returns

A dictionary with annulus IDs as keys, and astropy array quantities of upper energy bounds as values.

Return type

dict

get_cross_arf_eff_areas(obs_id, inst, src_ann_id, cross_ann_id=None)[source]

A method that will retrieve the effective area data from cross-arfs associated with this annular spectrum. A set of cross-arf effective areas can be retrieved for a particular source annulus, or an individual cross-arf for a particular source annulus, depending on user input.

Parameters
  • obs_id (str) – The ObsID of the spectrum for which you wish to retrieve cross-arf effective areas.

  • inst (str) – The instrument of the spectrum for which you wish to retrieve cross-arf effective areas.

  • src_ann_id (int) – The annulus ID (e.g. 1) of the spectrum you wish to retrieve cross-arf effective areas for.

  • cross_ann_id (int) – Optionally you can specify the cross-arf annulus ID. The default is None, in which case all effective areas of cross-arfs for the given source annulus will be returned.

Returns

A dictionary with annulus IDs as keys, and astropy array quantities of effective areas as values.

Return type

dict

add_fit_data(model, tab_line, lums, obs_order)[source]

An equivalent to the add_fit_data method built into all source objects. The final fit results and luminosities are housed in a storage structure within the AnnularSpectra, which makes sense because this is an aggregate product of all the relevant spectra, storing them just as source objects store spectra that don’t exist in a spectrum set.

Parameters
  • model (str) – The XSPEC definition of the model used to perform the fit. e.g. constant*tbabs*apec

  • tab_line – A dictionary of table lines with fit data, the keys of the dictionary being the relevant annulus ID for the fit.

  • lums (dict) – A dictionary of the luminosities measured during the fits, the keys of the outermost dictionary being annulus IDs, and the luminosity dictionaries being energy based.

  • obs_order (dict) – A dictionary (with keys being annuli idents) of lists of lists describing the order the data is being passed, so that specific results can be related back to specific observations later (if applicable). The lists should be structured like [[obsid1, inst1], [obsid1, inst2], [obsid1, inst3]] for instance.

get_results(annulus_ident, model, par=None)[source]

Important method that will retrieve fit results from the AnnularSpectra object. Either for a specific parameter of the supplied model combination, or for all of them. If a specific parameter is requested, all matching values from the fit will be returned in an N row, 3 column numpy array (column 0 is the value, column 1 is err-, and column 2 is err+). If no parameter is specified, the return will be a dictionary of such numpy arrays, with the keys corresponding to parameter names.

Parameters
  • annulus_ident (int) – The annulus for which you wish to retrieve the fit results.

  • model (str) – The name of the fitted model that you’re requesting the results from (e.g. constant*tbabs*apec).

  • par (str) – The name of the parameter you want a result for.

Returns

The requested result value, and uncertainties.

get_luminosities(annulus_ident, model, lo_en=None, hi_en=None)[source]

This will retrieve luminosities of specific annuli from fits performed on this AnnularSpectra object. A model name must be supplied, and if a luminosity from a specific energy range is desired then lower and upper energy bounds may be passed.

Parameters
  • annulus_ident (int) – The annulus for which you wish to retrieve the luminosities.

  • model (str) – The name of the fitted model that you’re requesting the results from (e.g. constant*tbabs*apec).

  • lo_en (Quantity) – The lower energy limit for the desired luminosity measurement.

  • hi_en (Quantity) – The upper energy limit for the desired luminosity measurement.

Returns

The requested luminosity value, and uncertainties. If a specific energy range has been supplied then a quantity containing the value (col 1), -err (col 2), and +err (col 3), will be returned. If no energy range is supplied then a dictionary of all available luminosity quantities will be returned.

Return type

Union[Quantity, Dict[str, Quantity]]

generate_profile(model, par, par_unit, upper_limit=None)[source]

This generates a radial profile of the requested fit parameter using the stored results from an XSPEC model fit run on this AnnularSpectra. The profile is added to AnnularSpectra internal storage, and also returned to the user.

Parameters
  • model (str) – The name of the fitted model you wish to generate a profile from.

  • par (str) – The name of the free model parameter that you wish to generate a profile for.

  • par_unit (Unit/str) – The unit of the free model parameter as an astropy unit object, or a string representation (e.g. keV).

  • upper_limit (Quantity) – Allows an allowed upper limit for the y values in the profile to be passed.

Returns

The requested profile object.

Return type

Union[BaseProfile1D, ProjectedGasTemperature1D, ProjectedGasMetallicity1D]

view_cross_arfs(src_ann_id, obs_id, inst, src_arf_norm=False, figsize=(8, 6), xscale='log', yscale='linear', lo_en=<Quantity 0.01 keV>, hi_en=<Quantity 16. keV>)[source]

A method that produces a plot of the cross-arf curves for a specified source annulus spectrum, for a specified ObsID and instrument. The original source spectrum will also be plotted as a reference. This method can also be used to create ‘normalized’ curves were the cross-arf effective area values are divided by the source arf effective areas.

Parameters
  • src_ann_id (int) – The annulus ID of the source annulus for which you wish to plot cross-arf curves.

  • obs_id (str) – The ObsID of the spectrum for which you wish to plot cross-arf curves.

  • inst (str) – The instrument of the spectrum for which you wish to plot cross-arf curves.

  • src_arf_norm (bool) –

  • figsize (tuple) – The size of the figure, the default is (8, 6).

  • xscale (str) – The xscale to use for the plot.

  • yscale (str) – The yscale to use for the plot.

  • lo_en (Quantity) – The lower energy limit for the x-axis. The default is 0.01 keV. This will be altered to reflect the minimum value of the energy scale for this curve if lo_en is smaller than the lowest energy bin.

  • hi_en (Quantity) – The upper energy limit for the x-axis. The default is 16.0 keV. This will be altered to reflect the maximum value of the energy scale for this curve if hi_en is greater than the highest energy bin.

view_annulus(ann_ident, model, figsize=12, 8)[source]

An equivalent to the Spectrum view method, but allows all spectra from the same annulus to be displayed on the same axis.

Parameters
  • ann_ident (int) – The integer identifier of the annulus you wish to see spectra for.

  • model (str) – The fitted model to display on the data.

  • figsize (tuple) – The size of the plot.

view_annuli(obs_id, inst, model, figsize=12, 8, elevation_angle=30, azimuthal_angle=- 60)[source]

This view method is one of several in the AnnularSpectra class, and will display data and associated model fits for a single ObsID-Instrument combination for all annuli in this AnnularSpectra, in a 3D plot. The output of this can be quite visually confusing, so you may wish to use view_annulus to see the spectrum of a particular annulus for a particular ObsID-Instrument in a more traditional way, or just view to see all model fits at all annuli.

Parameters
  • obs_id (str) – The ObsID of the spectra to display.

  • inst (str) – The instrument of the spectra to display.

  • model (str) – The model fit to display

  • figsize (tuple) – The size of the figure.

  • elevation_angle (int) – The elevation angle in the z plane, in degrees.

  • azimuthal_angle (int) – The azimuth angle in the x,y plane, in degrees.

view(model, figsize=12, 8, elevation_angle=30, azimuthal_angle=- 60)[source]

This view method is one of several in the AnnularSpectra class, and will display model fits to all spectra for each annuli in a 3D plot. No data is displayed in this viewing method, primarily because its so visually confusing. If you wish to see model fits displayed over actual data in this style, please use view_annuli.

Parameters
  • model (str) – The model fit to display

  • figsize (tuple) – The size of the figure.

  • elevation_angle (int) – The elevation angle in the z plane, in degrees.

  • azimuthal_angle (int) – The azimuth angle in the x,y plane, in degrees.