products

products.base module

class xga.products.base.BaseProduct(path, obs_id, instrument, stdout_str, stderr_str, gen_cmd, extra_info=None, telescope=None, force_remote=False, fsspec_kwargs=None, check_exists=True)[source]

Bases: object

The super class for all X-ray products in XGA. Stores relevant file path information, ObsID, instrument, and telescope. It can also parse the std_err output of some generation processes into specific errors.

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.

  • telescope (str) – The telescope that this product is derived from. Default is None.

  • force_remote (bool) – Used to force the product instantiation to treat the passed path string as a url to a remote dataset, and to use fsspec to read/stream the data.

  • fsspec_kwargs (dict) – Optional arguments that can be passed fsspec when reading or streaming remote datasets - e.g. to pass credentials to access an S3 bucket. Default value is None, which sets the argument to {“anon”: True}, making it instantly compatible with NASA archive S3 buckets.

  • check_exists (bool) – Controls whether the product instantiation process checks for the file path’s existence or not. Default is True, in which case a check will be performed, but if declaring many products from the same directory/directory structure, it can be more performant to run listdir or scandir and confirm files exist externally, than one by one in each product declaration.

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

property local_file
A file is deemed remote by the presence of certain strings at the beginning of the path, or the

user passing ‘force_remote=True’ at product initialization, otherwise it is considered to be local.

Returns:

Returns a boolean flag describing if we think this product is pointed at a local file (True) or a remote file (False).

Return type:

bool

property force_remote

A property providing the value of the ‘force_remote’ argument passed to this product at instantiation - that value controls how the init treats the file path.

Returns:

The value of ‘force_remote’ argument passed to this product at instantiation.

Return type:

bool

property fsspec_kwargs

Property getter for the attribute containing the fsspec keyword arguments passed to this product at instantiation. These are for passing configuration information such as credentials for the remote access of S3 buckets

Returns:

The fsspec keyword arguments passed to this product at instantiation.

Return type:

dict

parse_stderr()[source]

This method parses the stderr associated with the generation of a product into errors confirmed to have come from a telescope-specific software package (e.g. SAS, or eSASS), and other unidentifiable errors. The telescope-specific errors are returned with the error name, the error message, and the routine that caused the error.

Returns:

A list of dictionaries containing parsed, confirmed telescope-specific errors, another containing telescope-specific warnings, and another list of unidentifiable errors that occurred in the stderr.

Return type:

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

property gen_errors

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

Returns:

The list of confirmed generation errors.

Return type:

List[str]

property gen_warnings

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

Returns:

The list of confirmed generation warnings.

Return type:

List[Dict]

raise_errors()[source]

Method to raise the errors parsed from std_err string.

property telescope

Property getter for the name of the telescope that this product was derived from.

Returns:

The telescope name.

Return type:

str

property pretty_telescope_name

Property getter for a ‘pretty’ version of a telescope name, for inclusion in figure labels, titles, etc. - only if a ‘pretty’ name is defined in xga.utils.

Returns:

The ‘pretty’ version of the telescope name if available, the usual form of the telescope name if not, and None if no telescope name is set.

Return type:

Union[str, None]

property obs_id

Property getter for the ObsID of the observation that this product was derived from.

Returns:

The ObsID of this product.

Return type:

str

property instrument

Property getter for the name of the instrument that this product was derived from.

Returns:

The instrument name of this product.

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-parsed errors detected during the generation of a product.

Returns:

A list of errors that haven’t been successfully linked to a generation process specific to a telescope.

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, telescope=None)[source]

Bases: object

A base class for any XGA products that are an aggregate of a set of XGA products, 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.

  • telescope (str) – The telescope that this product is derived from. Default is None.

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 AggregateProduct. 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 ObsID of this AggregateProduct.

Return type:

str

property instrument

Property getter for the instrument of this AggregateProduct. 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 instrument of this AggregateProduct.

Return type:

str

property telescope

Property getter for the name of the telescope that this product was derived from.

Returns:

The telescope name.

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 gen_errors

Equivelant to the BaseProduct gen_errors property, but reports any telescope software errors stored in the component products.

Returns:

A list of telescope software errors related to component products.

Return type:

List

property errors

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

Returns:

A list of non-telescope software errors related to component products.

Return type:

List

property unprocessed_stderr

Equivelant to the BaseProduct gen_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.>, auto_save=False, telescope=None, spec_model=None, fit_conf=None)[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.

  • auto_save (bool) – Whether the profile should automatically save itself to disk at any point. The default is False, but all profiles generated through XGA processes acting on XGA sources will auto-save.

  • telescope (str) – The telescope that this profile is derived from. Default is None.

  • spec_model (str) – The spectral model that was fit to annular spectra to measure the results that were used to create this profile. Only relevant to profiles that are generated from annular spectra, default is None.

  • fit_conf (str) – The key that describes the fit-configuration used when fitting models to annular spectra to measure the results that were then used to create this profile. Only relevant to profiles that are generated from annular spectra, default is None.

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, force_refit=False)[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).

  • force_refit (bool) – Controls whether the profile will re-run the fit of a model that already has a good model fit stored. The default is False.

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.

