PostProcessing
Module for various (posterior) sample post-processing operations.
Users
The typical usage pattern is to use the following classes:
Runsto load a set of nested sampling runs on one underlying posterior distribution;
CornerPlotterto plot 1D and 2D marginal posterior density distributions (from a set ofRunsinstances) in lower-triangular form, and to compute various posterior estimators;
CorrelationMatrixto plot the posterior distributions correlation structures;
SignalPlotterto plot thematic X-ray signals (or, generally, derived quantities) in posterior- expected form or conditional-posterior form, together with ground truths (i.e., injected) and in component form when there are two or more disjoint surface hot regions;to use the
SignalPlotterclass, a user must supply a set of plot class instances for each posterior distribution to be processed, where these native classes areand can be configured both on a class and instance level.
Statistical residual diagnostics
The ResidualPlot class can optionally add
(plot_clusters=True) a map of the clusters of large standardised
residuals, the residual distribution compared with a normal distribution
(with a Kolmogorov-Smirnov test), and the distribution of cluster sizes
compared with the range expected from counting noise alone (with a p-value
for the largest cluster). The Residual1DPlot
class shows the residual distribution and its Kolmogorov-Smirnov test on
its own.
The ResidualStructurePlot class quantifies
whether the standardised (data minus posterior-expected) residuals exhibit
2D structure over the joint phase-channel intervals, or are instead
consistent with random noise. It runs a suite of six complementary
statistical tests:
a 2D power spectrum (FFT) test for periodic and smooth patterns;
an empirical variogram test for distance-dependent correlation;
a 2D autocorrelation-function scan over all lag vectors, sensitive to clustered residuals at any orientation (including diagonal);
a Kolmogorov-Smirnov normality test combined with a Ljung-Box autocorrelation test (optional dependency
statsmodels);Moran’s I global spatial autocorrelation (optional dependencies
esdaandlibpysal);a Wald-Wolfowitz runs test applied per channel and per phase bin.
A combined verdict (STRUCTURED, RANDOM, or INCONCLUSIVE) is
printed and stored on the instance, and its figure shows tests 1 to 4 and a
summary of all six tests. It is a separate plot class, which can be passed
to SignalPlotter together with
ResidualPlot for the same posterior, e.g.,
plots = {'ST': [ResidualPlot(plot_clusters=True), ResidualStructurePlot()]};
the posterior-expected counts are then computed only once for both plots.
Customization
The aforementioned native classes can of course be subclassed if the aim is to wrap, modify, or add functionality too.
In order to make entirely new plot type, we need to subclass the abstract
base class SignalPlot, using the
native subclasses for guidance.
If new plot types are developed, please contribute to the source code via a pull request. Isolate the new functionality in a proposed submodule, adding your authorship information, and supply examples of usage in a Jupyter notebook (either a new tutorial or by extending an existing tutorial as appropriate). The subclass can then be imported from the submodule namespace as shown below for the native classes. Then add the submodule to the Sphinx doc pages. If you can include an example image in the subclass docstring, please do, as it will be rendered directly in the class documentation. Finally, if you can point to a journal article that implements the plot type, please do.
|
Container for nested sampling runs on a shared posterior. |
|
Plot marginal posterior densities and estimators. |
|
Plot conditional posterior distributions of thematic X-ray signals. |
Plot the count data, the posterior-expected count signal, residuals, clusters and their related distributions. |
|
|
Plot the distribution of the standardised residuals. |
Test whether the 2D residuals contain structure, and plot the tests. |
|
|
Plot posterior-averaged channel-summed count-rate pulse profiles. |
Plot posterior-averaged channel count-rate spectra. |
- class xpsi.PostProcessing.Runs(runs, likelihood, *args, **kwargs)[source]
Bases:
MetadataContainer for nested sampling runs on a shared posterior.
- Parameters:
likelihood – The instance of
Likelihoodused for sampling, or a clone of that instance. Defaults toNone. If multiple likelihood functions are associated with the runs due to discreteness in the model space, one can pass a dictionary with keys matching the IDs of the runs.
- property combined
Try to get a combined run in the form of a
nestcheckbackend.
- get_attr(attribute, current=True, nestcheck_compatible=False)[source]
Get a list of attributes of the
Runinstances stored as the current subset.
- property likelihood
Get the likelihood instance.
- classmethod load_runs(ID, run_IDs, roots, base_dirs, use_nestcheck, likelihood=None, multi_mode=False, mode_label='mode', **kwargs)[source]
Construct a
Runsinstance by loading distinct runs.- param bool multi_mode:
Load the runs so that they are separated in different modes found by a MultiNest run with mmodal=True.
- param string mode_label:
Select a label for the modes to be shown in the plots.
The kwargs will be shared by nested sampling runs. The args must be lists that will be zipped to instantiate a set of run backends. The kwargs include the metadata of the runs (see
Metadata), e.g.,names,bounds,labelsandshort_labels. The optionalshort_labelsdictionary specifies shorter labels (e.g., without units) for the off-diagonal 2D panel annotations of corner plots whenlabels_2D=True; parameters without a short label default to their full label fromlabels.
- property runs
Get a copy of the list of runs.
- set_subset(IDs=None, combine=False, combine_all=False, force_combine=False, only_combined=False, only_principal=False, overwrite=False, split_modes=False)[source]
Set a current list of
Runinstances.
- property subset
Get the current subset of runs for plotting.
- property subset_to_plot
Get the current subset of runs (+ combined) for plotting.
- class xpsi.PostProcessing.CornerPlotter(posteriors)[source]
Bases:
PostProcessorPlot marginal posterior densities and estimators.
- KL_divergence(base='bits', bootstrap=False, quantiles=[0.025, 0.5, 0.975], n_simulate=200, **kwargs)[source]
Kullback-Leibler divergence integral jointly for all parameters.
E.g., if you want the interval about the median containing divergence of 90% of realisations, declare
quantiles=[0.05,0.5,0.95].
- evidence_error(quantiles=[0.025, 0.5, 0.975], n_simulate=200, flip_skew=True, **kwargs)[source]
Estimate evidence error for nestcheck-compatible runs.
E.g., if you want the interval about the median containing the evidence of 90% of realisations, declare
quantiles=[0.05,0.5,0.95].
- plot(params, IDs=None, combine=False, combine_all=False, only_combined=False, force_combine=True, overwrite_combined=False, split_modes=False, bootstrap_estimators=True, bootstrap_density=False, separate_plots=False, write=False, root_filename='', directory='./', ext='.pdf', dpi=300, maxdots=2000, **kwargs)[source]
Generate posterior density plots.
Invokes
getdistandnestcheckfor nested sampling runs.Up to five runs can be plotted natively via
nestcheck; beyond such a number the plots generally display too much information and clarity is lost.- Parameters:
params (list) – List of parameter strings for plotting. Must be shared by all posteriors selected with the
IDsargument.IDs (OrderedDict) – Keys must be string identifiers of
Runsinstances. Each dictionary element must be a list of string identifiers, each matching objects collected inRunsinstance corresponding to the key. Defaults toNone, meaning attempt to use as many runs as possible subject to plotting restrictions.
Note
The order of IDs is used to control the layering of posteriors. If there are multiple underlying posteriors (i.e., multiple dictionary keys), only one (combined) run per posterior is rendered, and the first posterior is rendered on the topmost layer. If there is only one underlying posterior (i.e., one dictionary keys), then the combined-sample posterior, if available, is plotted on the topmost layer, whilst the runs on that posterior are rendered on layers underneath in the order specified in the list. In either case, estimators are calculated and reported for the (combined) run on the topmost layer.
- Parameters:
combine (bool) – Additionally combine the runs into a single run for overplotting? The overriding setting if there is more than one underlying posterior to be plotted, is to attempt to combine runs on each posterior if multiple such runs are available, in order to reduce information density. If there is a single underlying posterior, the user-specified value is respected.
combine_all (bool) – Combine all runs in each
Runsinstance or only those for which IDs are provided? Ignored ifcombineisFalse.force_combine (bool) – Force recombination of elligible run sets, even if a combined run is already cached?
only_combined (bool) – Only plot the combined run? Only heeded if a single posterior is selected for plotting, and in that case is ignored if
combineisFalse.overwrite_combined (bool) – Overwrite combined-sample files on disk with the same filename?
split_modes (bool) – Split modes for plotting input multi-mode runs?
bootstrap (bool) – Use
nestcheckandfgivenxto bootstrap the runs for posterior density error estimation?separate_plots (bool) – Generate a lower-triangle plot with
getdist, and a separate error plot withnestcheck(withfgivenxandgetdist). IfFalse(default), the diagonal panels of the lower-triangle plot are modified by adding the nestcheck output. Ignored ifbootstrapisFalse.write (bool) – Export the figure?
root_filename (str) – Root filename to prepend to automatically generated name. Can be, e.g., a model and/or data set identifier.
directory (str) – If
Nonedefaults to current directory.ext (str) – File extension for writing. E.g.,
'.png'.dpi (int) – Dots-per-square-inch settings for exporting plots.
kwargs – Keyword arguments for the
_plot_density_with_error()and_plot_triangle()methods. Keyword arguments for line properties (width, color, and alpha) forgetdistcontours and density distributions. Ifbootstrap and not separate_plotsthen the density distribution linewidth is set to zero if not explicitly specified with kwarglw_1d. In addition, keyword arguments for avoiding unnecessary re-drawing of prior samples (force_draw,prior_samples_fnamesandpriors_identical). Paramprecisions(a list of integers or Nones) can be used to define the decimal number precision for each credible interval plotted. In case of 2 parameters, one can do e.g. precisions=[2,None] to use 2 digit decimal precision for the first parameter and use the default automatic precision for the second. Paramci_gap(a float) can be used to adjust the white gaps between the texts printed above the diagonal (the default is 0.12).
- class xpsi.PostProcessing.SignalPlotter(posteriors)[source]
Bases:
PostProcessorPlot conditional posterior distributions of thematic X-ray signals.
Methods to plot the data and model for posterior checking.
Plots are generated for each posterior selected using the associated likelihood object.
For a given model, there may be multiple
Signalinstances per likelihood object. If this is the case, you need to reduce the model down to only the objects needed for functioning of theSignalobject to be handled. To do this, simply remove supply to your likelihood object the references to this minimal set of objects. This minimises computation time and ensures explicit declaration of the signals to be plotted.Note
If a model has multiple instruments, then the energy set for signal integration is calculated based on waveband coverage union. If instruments are omitted from the likelihood object in order to execute posterior signal plotting, the number of energies that span the waveband of the remaining instrument waveband should be set to match the number in the full model (with all instruments) if the likelihood factor for the remaining instrument is to be exactly the same.
- plot(plots, IDs=None, combine=False, combine_all=False, only_combined=False, force_combine=True, nsamples=200, cache=True, force_cache=False, cache_dir='./', read_only=False, archive=True)[source]
Compute and plot signals a posteriori.
- Parameters:
plots (dict) – Dictionary of lists of plot objects, where each dictionary key must match a posterior ID.
IDs (OrderedDict) – Keys must be string identifiers of
Runsinstances. Each dictionary element must be a list of string identifiers, each matching objects collected inRunsinstance corresponding to the key. Defaults toNone, meaning attempt to use as many runs as possible subject to plotting restrictions.cache (bool) – Cache intermediary model objects to accelerate post-processing?
force_cache (bool) – Force caching irrespective of checks of existing cache files. Useful if some part of the model is tweaked and the cache file with the same name and sample set is not manually moved from the designated directory..
nsamples (int) – Number of samples to use. Equally-weighted samples are generated, thus introducing a additional Monte Carlo noise which is ignored.
num_phases (int) – Number of phases to interpolate at on the interval [0,2] cycles.
filename (str) – Filename of cache.
cache_dir (str) – Directory to write cache to.
read_only (bool) – Do not write to cache file?
archive (bool) – If not read-only, then archive an existing cache file found at the same path?
- property plots
Get the dictionary of plot objects last processed.
- class xpsi.PostProcessing.ResidualPlot(data_cmap='inferno', model_cmap='inferno', residual_cmap='PuOr', parameters_vector=None, plot_pulse=False, legend_pulse_coords=None, n_realisation_per_sample=1, blur_residuals=False, plot_clusters=False, threshlim=2.0, clusters_cmap='PuOr_seq', clustdist_cmap=None, mu=0.0, sigma=1.0, nbins=50, cluster_null_n=1000, cluster_null_random_seed=0, cluster_connectivity=8, **kwargs)[source]
Bases:
SignalPlotPlot the count data, the posterior-expected count signal, residuals, clusters and their related distributions.
The figure contains three upper panels which share phase as an x-axis:
the top panel displays the data count numbers in joint channel-phase intervals, identically split over two rotational phase cycles;
the center panel displays the posterior-expected count signal over joint channel-phase intervals;
the bottom panel displays the standardised residuals between the data and posterior-expected count signal over joint channel-phase intervals.
If
plot_pulse=True, a panel with the phase-resolved total counts of the data and of the posterior-expected signal (with posterior-predictive error bars) is added on top.If
plot_clusters=True, the figure also contains two lower rows for basic diagnostics of residuals (via analysis of clusters):a cluster panel sharing the phase axis of the panels above: over the first phase cycle, the standardised residuals with
|residual| >= threshlim; over the second cycle, the size (in pixels) of the cluster each of these residuals belongs to. Clusters are groups of adjacent pixels (seecluster_connectivity), merged across the periodic phase boundary.on the left, the residual distribution (density) with a fitted normal distribution, a reference normal distribution (by default N(0,1)) and the p-value of a Kolmogorov-Smirnov test against the reference; on the right, the cumulative number of clusters with size at least \(s\), compared with the range expected from counting noise alone (Poisson realisations of the posterior-expected counts), and the p-value of the largest cluster.
Statistical tests of 2D structure in the residuals (power spectrum, variogram, autocorrelation, …) are provided by the separate
ResidualStructurePlot, which can be passed together with this plot.The following example is (improved) from Riley et al. 2019:
Each instance draws one figure: create a new instance for each call of
plot()(reusing an instance that has already been plotted raises aRuntimeError).- Parameters:
data_cmap (str) – Colormap name from
matplotlibto use for the data count numbers over joint channel-phase intervals.model_cmap (str) – Colormap name from
matplotlibto use for the posterior-expected count numbers over joint channel-phase intervals.residual_cmap (str) – Colormap name from
matplotlibto use for the standardised residuals (residual panel and, withplot_clusters=True, the residuals abovethreshlim). A diverging colormap is recommended.parameters_vector (list) – If given, the plot is made for this single vector of model parameter values (in the order of the likelihood parameters) instead of for posterior samples.
SignalPlotteronly looks at the first plot passed for a posterior, so this then applies to all plots passed together.plot_pulse (bool) – Add a top panel with the pulse profile (counts summed over channels) of the data and of the posterior-expected signal, with a posterior-predictive band (see
n_realisation_per_sample)?legend_pulse_coords (tuple) – Position of the legend of the pulse panel, passed to
matplotlibasbbox_to_anchor. If not given, the best location is chosen automatically.n_realisation_per_sample (int) – Number of Poisson realisations drawn from the pulse profile of each posterior sample, to build the posterior-predictive band (16th to 84th percentiles) of the pulse panel (
plot_pulse=True). If fewer than 100 realisations are available in total (number of posterior samples times this number), the band is instead the posterior-expected pulse plus or minus its square root (Poisson error). Default 1.blur_residuals (bool) – Smooth the displayed residual map with a Gaussian filter? This only affects the display; clusters and statistics use the unsmoothed residuals.
plot_clusters (bool) – Add the cluster panel and the distribution panels (residual distribution and cluster-size distribution) described above? The parameters
threshlim,clusters_cmap,mu,sigma,nbins,cluster_null_n,cluster_null_random_seedandcluster_connectivityare only used ifTrue.threshlim (float) – Threshold on the absolute value of the standardised residuals: pixels with
|residual| >= threshlimare grouped into clusters. Default 2.0.clusters_cmap (str) – Colormap name from
matplotlibto use for the cluster sizes. Cluster sizes are non-negative, so a sequential colormap is recommended. The default,'PuOr_seq', is a sequential colormap with the colours of'PuOr'(light orange for small clusters to dark purple for large ones), registered withmatplotlibby this module. When all clusters are smaller than 7 pixels, the colour bar is discrete, with one colour for each size from 1 to 6. Pixels outside any cluster are left blank.clustdist_cmap (str) – Deprecated and ignored: the cluster-size distribution panel has no colormap. Passing it issues a
FutureWarning; it will be removed in a future release.mu (float) – Mean of the reference normal distribution (dashed line) drawn over the residual distribution. Default 0, as expected for standardised residuals. A maximum-likelihood normal fitted to the residuals is always drawn as well (solid line); its parameters are stored in
residual_fit_muandresidual_fit_sigma. A one-sample Kolmogorov-Smirnov test of the residuals against the reference distribution is reported in the legend; its statistic and p-value are stored inresidual_ref_ks_statandresidual_ref_ks_pvalue.sigma (float) – Standard deviation of the reference normal distribution (dashed line). Default 1, as expected for standardised residuals.
nbins (int) – Number of bins of the residual distribution histogram. The bins span a range symmetric about zero. Default 50.
cluster_null_n (int) – Number of Poisson realisations of the posterior-expected counts used to build the noise-only reference of the cluster-size distribution panel. Each realisation is standardised and clustered exactly like the data. Default 1000; the smallest reportable p-value for the largest cluster is
1/(cluster_null_n+1). The size of the largest cluster and its p-value are stored incluster_max_sizeandcluster_max_pvalue.cluster_null_random_seed (int) – Seed for the cluster-size noise realisations (reproducibility).
cluster_connectivity (int) – Pixel connectivity used to group
|residual| >= threshlimpixels into clusters:8(default) joins pixels sharing an edge or a corner, so oblique structures stay in one cluster;4joins pixels sharing an edge only. Applied identically to the data and to the noise realisations, including across the periodic phase boundary.kwargs – Keyword arguments for
SignalPlot(e.g.write,dpi,fig_dir,root_filename), andyscale('log'by default) for the channel axis of the channel-phase panels.
- property expected_counts
Get the estimated posterior expectation of the count numbers.
- finalize()[source]
Execute instructions to finish plotting.
Before this method is called, the likelihood object will be updated so that the true (injected) signals are cached. In the body of the subclass implementation of this method, one can plot the injected signals by accessing the attributes of the signal instance.
- property model_list
Get the current list of the count numbers.
- property model_sum
Get the current posterior sum of the count numbers.
- class xpsi.PostProcessing.Residual1DPlot(nbins=20, plot_fit=False, mu=0.0, sigma=1.0, parameters_vector=None, **kwargs)[source]
Bases:
SignalPlotPlot the distribution of the standardised residuals.
The figure contains one panel: the histogram (density) of the standardised residuals \((c_{ik}-d_{ik})/\sqrt{c_{ik}}\) between the posterior-expected count signal \(c_{ik}\) and the data \(d_{ik}\) over all joint channel-phase intervals, with a reference normal distribution (by default N(0,1), dashed line) and the p-value of a one-sample Kolmogorov-Smirnov test of the residuals against it, and optionally a normal distribution fitted to the residuals.
Each instance draws one figure: create a new instance for each call of
plot()(reusing an instance that has already been plotted raises aRuntimeError).- Parameters:
nbins (int) – Number of histogram bins, spanning the range of the residuals. Default 20.
plot_fit (bool) – Overlay a maximum-likelihood normal distribution fitted to the residuals (solid line), with a dashed vertical line at its mean?
mu (float) – Mean of the reference normal distribution (dashed line). Default 0, as expected for standardised residuals. A one-sample Kolmogorov-Smirnov test of the residuals against the reference is reported in the legend; its statistic and p-value are stored in
residual_ref_ks_statandresidual_ref_ks_pvalue.sigma (float) – Standard deviation of the reference normal distribution. Default 1, as expected for standardised residuals.
parameters_vector (list) – If given, the plot is made for this single vector of model parameter values (in the order of the likelihood parameters) instead of for posterior samples.
SignalPlotteronly looks at the first plot passed for a posterior, so this then applies to all plots passed together.kwargs – Keyword arguments for
SignalPlot(e.g.write,dpi,fig_dir,root_filename).
- property expected_counts
Get the estimated posterior expectation of the count numbers.
- finalize()[source]
Execute instructions to finish plotting.
Before this method is called, the likelihood object will be updated so that the true (injected) signals are cached. In the body of the subclass implementation of this method, one can plot the injected signals by accessing the attributes of the signal instance.
- property model_sum
Get the current posterior sum of the count numbers.
- class xpsi.PostProcessing.ResidualStructurePlot(parameters_vector=None, structure_power_n_null=1000, structure_power_alpha=0.05, structure_power_low_k_fraction=0.15, structure_power_random_seed=0, structure_variogram_max_lag=20, structure_variogram_n_null=1000, structure_variogram_alpha=0.05, structure_variogram_random_seed=0, structure_acf2d_max_lag=8, **kwargs)[source]
Bases:
SignalPlotTest whether the 2D residuals contain structure, and plot the tests.
Computes the standardised residuals between the data and the posterior-expected count signal over joint channel-phase intervals, \((c_{ik}-d_{ik})/\sqrt{c_{ik}}\), and runs six complementary tests of whether they exhibit 2D structure or are consistent with random noise:
2D power spectrum – periodic and smooth structure from the 2D periodogram (calibrated with white-noise simulations).
Variogram – how the correlation decays with pixel distance on the phase-channel grid (calibrated with white-noise simulations).
2D autocorrelation-function (ACF) scan – correlation at every lag vector up to
structure_acf2d_max_lag, at any orientation.KS + Ljung–Box – Gaussianity of the residuals and serial autocorrelation of the flattened residuals (Ljung–Box requires
statsmodels; KS always runs).Moran’s I – global spatial autocorrelation (requires
esdaandlibpysal; skipped if absent).Runs test – Wald–Wolfowitz test applied per channel and per phase bin.
A summary of the tests and a combined verdict (
STRUCTUREDif at least three tests flag structure,RANDOMif none does,INCONCLUSIVEotherwise) is printed when the plot is finalised. The per-test results are stored inresidual_structure_resultsand the verdict inresidual_structure_verdict.The figure contains:
in the first two columns, one panel per test for tests 1 to 4: the 2D power spectrum and the normalised variogram (top row), the 2D ACF map with the strongest lag marked and a normal Q-Q plot (bottom row);
in the third column, a summary of all six tests (including tests 5 and 6, which have no panel): for each test, a short description of what it looks for and how to read its panel, and the values and threshold that decide its verdict; then the combined verdict.
The residual map itself is shown by
ResidualPlot.This plot is independent of
ResidualPlot. Both use the posterior-expected counts, so they can be passed together for the same posterior, e.g.:plots = {'ST': [xpsi.ResidualPlot(plot_clusters=True), xpsi.ResidualStructurePlot()]}
They then use the same posterior samples, and with caching (the default of
plot()) the model is evaluated only once for both.Each instance draws one figure: create a new instance for each call of
plot()(reusing an instance that has already been plotted raises aRuntimeError).- Parameters:
parameters_vector (list) – If given, the residuals are computed for this single vector of model parameter values (in the order of the likelihood parameters) instead of for posterior samples.
SignalPlotteronly looks at the first plot passed for a posterior, so this then applies to all plots passed together.structure_power_n_null (int) – Number of white-noise simulations used to calibrate the null distribution of the 2D power spectrum test (test 1). Default 1000; the smallest reportable p-value is
1/(n_null+1).structure_power_alpha (float) – Significance level of the 2D power spectrum test, before the internal Bonferroni factor of 2 over its two statistics. Default 0.05.
structure_power_low_k_fraction (float) – Radial-frequency cut (as a fraction of the Nyquist radius) defining the low-k region for the smooth-structure statistic of the 2D power spectrum test. Default 0.15.
structure_power_random_seed (int) – Seed for the power spectrum null simulations (reproducibility).
structure_variogram_max_lag (int) – Maximum pixel lag used for the variogram test (test 2). Default 20.
structure_variogram_n_null (int) – Number of white-noise simulations used to calibrate the null distribution of the variogram test. Default 1000.
structure_variogram_alpha (float) – Significance level of the variogram test, before the internal Bonferroni factor of 2 over its two statistics. Default 0.05.
structure_variogram_random_seed (int) – Seed for the variogram null simulations (reproducibility).
structure_acf2d_max_lag (int) – Maximum pixel lag along each axis for the 2D ACF scan (test 3). Default 8.
kwargs – Keyword arguments for
SignalPlot(e.g.write,dpi,fig_dir,root_filename).
- property expected_counts
Get the estimated posterior expectation of the count numbers.
- finalize()[source]
Execute instructions to finish plotting.
Before this method is called, the likelihood object will be updated so that the true (injected) signals are cached. In the body of the subclass implementation of this method, one can plot the injected signals by accessing the attributes of the signal instance.
- property model_sum
Get the current posterior sum of the count numbers.
- class xpsi.PostProcessing.PulsePlot(num_phases=1000, incident_cmap='inferno', registered_cmap='inferno', show_components=False, expectation_line_kwargs=None, comp_expectation_line_kwargs=None, sample_line_kwargs=None, use_fgivenx=False, incident_contour_kwargs=None, registered_contour_kwargs=None, plot_truth=False, truth_line_kwargs=None, comp_truth_line_kwargs=None, parameters_vector=None, **kwargs)[source]
Bases:
SignalPlotPlot posterior-averaged channel-summed count-rate pulse profiles.
The figure contains four panels which share phase as an x-axis:
the first (topmost) panel displays the posterior expectation of the specific photon flux signal from the source, jointly resolved in energy and phase;
the second panel displays the energy-integrated photon specific flux signal as function of phase for a subset of samples, optionally using
fgivenx;the third panel displays the posterior expectation of the count-rate signal as a function of channel and phase;
the last (bottommost) panel displays the channel-summed pulse as a function of phase for a subset of samples, optionally using
fgivenx.
The second and last panels aim to render the conditional posterior distribution of the associated signal as a function phase, ideally with contours to map out the conditional posterior mass. These panels have space to optionally display other elements such as: the posterior-expected total signal; the posterior-expected component signals; and the true total and component signals if the ground truth (the injected signal correpsonding to some model parameter vector) is known.
The following example is from Riley et al. 2019:
- Parameters:
num_phases (int) – The number of phases to interpolate the pulse-profile signals at.
incident_cmap (str) – Colormap name from
matplotlibto use for the posterior-expected incident signal as a function of energy and phase (top panel).registered_cmap (str) – Colormap name from
matplotlibto use for the posterior-expected registered signal as a function of channel and phase (third panel).show_components (bool) – If the
Signalinstance has multiple components, display the posterior expectations of those components as a function of phase (second and last panels).expectation_line_kwargs (dict) – Keyword arguments for plotting the posterior-expected signal lines (in the second and last panels).
use_fgivenx (bool) – Use
fgivenxto plot conditional posterior contours in the second and last panels?incident_contour_kwargs (dict) – Keyword arguments for
fgivenxincident signal contours (second panel) that will take precedence over the corresponding class attributes. (See theSignalPlotclass if you choose not to modify these attributes on this present subclass.)registered_contour_kwargs (dict) – Keyword arguments for
fgivenxregistered signal contours (last panel) that will take precedence over the corresponding class attributes. (See theSignalPlotclass if you choose not to modify these attributes on this present subclass.)plot_truth – Plot the ground truth (injected) signal, if known and available, in the second and last panels.
truth_line_kwargs – Keyword arguments for plotting the ground truth signal lines (second and last panels).
- property expected_incident
Get the expectations of the component incident signals.
- property expected_registered
Get the expectations of the component registered signals.
- class xpsi.PostProcessing.SpectrumPlot(rel_num_energies=10.0, num_phases=1000, registered_cmap='inferno', show_components=False, show_attenuated=True, expectation_line_kwargs=None, comp_expectation_line_kwargs=None, add_background=False, background_line_kwargs=None, sample_line_kwargs=None, use_fgivenx=False, incident_contour_kwargs=None, registered_contour_kwargs=None, plot_truth=False, truth_line_kwargs=None, comp_truth_line_kwargs=None, parameters_vector=None, **kwargs)[source]
Bases:
SignalPlotPlot posterior-averaged channel count-rate spectra.
The figure contains three panels which share phase as an x-axis:
the top panel displays the specific photon flux signal from the source, resolved as a function of energy, optionally showing both unattenuated and attenuated incident spectra and optionally using
fgivenx;the center panel displays the posterior expectation of the count-rate signal as a function of channel and phase, optionally including an expected background signal;
the bottom panel displays the phase-integrated (averaged) count-rate spectum as a function of channel number, optionally including an expected background signal and optionally using
fgivenx.
The top and bottom panels aim to render the conditional posterior distribution of the associated signal as a function an energy (proxy) variable, ideally with contours to map out the conditional posterior mass. These panels have space to optionally display other elements such as: the posterior-expected total signal; the posterior-expected component signals; the true total and component signals if the ground truth (the injected signal correpsonding to some model parameter vector) is known; attenuated incident spectra; and the summation of posterior-expected total (component-summed) source count-rate signals with posterior-expected background count-rate signals.
The following example is (improved) from Riley et al. 2019:
- Parameters:
rel_num_energies (float) – The number of energies desired for interpolation as a fraction of the number of energies implemented for the original incident signal integration. The energy set will be appropriately spaced and bounded.
num_phases (int) – The number of phases to interpolate the pulse-profile signals at for the center panel.
registered_cmap (str) – Colormap name from
matplotlibto use for the posterior-expected registered signal as a function of channel and phase (center panel).show_components (bool) – If the
Signalinstance has multiple components (hot region signals), display the posterior expectations of those components as a function of energy (top panel) and channel (bottom panel).show_attenuated (bool) – If the source signal is attenuated by the interstellar absorption processes, display the posterior-expected attenuated incident specific photon flux spectra? This switch also instructs
fgivenx, if enabled, to generate conditional posterior contours for the attenuated spectrum instead of the unattenuated spectrum (top panel). Iffgivenxis not invoked, this switch instructs the plotting of sample-by-sample attenuated total (component-summed) spectra to delineate the distribution of conditional posterior mass (top panel).expectation_line_kwargs (dict) – Keyword arguments for plotting the posterior-expected signal lines (in the top and bottom panels).
add_background (bool) – Add an posterior-expected background count-rate signal to the total (component-summed) expected source count-rate signals in the center and bottom panels?
background_line_kwargs (dict) – Keyword arguments for plotting the posterior-expected spectrum in the bottom panel that includes the background signal.
use_fgivenx (bool) – Use
fgivenxto plot conditional posterior contours in the top and bottom panels?incident_contour_kwargs (dict) – Keyword arguments for
fgivenxincident signal contours (top panel) that will take precedence over the corresponding class attributes. (See theSignalPlotclass if you choose not to modify these attributes on this present subclass.)registered_contour_kwargs (dict) – Keyword arguments for
fgivenxregistered signal contours (bottom panel) that will take precedence over the corresponding class attributes. (See theSignalPlotclass if you choose not to modify these attributes on this present subclass.)plot_truth – Plot the ground truth (injected) signal, if known and available, in the top and bottom panels.
truth_line_kwargs – Keyword arguments for plotting the ground truth signal lines (top and bottom panels).
comp_truth_line_kwargs – Keyword arguments for plotting the component ground truth signal lines (top and bottom panels).
- execute(thetas, wrapper)[source]
Execute behaviours requiring a loop over samples.
- Parameters:
thetas (ndarray[n,m]) – Equally-weighted set of posterior samples.
wrapper (callable) – Wrapper function that interleaves iterative calls next(self) with code to update the
Signalinstance from a cache stored on disk. The wrapper returns a callback function, If such a cache is unavailable, the likelihood function is evaluated on-the-fly when the callback is called passing a sample (parameter vector). In this case, signals to be plotted are temporarily cached in theSignalinstance. The signature of the wrapper function is: wrapper(self, delete_me=None, index=None), where self is this a subclass ofSignalPlot, delete_me is an optional attribute name or a list of attribute name in self.__dict__ to be deleted before iterating over samples, and index is an optional integer to index a tuple returned from next(self). The signature of the callback function, if you need to call it directly (instead of an external library such as fgivenx calling it): callback(None, theta), where each sample/parameter vector is a row in thetas.
- property expected_attenuated_incident
Get the expectations of the incident (component) spectra.
- property expected_background
Get the expectation of the background count-rate spectrum.
- property expected_incident
Get the expectations of the incident (component) spectra.
- property expected_registered
Get the expectations of the registered count-rate spectra.
Base classes for development
Base class for a signal plot. |
|
Post-process samples for inference and posterior checking. |
|
Container for nested samples generated by a single run, and backends for analysis of the run. |
|
|
Base class for a sample container. |
|
Base class to record basic information about sampling runs. |
- class xpsi.PostProcessing._signalplot.SignalPlot(fig_dir='./', root_filename='', cmap='RdPu_r', **kwargs)[source]
Base class for a signal plot.
Interact with a single
Signalinstance to plot signals.- Parameters:
fig_dir (str) – Directory to write to.
root_filename (str) – Prepended to filename automatically generated figure filename.
cmap (str) – Colormap name from
matplotlibto use forfgivenxcontours. It is advisable to choose a colormap that is darker at lower values (in tails of conditional posterior distribution) and lighter at higher values (at higher densities in conditional posterior distribution).
- classmethod declare_settings(panelsize=(8, 4), fscale=1.0, rasterized=True, tick_lengths=(8, 4), tick_width=1.0, logspace_y=False, tqdm_kwargs={'disable': False}, scale_ymin=0.9, scale_ymax=1.1, ny=500, lines_on=False, add_label=True, write=True, extension='.pdf', dpi=300, write_kwargs=None, xticks=None, yticks=None)[source]
Configure subclass with attributes, before instantiation.
These attributes can in principle be safely changed during the runtime.
- Parameters:
panelsize (tuple) – The approximate size,
(width, height), in inches per panel.fscale (float) – Scale factor for the fontsize applied to the default.
rasterized (bool) – Beware that if
False, white polygon edges may appear in figures.tick_lengths (tuple(int, int)) – The major and minor tick lengths for all axis objects.
tick_width (int) – The width of every tick.
logspace_y (bool) – Should the
fgivenxy-values (for which the posterior mass is integrated over points at lower densities than the density at y) be logarithimcally or linearly spaced? Appropriate for logarithmic y-axes of signal panels.tqdm_kwargs (dict) – Progress bar keyword arguments.
scale_ymin (float) – The minimum y-value to use, as a fraction of the minimum sample value.
scale_ymax (float) – The maximum y-value to use, as a fraction of the minimum sample value.
ny (int) – Number of y-values to compute the posterior mass for.
lines_on (bool) – Render contour lines?
add_label (bool) – Add contour colorbar label.
write (bool) – Write figure to disk?
extension (str) – File extension for writing.
dpi (int) – Figure write resolution.
write_kwargs (dict) – Additional writing keyword arguments.
xticks (list(list(float))) – Determine the x-tick values that will be labelled in each of the subplots (including color bars). Automatic ticks and labels are used for the specific subplot if providing None instead of a list of floats (e.g., xticks=[[0.1,0.5,1.0],None,None]). If xticks=None (default), automatic ticks and labels are used for all the subplots.
yticks (list(list(float))) – Determine the y-tick values that will be labelled in each of the subplots (including color bars). See param xticks for more details.
- abstractmethod execute(thetas, wrapper)[source]
Execute behaviours requiring a loop over samples.
- Parameters:
thetas (ndarray[n,m]) – Equally-weighted set of posterior samples.
wrapper (callable) – Wrapper function that interleaves iterative calls next(self) with code to update the
Signalinstance from a cache stored on disk. The wrapper returns a callback function, If such a cache is unavailable, the likelihood function is evaluated on-the-fly when the callback is called passing a sample (parameter vector). In this case, signals to be plotted are temporarily cached in theSignalinstance. The signature of the wrapper function is: wrapper(self, delete_me=None, index=None), where self is this a subclass ofSignalPlot, delete_me is an optional attribute name or a list of attribute name in self.__dict__ to be deleted before iterating over samples, and index is an optional integer to index a tuple returned from next(self). The signature of the callback function, if you need to call it directly (instead of an external library such as fgivenx calling it): callback(None, theta), where each sample/parameter vector is a row in thetas.
- property fig
Get the figure object.
- abstractmethod finalize()[source]
Execute instructions to finish plotting.
Before this method is called, the likelihood object will be updated so that the true (injected) signals are cached. In the body of the subclass implementation of this method, one can plot the injected signals by accessing the attributes of the signal instance.
- class xpsi.PostProcessing._postprocessor.PostProcessor(posteriors)[source]
Post-process samples for inference and posterior checking.
Base class that functions as a container for nested sampling run objects representing some set of posterior distributions that share some subset of parameters of interest that are to be plotted. The parameters can be shared in the sense that their relationship is the identity relation, or multiple physical objects in a population context each have an instance of a parameter type. An example of the former is the mass of a star, for which there are two or more distinct posterior distributions, due, e.g.:
to sequential inference conditional on independent data sets, where each posterior is an updated of the previous in the sequence;
inference conditional on independent data sets, where the different analyses invoked same [different] prior models and one simply wants to overlay the posteriors e.g., to gauge the synergy of different experiments [and argue the priors are weakly informative/ diffuse in the context of the likelihood functions];
to analysis of a single data set but the effective existence of discrete hyperparameter resulting in posteriors conditional on the discrete label over population-level prior distributions that has not been marginalized over (i.e., the problem of choosing an appropriate the hierarchical prior model);
to competing models, where models can differ in the likelihood function, prior density, or both.
An example of the latter is two more (neutron) stars, each with a mass; these masses collectively encode interesting population-level information.
Subclasses will calculate inferences, usually in the form of approximate integrals over the posterior distribution. They will also provide tools for visualisation of posterior information and derived quantities, which is useful for basic posterior predictive checking.
- Parameters:
posteriors (iterable) – An iterable of instances of
Runs.
- get_attr(attribute)[source]
Get a list of attributes of the
Runsinstances stored as the current subset.
- property params
Get the current parameter information.
- property posteriors
Get the posteriors.
- set_subset(IDs=None, combine=False, combine_all=False, force_combine=True, only_combined=False, overwrite=False, split_modes=False)[source]
Set a current list of
Runsinstances.Helper function to get and notify which runs will be plotted.
- Parameters:
IDs (OrderedDict) – A dictionary of lists, where keys match
Runsinstance IDs, and list elements matchRuninstance IDs. If no key matches aRunsinstance ID, it is assumed that all associatedRuninstances are to be selected as the current subset for plotting applications.combine (bool) – Additionally combine the runs into a single run for overplotting? The overriding setting if there is more than one underlying posterior to be plotted, is to attempt to combine runs on each posterior if multiple such runs are available, in order to reduce information density. If there is a single underlying posterior, the user-specified value is respected.
combine_all (bool) – Combine all runs in each
Runsinstance or only those for which IDs are provided? Ignored ifcombineisFalse.force_combine (bool) – Force recombination of elligible run sets, even if a combined run is already cached?
only_combined (bool) – Only plot the combined run? Only heeded if a single posterior is selected for plotting, and in that case is ignored if
combineisFalse.overwrite (bool) – Overwrite combined-sample files on disk with the same filename?
split_modes (bool) – Split posteriors by mode? Only useful for cornerplots.
- property subset
Get the current subset of posteriors for plotting.
- property subset_to_plot
Get the current subset of runs for plotting.
- class xpsi.PostProcessing._backends.NestedBackend(root, base_dir, use_nestcheck, transform=None, overwrite_transformed=False, **kwargs)[source]
Bases:
RunContainer for nested samples generated by a single run, and backends for analysis of the run.
The other keyword arguments are generic properties passed to the parent class, such as the identification (ID) string of the run.
- Parameters:
root (str) – The root filename of the sample file collection.
base_dir (str) – The directly containing the sample file collection.
use_nestcheck (bool) – Invoke
nestcheckfor nested sampling error analysis?transform (callable) – A function to transform the parameter vector to another space.
- property getdist_backend
Get the
getdist.mcsamples.MCSamplesinstance.
- property margeStats
Return the marginal statistics using
getdist.
- property nestcheck_backend
Get the
nestcheckbackend for the nested samples.
- class xpsi.PostProcessing._run.Run(filepath, **kwargs)[source]
Bases:
MetadataBase class for a sample container.
- property contours
Get the dictionary of contour arguments for
getdist.- Parameters:
contours (dict) –
getdist-compatible dictionary of parameters specifying the properties of the contours representing credible regions of the two-dimensional marginal distributions of parameters.
- property lines
Get the dictionary of line arguments for
getdist.- Parameters:
lines (dict) –
getdist-compatible dictionary of parameters specifying the properties of the smooth lines representing one-dimensional marginal distributions of parameters.
- property samples
Get a copy of the samples array.
- class xpsi.PostProcessing._metadata.Metadata(ID, names, bounds=None, labels=None, implementation=None, kde_settings=None, truths=None, precisions=None, short_labels=None)[source]
Base class to record basic information about sampling runs.
- Parameters:
ID (str) – For identification of the object.
names (list) – An ordered list of
strparameter names. The ordering must match the parameter vector ordering defined in sample backend objects.bounds (dict) – A dictionary of one-dimensional hard parameter bounds. See
getdist.mcsamples.MCSamples; the keys must match thenameslist. For the purpose of density estimation plots these bounds can be viewing bounds.labels (dict) – A dictionary of (LaTeX compatible)
strliteral parameter labels. The keys must match thenameslist. IfNone, the parameter names are used as labels.short_labels (dict) – Optional dictionary of shorter (LaTeX compatible)
strliteral parameter labels, e.g., the labels without units. These are only used to annotate the off-diagonal 2D panels of corner plots whenlabels_2D=True(seeplot()), where the concatenation of two full labels may not fit in the panel. The keys must be a subset of thenameslist: any parameter without a short label defaults to its full label fromlabels. IfNone(default), all short labels default to the full labels.implementation (str) – Sampling software applied to generate the samples. Known options are
['multinest', 'polychord', 'emcee'].kde_settings (dict) – Settings for instantiation of
getdist.mcsamples.MCSamples.truths (dict) – Optional dictionary of parameter truths, if known; if unknown leave as
None. The keys must be names which match those innames.
- property ID
Get the identification
strof the sample set.
- property bounds
Get the parameter bounds.
- property implementation
Sampling software applied to generate the samples of the run.
- property kde_settings
Get the input
getdistKDE settings dictionary.
- property labels
Get the parameter labels.
- property names
Get the parameter names.
- property parent_ID
The ID of the parent container with which a run is associated.
- property precisions
Get the parameter precisions.
- property prepend_ID
Prepend the run ID with the parent ID.
- property short_labels
Get the short parameter labels.
Parameters without a user-specified short label default to their full label.
- property short_labels_defaulted
Names of the parameters whose short label defaults to the full label because no short label was specified.
- property truth_vector
Get the parameter truths as a list.
- property truths
Get the parameter truths as a dictionary.