remove_model_fit(model, method)[source]

This will remove an existing model fit for a particular fit method.

Parameters:
  • model (str/BaseModel1D) – The model fit to delete.

  • 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=None, 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, default is None, which corresponds to an empty dictionary.

  • 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=None, 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=None, 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/List[str] model_colour:

The matplotlib colour(s) that should be used for plotted model fits (if applicable). Either a single colour name, or a list of colour names, may be passed depending on the number of models that are being plotted - if there are multiple models, and a single colour is passed, the plot will revert to the default matplotlib colour cycler. If a list is passed, those colours will be cycled through instead (if there are insufficient entries for the number of models an error will be raised). The default value is ‘seagreen’.

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=None, 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=None, 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/List[str] model_colour:

The matplotlib colour(s) that should be used for plotted model fits (if applicable). Either a single colour name, or a list of colour names, may be passed depending on the number of models that are being plotted - if there are multiple models, and a single colour is passed, the plot will revert to the default matplotlib colour cycler. If a list is passed, those colours will be cycled through instead (if there are insufficient entries for the number of models an error will be raised). The default value is ‘seagreen’.

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=None, 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=None, 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/List[str] model_colour:

The matplotlib colour(s) that should be used for plotted model fits (if applicable). Either a single colour name, or a list of colour names, may be passed depending on the number of models that are being plotted - if there are multiple models, and a single colour is passed, the plot will revert to the default matplotlib colour cycler. If a list is passed, those colours will be cycled through instead (if there are insufficient entries for the number of models an error will be raised). The default value is ‘seagreen’.

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 auto_save

Whether the profile will automatically save itself at any point (such as after successful model fits).

Returns:

Boolean flag describing whether auto-save is turned on.

Return type:

bool

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 telescope

Property getter for the name of the telescope that this profile was derived from.

Returns:

The telescope name.

Return type:

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 spec_fit_conf

If this profile was generated from an annular spectrum, this property provides the fit-configuration key of the spectral fits that provided the properties used to build it.

Returns:

The spectral fit-configuration key. If the spectral fit configuration key was never set, the return will be None.

Return type:

str

property spec_model

If this profile was generated from an annular spectrum, this property provides the name of the model that was fit to the spectra in order to measure the properties used to build it.

Returns:

The spectral model name. If the spectral model name was never set, the return will be None.

Return type:

str

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

property custom_aggregate_label

This property is a label that should be used in place of the source name associated with this profile when plotting multiple profiles on one axis through an aggregate profile instance.

Returns:

The custom label, default is None.

Return type:

str

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=None, x_norm=False, y_norm=False, x_label=None, y_label=None, save_path=None, draw_vals=None, 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

products.phot module

products.profile module

products.relation module

products.spec module

products.lightcurve module

class xga.products.lightcurve.LightCurve(path, obs_id, instrument, stdout_str, stderr_str, gen_cmd, central_coord, inn_rad, out_rad, lo_en, hi_en, time_bin_size, pattern_expr='', region=False, is_back_sub=True, telescope=None, check_exists=True)[source]

Bases: BaseProduct

This is the XGA LightCurve product class, which is used to interface with X-ray lightcurves generated for a variety of sources. It provides simple access to data and information about the lightcurve, fitting capabilities, and the ability to easily create lightcurve visualisations.

Parameters:
  • path (str) – The path to the lightcurve.

  • obs_id (str) – The ObsID from which this lightcurve was generated.

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

  • 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 lightcurve.

  • central_coord (Quantity) – The central coordinate of the region from which this lightcurve was extracted.

  • inn_rad (Quantity) – The inner radius of the lightcurve region.

  • out_rad (Quantity) – The outer radius of the lightcurve region.

  • lo_en (Quantity) – The lower energy bound for this lightcurve.

  • hi_en (Quantity) – The upper energy bound for this lightcurve.

  • time_bin_size (Quantity) – The time bin size used to generate the lightcurve.

  • pattern_expr (str) – The event selection pattern used to generate the lightcurve.

  • region (bool) – Whether this was generated from a region in a region file

  • is_back_sub (bool) – Whether this lightcurve is background subtracted or not.

  • telescope (str) – The telescope that this product is derived from. Default is None.

  • check_exists (bool) – Controls whether the product instantiation process checks for the file path’s existence or not. Default is True, in which case a check will be performed, but if declaring many products from the same directory/directory structure, it can be more performant to run listdir or scandir and confirm files exist externally, than one by one in each product declaration.

property storage_key

This property returns the storage key which this object assembles to place the LightCurve in an XGA source’s storage structure. The key is based on the properties of the LightCurve, and some 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 light curve 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 light curve 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 light curve 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 light curve was generated.

Returns:

The outer radius(ii) of the region.

Return type:

Quantity

property time_bin_size

Gives the time bin size used to generate the lightcurve.

Returns:

The time bin size used to generate the lightcurve.

Return type:

Quantity

property count_rate

Returns the background-subtracted instrumental-effect-corrected count-rates for this light curve.

Returns:

Background-subtracted instrumental-effect-corrected count-rates, in units of ct/s.

Return type:

Quantity

property count_rate_err

Returns the background-subtracted instrumental-effect-corrected count-rate uncertainties for this light curve.

Returns:

Background-subtracted instrumental-effect-corrected count-rate uncertainties, in units of ct/s.

Return type:

Quantity

property src_count_rate

Returns the source instrumental-effect-corrected count-rates for this light curve.

Returns:

Source instrumental-effect-corrected count-rates, in units of ct/s.

Return type:

Quantity

property src_count_rate_err

Returns the source instrumental-effect-corrected count-rate uncertainties for this light curve.

Returns:

Source instrumental-effect-corrected count-rate uncertainties, in units of ct/s.

Return type:

Quantity

property ref_time

Returns the reference time for this lightcurve, which is what the ‘time’ values are calculated from.

Returns:

An Astropy Time object that defines the reference time for this lightcurve.

Return type:

Time

property time_system

Returns the time system for this lightcurve; e.g. TT or terrestrial time.

Returns:

The time system.

Return type:

str

property time

Returns the time steps that correspond to the count-rates measured for this light curve

Returns:

Background-subtracted and instrumental-effect-corrected count-rate uncertainties, in units of seconds.

Return type:

Quantity

property datetime

Returns the time steps for this light curve, but in a datetime format, and no longer relative to a reference time.

Returns:

The absolute datetimes that the time steps correspond to.

Return type:

np.ndarray(datetime)

property bck_count_rate

Returns the background count-rates for this light curve.

Returns:

Background count-rates, in units of ct/s.

Return type:

Quantity

property bck_count_rate_err

Returns the background count-rate uncertainties for this light curve.

Returns:

Background count-rate uncertainties, in units of ct/s.

Return type:

Quantity

property frac_exp

This should contain the correction factor for which all sensitivity effects (dead time, vignetting) are taken into account - i.e. dividing by this should make lightcurves across different instruments/telescope consistent.

Returns:

Fractional exposure.

Return type:

Quantity

property src_gti

Returns a 2D quantity with start (column 0) and end (column 1) times for the good-time-intervals of the source light curve.

Returns:

A 2D astropy quantity with start (column 0) and end (column 1) times for the source good-time-intervals (in seconds).

Return type:

Quantity

property bck_gti

Returns a 2D quantity with start (column 0) and end (column 1) times for the good-time-intervals of the background light curve.

Returns:

A 2D astropy quantity with start (column 0) and end (column 1) times for the background good-time-intervals (in seconds).

Return type:

Quantity

property start_time

A property getter to access the recorded start time for this light curve.

Returns:

Light curve start time, in seconds.

Return type:

Quantity

property stop_time

A property getter to access the recorded stop time for this light curve.

Returns:

Light curve stop time, in seconds.

Return type:

Quantity

property start_datetime

A property getter to access the recorded start datetime for this light curve.

Returns:

Light curve start datetime.

Return type:

datetime

property stop_datetime

A property getter to access the recorded stop datetime for this light curve.

Returns:

Light curve stop datetime.

Return type:

datetime

property time_assign

A property getter to access the physical location that the assigned times are based on.

Returns:

The TASSIGN entry of the light curve file.

Return type:

str

property header

Property getter allowing access to the main fits header of the light curve.

Returns:

The header of the primary data table (RATE) of the light curve that was read in.

Return type:

FITSHDR

overlap_check(lightcurves)[source]

A simple method which checks whether a passed LightCurve (or list of lightcurves) overlap temporally with this lightcurve.

Parameters:

lightcurves (LightCurve/List[LightCurve]) – A LightCurve, or a list of LightCurves, to check for overlap with this LightCurve.

Return type:

np.ndarray/bool

Returns:

A boolean value (or an array of boolean values if multiple LightCurve instances were passed) which is True if the passed LightCurve temporally overlaps with this one, and False if it does not.

get_data(date_time=False, fracexp_corr=False)[source]

A get method to retrieve the count-rate (and error) and timing data from this LightCurve.

Alternatively, the ‘count_rate’, ‘count_rate_err’, and ‘time’ properties can be used to access the information. This implementation is meant to be analogous to the ‘get_data’ method of the AggregateLightCurve class.

Parameters:
  • date_time (bool) – Whether the time data should be returned as an array of datetimes (not the default), or an Astropy TimeDelta object from the MJD reference time defined in the file header.

  • fracexp_corr (bool) – Controls whether the data should be corrected for vignetting and deadtime effects by dividing by the ‘FRACEXP’ entry in the lightcurve. Default is False.

Returns:

The count rate data, count rate uncertainty data, and time data.

Return type:

Tuple[Quantity, Quantity, Union[TimeDelta, np.ndarray]]

get_view(ax, time_unit=Unit('s'), lo_time_lim=None, hi_time_lim=None, colour='black', plot_sep=False, src_colour='tab:cyan', bck_colour='firebrick', custom_title=None, label_font_size=15, title_font_size=18, highlight_bad_times=True, fracexp_corr=False, alpha=0.8)[source]

A method that allows the user to retrieve a populated lightcurve visualisation axes, in a form that allows them to then add their own plots in additon to what has been automatically constructed. This is an alternative to the view method, which calls this method and then displays the visualisation as constructed here.

Parameters:
  • ax (Axes) – The matplotlib axes that should be populated with a lightcurve visualization.

  • time_unit (str/Unit) – The unit to be used for the time axis.

  • lo_time_lim (Quantity) – The lower x-limit (i.e. lower time limit) of the data to be displayed.

  • hi_time_lim (Quantity) – The upper x-limit (i.e. upper time limit) of the data to be displayed.

  • colour (str) – The colour to be used to plot data points (if background and source lightcurves are not plotted separately).

  • plot_sep (bool) – Should the source and background lightcurves be plotted separately. Default is False.

  • src_colour (str) – The colour to be used to plot source lightcurve data points, if plot_sep is True.

  • bck_colour (str) – The colour to be used to plot background lightcurve data points, if plot_sep is True.

  • custom_title (str) – A title to be added to the axes, which would override the automatically constructed figure title.

  • label_font_size (int) – The fontsize to be used for labels.

  • title_font_size (int) – The fontsize to be used for the title.

  • highlight_bad_times (bool) – Should periods of time that are NOT within a GTI be highlighted? Default is True.

  • fracexp_corr (bool) – Controls whether the plotted data should be corrected for vignetting and deadtime effects by dividing by the ‘FRACEXP’ entry in the lightcurve. Default is False.

  • alpha (float) – The alpha value to be used for the plotted data. Default is 0.8.

Returns:

The input Axes, but populated with a lightcurve visualisation.

Return type:

Axes

view(figsize=(14, 6), time_unit=Unit('s'), lo_time_lim=None, hi_time_lim=None, colour='black', plot_sep=False, src_colour='tab:cyan', bck_colour='firebrick', custom_title=None, label_font_size=15, title_font_size=18, highlight_bad_times=True, fracexp_corr=False, alpha=0.8)[source]

A method that creates and displays a visualisation of this lightcurve.

Parameters:
  • figsize (tuple) – The figure size to use for this lightcurve visualisation.

  • time_unit (str/Unit) – The unit to be used for the time axis.

  • lo_time_lim (Quantity) – The lower x-limit (i.e. lower time limit) of the data to be displayed.

  • hi_time_lim (Quantity) – The upper x-limit (i.e. upper time limit) of the data to be displayed.

  • colour (str) – The colour to be used to plot data points (if background and source lightcurves are not plotted separately).

  • plot_sep (bool) – Should the source and background lightcurves be plotted separately. Default is False.

  • src_colour (str) – The colour to be used to plot source lightcurve data points, if plot_sep is True.

  • bck_colour (str) – The colour to be used to plot background lightcurve data points, if plot_sep is True.

  • custom_title (str) – A title to be added to the axes, which would override the automatically constructed figure title.

  • label_font_size (int) – The fontsize to be used for labels.

  • title_font_size (int) – The fontsize to be used for the title.

  • highlight_bad_times (bool) – Should periods of time that are NOT within a GTI be highlighted? Default is True.

  • fracexp_corr (bool) – Controls whether the plotted data should be corrected for vignetting and deadtime effects by dividing by the ‘FRACEXP’ entry in the lightcurve. Default is False.

  • alpha (float) – The alpha value to be used for the plotted data. Default is 0.8.

class xga.products.lightcurve.AggregateLightCurve(lightcurves)[source]

Bases: BaseAggregateProduct

The init method for the AggregateLightCurve class, performs checks and organises the light-curves which have been passed in, for easy retrieval. It also allows for analysis to be performed on the combined data, and for visualisations to be created.

This class is designed to package light-curves generated for the same source, with the same settings, and for the same energy bounds - if interested in the time varying behaviours of multiple energy bands then the HardnessCurve and AggregateHardnessCurve products should be used. It can take light-curves from different instruments, and will deal with them simultaneously rather than stacking them.

Light curves that are part of an AggregateLightCurve will be separated into ‘time chunks’, where a time chunk is a period that has uninterrupted coverage. For instance, three XMM observations separated by a year each would be in three different time chunks, but if there were a fourth observation that was taken by another telescope and happened concurrently (even if it didn’t start and end at the same time) with the first XMM observation, then it would be in the same time chunk.

Parameters:

lightcurves (Union[List[LightCurve], np.ndarray]) – A list or array of LightCurve objects that are to be collated in an AggregateLightCurve. These must be for the same source, and generated with the same settings.

property obs_ids

A property of this spectrum set that details which ObsIDs of which telescopes have contributed lightcurves to this object.

Returns:

A dictionary where the keys are telescope names and the values are lists of ObsIDs

Return type:

dict

property instruments

A property of this aggregate light curve that details which ObsIDs and instruments of which telescopes have contributed lightcurves to this object. The top level keys are telescopes, lower level keys are ObsIDs, and the values are lists of instruments.

Returns:

A dictionary where the top level keys are telescopes, the lower level keys are ObsIDs, and their values are lists of related instruments.

Return type:

dict

property associated_instruments

Returns a dictionary containing unique instrument names associated with each telescope, for the constituent light curves of this AggregateLightCurve.

NOTE - there is no guarantee that the instruments of a telescope are associated with a light curve in every time chunk.

Returns:

Dictionary with telescope names as keys, and lists of unique associated instruments as values.

Return type:

dict

property telescopes

Property getter for telescopes that are associated with this aggregate light curve.

Returns:

A list of telescope names with valid data related to this aggregate light curve.

Return type:

List[str]

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 all_lightcurves

Simple extra wrapper for get_lightcurve that allows the user to retrieve every single lightcurve associated with this AggregateLightCurve instance, for all time chunk IDs, telescopes, ObsIDs, and Instruments.

Returns:

A list of every single lightcurve associated with this object.

Return type:

List[LightCurve]

property central_coord

This property provides the central coordinates (RA-Dec) of the region that this set of light curves 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 set of light curves 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 set of light curves 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 set of light curves was generated.

Returns:

The outer radius(ii) of the region.

Return type:

Quantity

property time_bin_size

Gives the time bin size used to generate this set of light curves.

Returns:

The time bin size used to generate this set of light curves.

Return type:

Quantity

property ref_times

Returns the time system reference times of this aggregate lightcurve’s components.

There will be one reference time for each telescope associated with this object.

Returns:

Dictionary mapping telescope names to their reference times.

Return type:

Dict[str, Time]

property time_chunk_ids

Getter for the time chunk IDs associated with this AggregateLightCurve. Light curves that are part of an AggregateLightCurve will be separated into ‘time chunks’, where a time chunk is a period that has uninterrupted coverage. For instance, three XMM observations separated by a year each would be in three different time chunks, but if there were a fourth observation that was taken by another telescope and happened concurrently (even if it didn’t start and end at the same time) with the first XMM observation, then it would be in the same time chunk.

Returns:

np.ndarray

Return type:

An array of integer time chunk identifiers, ordered from earlier to later times.

property num_time_chunks

Getter for the number of time chunks associated with this AggregateLightCurve. Light curves that are part of an AggregateLightCurve will be separated into ‘time chunks’, where a time chunk is a period that has uninterrupted coverage. For instance, three XMM observations separated by a year each would be in three different time chunks, but if there were a fourth observation that was taken by another telescope and happened concurrently (even if it didn’t start and end at the same time) with the first XMM observation, then it would be in the same time chunk.

Returns:

np.ndarray

Return type:

An array of integer time chunk identifiers, ordered from earlier to later times.

property time_chunks

A getter for the start and stop times of the time chunks associated with this AggregateLightCurve. The left hand column are start times, and the right hand column are stop times. These are the earliest and latest times of coverage for all the observations in the particular time chunk.

Returns:

A Nx2 non-scalar Astropy Quantity, where the left hand column are chunk start times, and the right hand column are chunk stop times.

Return type:

Quantity

property datetime_chunks

A getter for the start and stop datetimes of the time chunks associated with this AggregateLightCurve. The left hand column are start datetimes, and the right hand column are stop datetimes. These are the earliest and latest times of coverage for all the observations in the particular time chunk.

Returns:

A Nx2 array of datetime objects, where the left hand column are chunk start datetimes, and the right hand column are chunk stop datetimes.

Return type:

np.ndarray(datetime)

property time_chunk_lengths

Computes and returns lengths (in seconds) of each time chunk.

Returns:

An astropy quantity containing the time chunk lengths in seconds.

Return type:

Quantity

property overall_time_window

Returns the beginning time of the first time chunk, and the end time of the last time chunk; represents the entire time window covered by this AggregateLightCurve (not necessarily continuously).

Returns:

Two element astropy Quantity, with the first element being the start time of the first time chunk, and the second element being the end time of the last time chunk.

Return type:

Quantity

property overall_datetime_window

Returns the beginning datetime of the first time chunk, and the end datetime of the last time chunk; represents the entire time window covered by this AggregateLightCurve (not necessarily continuously).

Returns:

Two element astropy Quantity, with the first element being the start datetime of the first time chunk, and the second element being the end datetime of the last time chunk.

Return type:

np.ndarray

property overall_time_window_coverage_fraction

Provides the fraction of the overall time window (from the beginning of the first observation to the end of the last observation) that is actually covered by constituent light curves.

Returns:

The overall time window coverage fraction.

Return type:

float

property storage_key

This property returns the storage key which this object assembles to place the AggregateLightCurve in an XGA source’s storage structure. The key is based on the properties of the AggregateLightCurve, and some of the configuration options, and is basically human-readable.

Returns:

String storage key.

Return type:

str

property event_selection_patterns

The event selection patterns used for different telescope instruments that are associated with this AggregateLightCurve.

Returns:

A dictionary where top level keys are telescope names, lower level keys are instrument names, and values are event selection patterns.

Return type:

dict

get_lightcurves(time_chunk_id, obs_id=None, inst=None, telescope=None)[source]

This is the getter for the lightcurves stored in the AggregateLightCurve data storage structure. They can be retrieved based on ObsID and instrument.

Parameters:
  • time_chunk_id (int) – The time chunk identifier to retrieve lightcurves 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.

  • telescope (str) – Optionally, a specific telescope to search for can be supplied.

Returns:

List of matching lightcurves, or just a LightCurve object if one match is found.

Return type:

Union[List[LightCurve], LightCurve]

get_data(inst=None, telescope=None, date_time=False, fracexp_corr=False, interval_start=None, interval_end=None, over_run=True)[source]

A get method to retrieve count-rate, count-rate error, timing, and time chunk data for a particular instrument of a particular telescope from this AggregateLightCurve.

The returned data are in the correct temporal order.

A time interval within which to retrieve data can be specified.

Parameters:
  • inst (str) – The instrument for which to retrieve the overall count-rate and time data. Default is None, which will automatically select the instrument name if only one is represented in this AggregateLightCurve. If multiple instruments are represented, the user must pass a value to choose which data to retrieve.

  • telescope (str) – The telescope for which to retrieve the overall count-rate and time data. Default is None, which will automatically select the telescope name if only one is represented in this AggregateLightCurve. If multiple telescopes are represented, the user must pass a value to choose which data to retrieve.

  • date_time (bool) – Whether the time data should be returned as an array of datetimes (not the default), or an Astropy TimeDelta object with the time as a different from MJD 50814.0 in seconds (the default).

  • fracexp_corr (bool) – Controls whether the data should be corrected for vignetting and deadtime effects by dividing by the ‘FRACEXP’ entry in the lightcurve. Default is False.

  • interval_start – The starting point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window start.

  • interval_end – The ending point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window end.

  • over_run – A boolean flag. If True, includes chunks partially overlapping the interval. If False, matches chunks entirely contained within the interval.

Returns:

The count rate data, count rate uncertainty data, and time data for the selected instrument. The final element of the return is an array indicating which time chunk each data point belongs to. Data are in the correct temporal order.

Return type:

Tuple[Quantity, Quantity, Union[TimeDelta, np.ndarray], np.ndarray]

get_src_gtis(inst=None, telescope=None, interval_start=None, interval_end=None, over_run=True)[source]

A get method to retrieve the good time intervals (GTIs) for the source light curves of a particular instrument of a particular telescope from this AggregateLightCurve.

The returned GTIs are in time chunk order.

A time interval within which to retrieve GTIs can be specified.

Parameters:
  • inst (str) – The instrument for which to retrieve the overall GTI information. Default is None, which will automatically select the instrument name if only one is represented in this AggregateLightCurve. If multiple instruments are represented, the user must pass a value to choose which GTIs to retrieve.

  • telescope (str) – The telescope for which to retrieve the overall GTI information. Default is None, which will automatically select the telescope name if only one is represented in this AggregateLightCurve. If multiple telescopes are represented, the user must pass a value to choose which GTIs to retrieve.

  • interval_start – The starting point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window start.

  • interval_end – The ending point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window end.

  • over_run – A boolean flag. If True, includes chunks partially overlapping the interval. If False, matches chunks entirely contained within the interval.

Returns:

The requested good-time-intervals for the source light curves, and an array indicating which time chunk each GTI belongs in. Data are in the correct temporal order.

Return type:

Tuple[Quantity, np.ndarray]

get_bck_gtis(inst=None, telescope=None, interval_start=None, interval_end=None, over_run=True)[source]

A get method to retrieve the good time intervals (GTIs) for the background light curves of a particular instrument of a particular telescope from this AggregateLightCurve.

The returned GTIs are in time chunk order.

A time interval within which to retrieve GTIs can be specified.

Parameters:
  • inst (str) – The instrument for which to retrieve the overall GTI information. Default is None, which will automatically select the instrument name if only one is represented in this AggregateLightCurve. If multiple instruments are represented, the user must pass a value to choose which GTIs to retrieve.

  • telescope (str) – The telescope for which to retrieve the overall GTI information. Default is None, which will automatically select the telescope name if only one is represented in this AggregateLightCurve. If multiple telescopes are represented, the user must pass a value to choose which GTIs to retrieve.

  • interval_start – The starting point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window start.

  • interval_end – The ending point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window end.

  • over_run – A boolean flag. If True, includes chunks partially overlapping the interval. If False, matches chunks entirely contained within the interval.

Returns:

The requested good-time-intervals for the background light curves, and an array indicating which time chunk each GTI belongs in. Data are in the correct temporal order.

Return type:

Tuple[Quantity, np.ndarray]

time_chunk_ids_within_interval(interval_start=None, interval_end=None, over_run=True)[source]

Fetches the IDs of time chunks that fall within a specified interval. The interval can be defined either as a duration offset from a reference time (Quantity) or as absolute timestamps (Time or datetime). Depending on the over_run parameter, the method returns IDs of chunks fully contained within the interval or only partially overlapping the interval. Raises validation exceptions in case of incompatible interval types or invalid configurations.

Parameters:
  • interval_start – The starting point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window start.

  • interval_end – The ending point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window end.

  • over_run – A boolean flag. If True, includes chunks partially overlapping the interval. If False, matches chunks entirely contained within the interval.

Returns:

An array of integer time chunk IDs for the time chunks that satisfy the filtering criteria.

Return type:

np.ndarray

Raises:
  • ValueError – If the start of the interval is not before the end of the interval.

  • TypeError – If the provided interval types are not one of the accepted formats or if their types are mismatched.

obs_ids_within_interval(interval_start=None, interval_end=None, over_run=True)[source]

Fetches the ObsIDs of data associated with time chunks that fall within a specified interval. The interval can be defined either as a duration offset from a reference time (Quantity) or as absolute timestamps (Time or datetime). Depending on the over_run parameter, the method returns ObsIDs related to chunks fully contained within the interval or only partially overlapping the interval. Raises validation exceptions in case of incompatible interval types or invalid configurations.

Parameters:
  • interval_start – The starting point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window start.

  • interval_end – The ending point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window end.

  • over_run – A boolean flag. If True, includes chunks partially overlapping the interval. If False, matches chunks entirely contained within the interval.

Returns:

A dictionary with telescope names as keys, and values being lists of ObsIDs within the specified interval.

Return type:

dict

time_chunk_good_fractions(src_gti=True, inst=None, telescope=None)[source]

A method to retrieve the good time fractions of each time chunk, for a particular instrument of a particular telescope. The good time fractions are the fraction of a time chunk that falls within a good-time-interval.

Parameters:
  • src_gti (bool) – Controls whether the good fractions are calculated using the source or background good-time-intervals. Default is True, which will use the source GTI information.

  • inst (str) – The instrument for which to calculate good time fractions of time chunks. Default is None, which will automatically select the instrument name if only one is represented in this AggregateLightCurve. If multiple instruments are represented, the user must pass a value to choose which GTIs to retrieve.

  • telescope (str) – The telescope for which to calculate good time fractions of time chunks. Default is None, which will automatically select the telescope name if only one is represented in this AggregateLightCurve. If multiple telescopes are represented, the user must pass a value to choose which GTIs to retrieve.

Returns:

The fraction of each time chunk that within a good-time interval.

Return type:

np.ndarray

check_times_within_gti(times, src_gti=True, inst=None, telescope=None)[source]

Check whether given times are within the good-time-intervals (GTIs) of any component light curve within this AggregateLightCurve that matches the specified instrument and telescope.

Comparisons are made to the source or background GTIs depending on the passed value of the ‘src_gti’ parameter.

Times must be in the form of seconds from reference time of the telescope of interest.

Parameters:
  • times (Quantity/np.ndarray/Time) – Times to be checked against the GTIs. Can be scalar or an array. Passing astropy Time objects, Python datetime objects (or arrays of datetimes), or seconds from reference time are all supported.

  • src_gti (bool) – Flag indicating whether to use source GTIs (True) or background GTIs (False). Defaults to True.

  • inst (str) – The instrument whose light curve GTIs we are to compare the input times with. If None, value will be inferred if only one telescope and instrument are associated with this object.

  • telescope (str) – The telescope whose light curve GTIs we are to compare the input times with. If None, value will be inferred if only one telescope and instrument are associated with this object.

Returns:

A boolean array indicating whether each input time falls within any of the GTIs.

Return type:

np.ndarray

get_view(fig, inst=None, custom_title=None, label_font_size=18, title_font_size=20, inst_cmap='viridis', y_lims=None, time_chunk_ids=None, yscale='linear', fracexp_corr=False, show_legend=True, alpha=0.8, interval_start=None, interval_end=None, over_run=True)[source]

A get method for a populated visualisation of the light curves present in this AggregateLightCurve.

Parameters:
  • fig (Figure) – The matplotlib Figure object to create axes on, and thus make the plot.

  • inst (str) – A specific instrument to display data for. Default is None, in which case all instruments are plotted.

  • custom_title (str) – A custom title to add to the visualisation - the default is None, in which case a title containing the source name and energy band will be generated.

  • label_font_size (int) – The font size for axes labels, default is 18.

  • title_font_size (int) – The font size for the title, default is 20.

  • inst_cmap (str) – The colormap from which we draw colours to uniquely identify different instruments plotted in this get_view method.

  • y_lims (Quantity) – The lower and upper limits that should be applied to the y-axis of this plot. The default is None, in which case they will be determined automatically based on the data.

  • time_chunk_ids (int/List[int]) – This parameter can be used to control which time chunks are plotted on this AggregateLightCurve view. The default is None, in which case all time chunks are plotted; however the user may also pass a list of chunk IDs (or a single chunk ID) to limit the data that are shown.

  • yscale (str) – The scaling that should be applied to the y-axis of this figure. Default is linear. Any matplotlib scale can be used.

  • fracexp_corr (bool) – Controls whether the plotted data should be corrected for vignetting and deadtime effects by dividing by the ‘FRACEXP’ entry in the lightcurve. Default is False.

  • show_legend (bool) – Controls whether a legend is included in each panel of the visualization.

  • alpha (float) – The alpha value to be used for the plotted data. Default is 0.8.

  • interval_start – The starting point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window start.

  • interval_end – The ending point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window end.

  • over_run – A boolean flag. If True, includes chunks partially overlapping the interval. If False, matches chunks entirely contained within the interval.

Returns:

A dictionary of axes objects that have been added, and the figure object that was passed in.

Return type:

Tuple[dict, Figure]

view(figsize=(14, 6), inst=None, custom_title=None, label_font_size=15, title_font_size=18, inst_cmap='viridis', y_lims=None, time_chunk_ids=None, yscale='linear', fracexp_corr=False, show_legend=True, alpha=0.8, interval_start=None, interval_end=None, over_run=True)[source]

This method creates a combined visualisation of all the light curves associated with this object (apart from when you specify a single instrument, then it uses all the light curves from that instrument). The data are displayed in the correct temporal order, with the x-axis labels indicating the date and time rather than the mission specific internal time.

Parameters:
  • figsize (tuple) – The size of the visualisation figure, default is (14, 6). Adjusting this value is the best way to achieve nice looking plots when labels are overlapping, particularly when there are many observations and time chunks to plot in the x-direction.

  • inst (str) – A specific instrument to display data for. Default is None, in which case all instruments are plotted.

  • custom_title (str) – A custom title to add to the visualisation - the default is None, in which case a title containing the source name and energy band will be generated.

  • label_font_size (int) – The font size for axes labels, default is 18.

  • title_font_size (int) – The font size for the title, default is 20.

  • inst_cmap (str) – The colormap from which we draw colours to uniquely identify different instruments plotted in this view method.

  • y_lims (Quantity) – The lower and upper limits that should be applied to the y-axis of this plot. The default is None, in which case they will be determined automatically based on the data.

  • time_chunk_ids (int/List[int]) – This parameter can be used to control which time chunks are plotted on this AggregateLightCurve view. The default is None, in which case all time chunks are plotted; however the user may also pass a list of chunk IDs (or a single chunk ID) to limit the data that are shown.

  • yscale (str) – The scaling that should be applied to the y-axis of this figure. Default is linear. Any matplotlib scale can be used.

  • fracexp_corr (bool) – Controls whether the plotted data should be corrected for vignetting and deadtime effects by dividing by the ‘FRACEXP’ entry in the lightcurve. Default is False.

  • show_legend (bool) – Controls whether a legend is included in each panel of the visualization.

  • alpha (float) – The alpha value to be used for the plotted data. Default is 0.8.

  • interval_start – The starting point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window start.

  • interval_end – The ending point of the time interval. Can be a Quantity indicating a duration from the reference time, an astropy Time, or a Python datetime, or None to use the overall window end.

  • over_run – A boolean flag. If True, includes chunks partially overlapping the interval. If False, matches chunks entirely contained within the interval.