pycbc.results package

Submodules

pycbc.results.color module

Utilities for managing matplotlib colors and mapping ifos to color

pycbc.results.color.ifo_color(ifo)[source]
pycbc.results.color.source_color(source)[source]

pycbc.results.dq module

This module contains utilities for following up search triggers

Return a string that links to the summary page and aLOG for this ifo

Parameters:
  • ifo (string) – The detector name

  • utc_time (sequence) – First three elements must be strings giving year, month, day resp.

Returns:

return_string – String containing HTML for links to summary page and aLOG search

Return type:

string

pycbc.results.followup module

This module provides functions to generate followup plots and trigger time series.

pycbc.results.followup.coinc_timeseries_plot(coinc_file, start, end)[source]
pycbc.results.followup.columns_from_file_list(file_list, columns, ifo, start, end)[source]

Return columns of information stored in single detector trigger files.

Parameters:
  • file_list_file (string) – pickle file containing the list of single detector

  • triggers.

  • ifo (string) – The ifo to return triggers for.

  • columns (list of strings) – The list of columns to read from the trigger files.

  • start (int) – The start time to get triggers from

  • end (int) – The end time to get triggers from

Returns:

trigger_dict – A dictionary of column vectors with column names as keys.

Return type:

dict

pycbc.results.followup.times_to_urls(times, window, tag)[source]
pycbc.results.followup.trigger_timeseries_plot(file_list, ifos, start, end)[source]

pycbc.results.layout module

This module contains result page layout and numbering helper functions

class pycbc.results.layout.SectionNumber(base, secs)[source]

Bases: object

Class to help with numbering sections in an output page.

pycbc.results.layout.group_layout(path, files, **kwargs)[source]

Make a well layout in chunks of two from a list of files

path: str

Location to make the well html file

files: list of pycbc.workflow.core.Files

This list of images to show in order within the well layout html file. Every two are placed on the same row.

pycbc.results.layout.grouper(iterable, n, fillvalue=None)[source]

Group items into chunks of n length

pycbc.results.layout.single_layout(path, files, **kwargs)[source]

Make a well layout in single column format

path: str

Location to make the well html file

files: list of pycbc.workflow.core.Files

This list of images to show in order within the well layout html file.

pycbc.results.layout.two_column_layout(path, cols, unique='', **kwargs)[source]

Make a well layout in a two column format

Parameters:
  • path (str) – Location to make the well html file

  • unique (str) – String to add to end of well name. Used if you want more than one well.

  • cols (list of tuples) – The format of the items on the well result section. Each tuple contains the two files that are shown in the left and right hand side of a row in the well.html page.

pycbc.results.metadata module

This Module contains generic utility functions for creating plots within PyCBC.

class pycbc.results.metadata.MetaParser[source]

Bases: HTMLParser

handle_data(data)[source]
handle_starttag(tag, attrs)[source]
pycbc.results.metadata.html_escape(text)[source]

Sanitize text for html parsing

pycbc.results.metadata.load_html_metadata(filename)[source]

Get metadata from html file

pycbc.results.metadata.load_metadata_from_file(filename)[source]

Load the plot related metadata saved in a file

Parameters:

filename (str) – Name of file load metadata from.

Returns:

cp – A configparser object containing the metadata

Return type:

ConfigParser

pycbc.results.metadata.load_png_metadata(filename)[source]
pycbc.results.metadata.save_fig_with_metadata(fig, filename, fig_kwds=None, **kwds)[source]

Save plot to file with metadata included. Kewords translate to metadata that is stored directly in the plot file. Limited format types available.

Parameters:
  • fig (matplotlib figure) – The matplotlib figure to save to the file

  • filename (str) – Name of file to store the plot.

pycbc.results.metadata.save_html_with_metadata(fig, filename, fig_kwds, kwds)[source]

Save a html output to file with metadata

pycbc.results.metadata.save_pdf_with_metadata(fig, filename, fig_kwds, kwds)[source]

Save a matplotlib figure to a PDF file with metadata.

pycbc.results.metadata.save_png_with_metadata(fig, filename, fig_kwds, kwds)[source]

Save a matplotlib figure to a png with metadata

pycbc.results.mpld3_utils module

This module provides functionality to extend mpld3

Bases: PluginBase

Plugin for following a link on click

JAVASCRIPT = '\n    mpld3.register_plugin("clicklink", ClickLink);\n    ClickLink.prototype = Object.create(mpld3.Plugin.prototype);\n    ClickLink.prototype.constructor = ClickLink;\n    ClickLink.prototype.requiredProps = ["id"];\n    ClickLink.prototype.defaultProps = {\n        links: null\n    }\n    function ClickLink(fig, props){\n        mpld3.Plugin.call(this, fig, props);\n    };\n\n    ClickLink.prototype.draw = function(){\n        var obj = mpld3.get_element(this.props.id);\n        var links = this.props.links;\n\n        obj.elements().on("mousedown",\n                          function(d, i){\n                                           window.open(links[i]);\n                                        }\n                          );\n    }\n    '
class pycbc.results.mpld3_utils.LineTooltip(line, label=None, hoffset=0, voffset=10, css=None)[source]

Bases: LineHTMLTooltip

JAVASCRIPT = ''
class pycbc.results.mpld3_utils.MPLSlide(button=True, enabled=None)[source]

Bases: PluginBase

JAVASCRIPT = '\n         mpld3.Axes.prototype.zoomed = function(propagate) {\n            propagate = typeof propagate == "undefined" ? true : propagate;\n            if (propagate) {\n              var dt0 = this.zoom.translate()[0] - this.zoom.last_t[0];\n              var dt1 = this.zoom.translate()[1] - this.zoom.last_t[1];\n              var ds = this.zoom.scale() / this.zoom.last_s;\n              this.zoom_x.translate([ this.zoom_x.translate()[0] + dt0, 0 ]);\n              this.zoom_x.scale(this.zoom_x.scale() * ds);\n\n              this.zoom.last_t = this.zoom.translate();\n              this.zoom.last_s = this.zoom.scale();\n              this.sharex.forEach(function(ax) {\n                ax.zoom_x.translate(this.zoom_x.translate()).scale(this.zoom_x.scale());\n              }.bind(this));\n\n              this.sharex.forEach(function(ax) {\n                ax.zoomed(false);\n              });\n            }\n            for (var i = 0; i < this.elements.length; i++) {\n              this.elements[i].zoomed();\n            }\n          };\n\n            mpld3.ZoomPlugin = mpld3_ZoomPlugin;\n            mpld3.register_plugin("zoom", mpld3_ZoomPlugin);\n            mpld3_ZoomPlugin.prototype = Object.create(mpld3.Plugin.prototype);\n            mpld3_ZoomPlugin.prototype.constructor = mpld3_ZoomPlugin;\n            mpld3_ZoomPlugin.prototype.requiredProps = [];\n            mpld3_ZoomPlugin.prototype.defaultProps = {\n                button: true,\n                enabled: null\n            };\n            function mpld3_ZoomPlugin(fig, props) {\n                mpld3.Plugin.call(this, fig, props);\n                if (this.props.enabled === null) {\n                    this.props.enabled = !this.props.button;\n                }\n                var enabled = this.props.enabled;\n                if (this.props.button) {\n                    var ZoomButton = mpld3.ButtonFactory({\n                        buttonID: "zoom",\n                        sticky: true,\n                        actions: [ "scroll", "drag" ],\n                        onActivate: this.activate.bind(this),\n                        onDeactivate: this.deactivate.bind(this),\n                        onDraw: function() {\n                            this.setState(enabled);\n                        },\n                        icon: function() {\n                            return mpld3.icons["move"];\n                        }\n                    });\n                this.fig.buttons.push(ZoomButton);\n                }\n            }\n            mpld3_ZoomPlugin.prototype.activate = function() {\n                this.fig.enable_zoom();\n            };\n            mpld3_ZoomPlugin.prototype.deactivate = function() {\n                this.fig.disable_zoom();\n            };\n            mpld3_ZoomPlugin.prototype.draw = function() {\n                if (this.props.enabled) this.fig.enable_zoom(); else this.fig.disable_zoom();\n            };\n        '
class pycbc.results.mpld3_utils.Tooltip(points, labels=None, hoffset=0, voffset=10, css=None)[source]

Bases: PointHTMLTooltip

JAVASCRIPT = ''

pycbc.results.plot module

Plotting utilities and premade plot configurations

pycbc.results.plot.add_style_opt_to_parser(parser, default=None)[source]

Adds an option to set the matplotlib style to a parser.

Parameters:
  • parser (argparse.ArgumentParser) – The parser to add the option to.

  • default (str, optional) – The default style to use. Default, None, will result in the default matplotlib style to be used.

pycbc.results.plot.hist_overflow(val, val_max, **kwds)[source]

Make a histogram with an overflow bar above val_max

pycbc.results.plot.set_style_from_cli(opts)[source]

Uses the mpl-style option to set the style for plots.

Note: This will change the global rcParams.

pycbc.results.psd module

Module to generate PSD figures

pycbc.results.psd.generate_asd_plot(psddict, output_filename)[source]

Generate an ASD plot as used for upload to GraceDB.

Parameters:
  • psddict (dictionary) – A dictionary keyed on ifo containing the PSDs as FrequencySeries objects

  • output_filename (string) – The filename for the plot to be saved to

Return type:

None

pycbc.results.pygrb_plotting_utils module

Module to generate PyGRB figures: scatter plots and timeseries.

pycbc.results.pygrb_plotting_utils.axis_max_value(trig_values, inj_values, inj_file)[source]

Deterime the maximum of a quantity in the trigger and injection data

pycbc.results.pygrb_plotting_utils.contour_plotter(axis, snr_vals, contours, colors, vert_spike=False)[source]

Plot contours in a scatter plot where SNR is on the horizontal axis

pycbc.results.pygrb_plotting_utils.make_grb_segments_plot(wkflow, science_segs, trigger_time, trigger_name, out_dir, coherent_seg=None, fail_criterion=None)[source]

Plot trigger time and offsource extent over segments

pycbc.results.pygrb_plotting_utils.pygrb_plotter(trigs, injs, xlabel, ylabel, opts, snr_vals=None, conts=None, shade_cont_value=None, colors=None, vert_spike=False, cmd=None)[source]

Master function to plot PyGRB results

pycbc.results.pygrb_postprocessing_utils module

Module to generate PyGRB figures: scatter plots and timeseries.

pycbc.results.pygrb_postprocessing_utils.construct_trials(seg_files, seg_dict, ifos, slide_dict, vetoes)[source]

Constructs trials from triggers, timeslides, segments and vetoes

pycbc.results.pygrb_postprocessing_utils.extract_basic_trig_properties(trial_dict, trigs, slide_dict, seg_dict)[source]

Extract and store as dictionaries time, SNR, and BestNR of time-slid triggers

pycbc.results.pygrb_postprocessing_utils.extract_ifos(trig_file)[source]

Extracts IFOs from hdf file

pycbc.results.pygrb_postprocessing_utils.extract_ifos_and_vetoes(trig_file, veto_files, veto_cat)[source]

Extracts IFOs from HDF files and vetoes from a directory

pycbc.results.pygrb_postprocessing_utils.get_antenna_dist_factor(antenna, ra, dec, geocent_time, inc=0.0)[source]

Returns the antenna factors (defined as eq. 4.3 on page 57 of Duncan Brown’s Ph.D.) for an IFO (passed as pycbc Detector type) at a given sky location and time.

pycbc.results.pygrb_postprocessing_utils.get_bestnrs(trigs, q=4.0, n=3.0, null_thresh=(4.25, 6), snr_threshold=6.0, sngl_snr_threshold=4.0, chisq_threshold=None, null_grad_thresh=20.0, null_grad_val=0.2)[source]

Calculate BestNR (coh_PTF detection statistic) of triggers through signal based vetoes. The (default) signal based vetoes are: * Coherent SNR < 6 * Bank chi-squared reduced (new) SNR < 6 * Auto veto reduced (new) SNR < 6 * Single-detector SNR (from two most sensitive IFOs) < 4 * Null SNR (CoincSNR^2 - CohSNR^2)^(1/2) < null_thresh

Returns Numpy array of BestNR values.

pycbc.results.pygrb_postprocessing_utils.get_coinc_snr(trigs_or_injs, ifos)[source]

Calculate coincident SNR using single IFO SNRs

pycbc.results.pygrb_postprocessing_utils.load_injections(inj_file, vetoes, sim_table=False, label=None)[source]

Loads injections from PyGRB output file

pycbc.results.pygrb_postprocessing_utils.load_segment_dict(hdf_file_path)[source]

Loads the segment dictionary with the format {slide_id: segmentlist(segments analyzed)}

pycbc.results.pygrb_postprocessing_utils.load_time_slides(hdf_file_path)[source]

Loads timeslides from PyGRB output file as a dictionary

pycbc.results.pygrb_postprocessing_utils.load_triggers(input_file, vetoes)[source]

Loads triggers from PyGRB output file

pycbc.results.pygrb_postprocessing_utils.load_xml_table(file_name, table_name)[source]

Load xml table from file.

pycbc.results.pygrb_postprocessing_utils.max_median_stat(slide_dict, time_veto_max_stat, trig_stat, total_trials)[source]

Deterine the maximum and median of the loudest SNRs/BestNRs

pycbc.results.pygrb_postprocessing_utils.mc_cal_wf_errs(num_mc_injs, inj_dists, cal_err, wf_err, max_dc_cal_err)[source]

Includes calibration and waveform errors by running an MC

pycbc.results.pygrb_postprocessing_utils.pygrb_add_bestnr_opts(parser)[source]

Add to the parser object the arguments used for BestNR calculation.

pycbc.results.pygrb_postprocessing_utils.pygrb_add_injmc_opts(parser)[source]

Add to parser object the arguments used for Monte-Carlo on distance.

pycbc.results.pygrb_postprocessing_utils.pygrb_initialize_plot_parser(description=None, version=None)[source]

Sets up a basic argument parser object for PyGRB plotting scripts

pycbc.results.pygrb_postprocessing_utils.sort_stat(time_veto_max_stat)[source]

Sort a dictionary of loudest SNRs/BestNRs

pycbc.results.pygrb_postprocessing_utils.sort_trigs(trial_dict, trigs, slide_dict, seg_dict)[source]

Constructs sorted triggers from a trials dictionary

pycbc.results.pygrb_postprocessing_utils.template_hash_to_id(trigger_file, bank_path)[source]

This function converts the template hashes from a trigger file into ‘template_id’s that represent indices of the templates within the bank. :param trigger_file: :type trigger_file: h5py File object for trigger file :param bank_file: :type bank_file: filepath for template bank

pycbc.results.render module

pycbc.results.render.get_embedded_config(filename)[source]

Attempt to load config data attached to file

pycbc.results.render.render_default(path, cp)[source]

This is the default function that will render a template to a string of HTML. The string will be for a drop-down tab that contains a link to the file.

If the file extension requires information to be read, then that is passed to the content variable (eg. a segmentlistdict).

pycbc.results.render.render_glitchgram(path, cp)[source]

Render a glitchgram file template.

pycbc.results.render.render_ignore(path, cp)[source]

Does not render anything.

pycbc.results.render.render_text(path, cp)[source]

Render a file as text.

pycbc.results.render.render_tmplt(path, cp)[source]

Render a file as text.

pycbc.results.render.render_workflow_html_template(filename, subtemplate, filelists, **kwargs)[source]

Writes a template given inputs from the workflow generator. Takes a list of tuples. Each tuple is a pycbc File object. Also the name of the subtemplate to render and the filename of the output.

pycbc.results.render.setup_template_render(path, config_path)[source]

This function is the gateway for rendering a template for a file.

pycbc.results.scatter_histograms module

Module to generate figures with scatter plots and histograms.

pycbc.results.scatter_histograms.construct_kde(samples_array, use_kombine=False, kdeargs=None)[source]

Constructs a KDE from the given samples.

Parameters:
  • samples_array (array) – Array of values to construct the KDE for.

  • use_kombine (bool, optional) – Use kombine’s clustered KDE instead of scipy’s. Default is False.

  • kdeargs (dict, optional) – Additional arguments to pass to the KDE. Can be any argument recognized by scipy.stats.gaussian_kde() or kombine.clustered_kde.optimized_kde(). In either case, you can also set max_kde_samples to limit the number of samples that are used for KDE construction.

Returns:

The KDE.

Return type:

kde

pycbc.results.scatter_histograms.create_axes_grid(parameters, labels=None, height_ratios=None, width_ratios=None, no_diagonals=False)[source]

Given a list of parameters, creates a figure with an axis for every possible combination of the parameters.

Parameters:
  • parameters (list) – Names of the variables to be plotted.

  • labels ({None, dict}, optional) – A dictionary of parameters -> parameter labels.

  • height_ratios ({None, list}, optional) – Set the height ratios of the axes; see matplotlib.gridspec.GridSpec for details.

  • width_ratios ({None, list}, optional) – Set the width ratios of the axes; see matplotlib.gridspec.GridSpec for details.

  • no_diagonals ({False, bool}, optional) – Do not produce axes for the same parameter on both axes.

Returns:

  • fig (pyplot.figure) – The figure that was created.

  • axis_dict (dict) – A dictionary mapping the parameter combinations to the axis and their location in the subplots grid; i.e., the key, values are: {(‘param1’, ‘param2’): (pyplot.axes, row index, column index)}

pycbc.results.scatter_histograms.create_density_plot(xparam, yparam, samples, plot_density=True, plot_contours=True, percentiles=None, cmap='viridis', contour_color=None, label_contours=True, contour_linestyles=None, xmin=None, xmax=None, ymin=None, ymax=None, exclude_region=None, fig=None, ax=None, use_kombine=False, kdeargs=None)[source]

Computes and plots posterior density and confidence intervals using the given samples.

Parameters:
  • xparam (string) – The parameter to plot on the x-axis.

  • yparam (string) – The parameter to plot on the y-axis.

  • samples (dict, numpy structured array, or FieldArray) – The samples to plot.

  • plot_density ({True, bool}) – Plot a color map of the density.

  • plot_contours ({True, bool}) – Plot contours showing the n-th percentiles of the density.

  • percentiles ({None, float or array}) – What percentile contours to draw. If None, will plot the 50th and 90th percentiles.

  • cmap ({'viridis', string}) – The name of the colormap to use for the density plot.

  • contour_color ({None, string}) – What color to make the contours. Default is white for density plots and black for other plots.

  • label_contours (bool, optional) – Whether to label the contours. Default is True.

  • contour_linestyles (list, optional) – Linestyles to use for the contours. Default (None) will use solid.

  • xmin ({None, float}) – Minimum value to plot on x-axis.

  • xmax ({None, float}) – Maximum value to plot on x-axis.

  • ymin ({None, float}) – Minimum value to plot on y-axis.

  • ymax ({None, float}) – Maximum value to plot on y-axis.

  • exclue_region ({None, str}) – Exclude the specified region when plotting the density or contours. Must be a string in terms of xparam and yparam that is understandable by numpy’s logical evaluation. For example, if xparam = m_1 and yparam = m_2, and you want to exclude the region for which m_2 is greater than m_1, then exclude region should be ‘m_2 > m_1’.

  • fig ({None, pyplot.figure}) – Add the plot to the given figure. If None and ax is None, will create a new figure.

  • ax ({None, pyplot.axes}) – Draw plot on the given axis. If None, will create a new axis from fig.

  • use_kombine ({False, bool}) – Use kombine’s KDE to calculate density. Otherwise, will use scipy.stats.gaussian_kde. Default is False.

  • kdeargs (dict, optional) – Pass the given keyword arguments to the KDE.

Returns:

  • fig (pyplot.figure) – The figure the plot was made on.

  • ax (pyplot.axes) – The axes the plot was drawn on.

pycbc.results.scatter_histograms.create_marginalized_hist(ax, values, label, percentiles=None, color='k', fillcolor='gray', linecolor='navy', linestyle='-', plot_marginal_lines=True, title=True, expected_value=None, expected_color='red', rotated=False, plot_min=None, plot_max=None)[source]

Plots a 1D marginalized histogram of the given param from the given samples.

Parameters:
  • ax (pyplot.Axes) – The axes on which to draw the plot.

  • values (array) – The parameter values to plot.

  • label (str) – A label to use for the title.

  • percentiles ({None, float or array}) – What percentiles to draw lines at. If None, will draw lines at [5, 50, 95] (i.e., the bounds on the upper 90th percentile and the median).

  • color ({'k', string}) – What color to make the histogram; default is black.

  • fillcolor ({'gray', string, or None}) – What color to fill the histogram with. Set to None to not fill the histogram. Default is ‘gray’.

  • plot_marginal_lines (bool, optional) – Put vertical lines at the marginal percentiles. Default is True.

  • linestyle (str, optional) – What line style to use for the histogram. Default is ‘-‘.

  • linecolor ({'navy', string}) – What color to use for the percentile lines. Default is ‘navy’.

  • title (bool, optional) – Add a title with a estimated value +/- uncertainty. The estimated value is the pecentile halfway between the max/min of percentiles, while the uncertainty is given by the max/min of the percentiles. If no percentiles are specified, defaults to quoting the median +/- 95/5 percentiles.

  • rotated ({False, bool}) – Plot the histogram on the y-axis instead of the x. Default is False.

  • plot_min ({None, float}) – The minimum value to plot. If None, will default to whatever pyplot creates.

  • plot_max ({None, float}) – The maximum value to plot. If None, will default to whatever pyplot creates.

  • scalefac ({1., float}) – Factor to scale the default font sizes by. Default is 1 (no scaling).

pycbc.results.scatter_histograms.create_multidim_plot(parameters, samples, labels=None, mins=None, maxs=None, expected_parameters=None, expected_parameters_color='r', plot_marginal=True, plot_scatter=True, plot_maxl=False, plot_marginal_lines=True, marginal_percentiles=None, contour_percentiles=None, marginal_title=True, marginal_linestyle='-', zvals=None, show_colorbar=True, cbar_label=None, vmin=None, vmax=None, scatter_cmap='plasma', plot_density=False, plot_contours=True, density_cmap='viridis', contour_color=None, label_contours=True, contour_linestyles=None, hist_color='black', line_color=None, fill_color='gray', use_kombine=False, kdeargs=None, fig=None, axis_dict=None)[source]

Generate a figure with several plots and histograms.

Parameters:
  • parameters (list) – Names of the variables to be plotted.

  • samples (FieldArray) – A field array of the samples to plot.

  • labels (dict, optional) – A dictionary mapping parameters to labels. If none provided, will just use the parameter strings as the labels.

  • mins ({None, dict}, optional) – Minimum value for the axis of each variable in parameters. If None, it will use the minimum of the corresponding variable in samples.

  • maxs ({None, dict}, optional) – Maximum value for the axis of each variable in parameters. If None, it will use the maximum of the corresponding variable in samples.

  • expected_parameters ({None, dict}, optional) – Expected values of parameters, as a dictionary mapping parameter names -> values. A cross will be plotted at the location of the expected parameters on axes that plot any of the expected parameters.

  • expected_parameters_color ({'r', string}, optional) – What color to make the expected parameters cross.

  • plot_marginal ({True, bool}) – Plot the marginalized distribution on the diagonals. If False, the diagonal axes will be turned off.

  • plot_scatter ({True, bool}) – Plot each sample point as a scatter plot.

  • marginal_percentiles ({None, array}) – What percentiles to draw lines at on the 1D histograms. If None, will draw lines at [5, 50, 95] (i.e., the bounds on the upper 90th percentile and the median).

  • marginal_title (bool, optional) – Add a title over the 1D marginal plots that gives an estimated value +/- uncertainty. The estimated value is the pecentile halfway between the max/min of maginal_percentiles, while the uncertainty is given by the max/min of the marginal_percentiles. If no ``marginal_percentiles are specified, the median +/- 95/5 percentiles will be quoted.

  • marginal_linestyle (str, optional) – What line style to use for the marginal histograms.

  • contour_percentiles ({None, array}) – What percentile contours to draw on the scatter plots. If None, will plot the 50th and 90th percentiles.

  • zvals ({None, array}) – An array to use for coloring the scatter plots. If None, scatter points will be the same color.

  • show_colorbar ({True, bool}) – Show the colorbar of zvalues used for the scatter points. A ValueError will be raised if zvals is None and this is True.

  • cbar_label ({None, str}) – Specify a label to add to the colorbar.

  • vmin ({None, float}, optional) – Minimum value for the colorbar. If None, will use the minimum of zvals.

  • vmax ({None, float}, optional) – Maximum value for the colorbar. If None, will use the maxmimum of zvals.

  • scatter_cmap ({'plasma', string}) – The color map to use for the scatter points. Default is ‘plasma’.

  • plot_density ({False, bool}) – Plot the density of points as a color map.

  • plot_contours ({True, bool}) – Draw contours showing the 50th and 90th percentile confidence regions.

  • density_cmap ({'viridis', string}) – The color map to use for the density plot.

  • contour_color ({None, string}) – The color to use for the contour lines. Defaults to white for density plots, navy for scatter plots without zvals, and black otherwise.

  • label_contours (bool, optional) – Whether to label the contours. Default is True.

  • contour_linestyles (list, optional) – Linestyles to use for the contours. Default (None) will use solid.

  • use_kombine ({False, bool}) – Use kombine’s KDE to calculate density. Otherwise, will use scipy.stats.gaussian_kde. Default is False.

  • kdeargs (dict, optional) – Pass the given keyword arguments to the KDE.

  • fig (pyplot.figure) – Use the given figure instead of creating one.

  • axis_dict (dict) – Use the given dictionary of axes instead of creating one.

Returns:

  • fig (pyplot.figure) – The figure that was created.

  • axis_dict (dict) – A dictionary mapping the parameter combinations to the axis and their location in the subplots grid; i.e., the key, values are: {(‘param1’, ‘param2’): (pyplot.axes, row index, column index)}

pycbc.results.scatter_histograms.get_scale_fac(fig, fiducial_width=8, fiducial_height=7)[source]

Gets a factor to scale fonts by for the given figure. The scale factor is relative to a figure with dimensions (fiducial_width, fiducial_height).

pycbc.results.scatter_histograms.reduce_ticks(ax, which, maxticks=3)[source]

Given a pyplot axis, resamples its which-axis ticks such that are at most maxticks left.

Parameters:
  • ax (axis) – The axis to adjust.

  • which ({'x' | 'y'}) – Which axis to adjust.

  • maxticks ({3, int}) – Maximum number of ticks to use.

Returns:

An array of the selected ticks.

Return type:

array

pycbc.results.scatter_histograms.remove_common_offset(arr)[source]

Given an array of data, removes a common offset > 1000, returning the removed value.

pycbc.results.scatter_histograms.set_marginal_histogram_title(ax, fmt, color, label=None, rotated=False)[source]

Sets the title of the marginal histograms.

Parameters:
  • ax (Axes) – The Axes instance for the plot.

  • fmt (str) – The string to add to the title.

  • color (str) – The color of the text to add to the title.

  • label (str) – If title does not exist, then include label at beginning of the string.

  • rotated (bool) – If True then rotate the text 270 degrees for sideways title.

pycbc.results.snr module

Module to generate SNR figures

pycbc.results.snr.generate_snr_plot(snrdict, output_filename, triggers, ref_time)[source]

Generate an SNR timeseries plot as used for upload to GraceDB.

Parameters:
  • snrdict (dictionary) – A dictionary keyed on ifo containing the SNR TimeSeries objects

  • output_filename (string) – The filename for the plot to be saved to

  • triggers (dictionary of tuples) – A dictionary keyed on IFO, containing (trigger time, trigger snr)

  • ref_time (number, GPS seconds) – Reference time which will be used as the zero point of the plot This should be an integer value, but doesn’t need to be an integer

Return type:

None

pycbc.results.str_utils module

This modules provides functions for formatting values into strings for display.

pycbc.results.str_utils.drop_trailing_zeros(num)[source]

Drops the trailing zeros in a float that is printed.

pycbc.results.str_utils.format_value(value, error, plus_error=None, use_scientific_notation=3, include_error=True, use_relative_error=False, ndecs=None)[source]

Given a numerical value and some bound on it, formats the number into a string such that the value is rounded to the nearest significant figure, which is determined by the error = abs(value-bound).

Note: if either use_scientific_notation or include_error are True, the returned string will include LaTeX characters.

Parameters:
  • value (float) – The value to format.

  • error (float) – The uncertainty in the value. This is used to determine the number of significant figures to print. If the value has no uncertainty, you can just do value*1e-k, where k+1 is the number of significant figures you want.

  • plus_error ({None, float}) – The upper uncertainty on the value; i.e., what you need to add to the value to get its upper bound. If provided, error is assumed to be the negative; i.e., value +plus_error -error. The number of significant figures printed is determined from min(error, plus_error).

  • use_scientific_notation (int, optional) – If abs(log10(value)) is greater than the given, the return string will be formated to “%.1f times 10^{p}”, where p is the powers of 10 needed for the leading number in the value to be in the singles spot. Otherwise will return “%.(p+1)f”. Default is 3. To turn off, set to numpy.inf. Note: using scientific notation assumes that the returned value will be enclosed in LaTeX math mode.

  • include_error ({True, bool}) – Include the error in the return string; the output will be formated val pm err, where err is the error rounded to the same power of 10 as val. Otherwise, just the formatted value will be returned. If plus_error is provided then the return text will be formatted as val^{+plus_error}_{-error}.

  • use_relative_error ({False, bool}) – If include_error, the error will be formatted as a percentage of the the value.

  • ndecs ({None, int}) – Number of values after the decimal point. If not provided, it will default to the number of values in the error.

Returns:

The value (and error, if include_error is True) formatted as a string.

Return type:

string

Examples

Given a value and its uncertainty:

>>> val, err
(3.9278372067613837e-22, 2.2351435286500487e-23)

Format with error quoted:

>>> format_value(val, err)
'3.93 \pm 0.22\times 10^{-22}'

Quote error as a relative error:

>>> format_value(val, err, use_relative_error=True)
'3.93 \times 10^{-22} \pm5.6\%'

Format without the error and without scientific notation:

>>> format_value(val, err, use_scientific_notation=float('inf'),
                 include_error=False)
'0.000000000000000000000393'

Given an plus error:

>>> err_plus
8.2700310560051804e-24

Format with both bounds quoted:

>>> format_value(val, err, plus_error=err_plus)
'3.928^{+0.083}_{-0.224}\times 10^{-22}'

Format with both bounds quoted as a relative error:

>>> format_value(val, err, plus_error=err_plus, use_relative_error=True)
'3.928\times 10^{-22}\,^{+2.1\%}_{-5.7\%}'
pycbc.results.str_utils.get_signum(val, err, max_sig=inf)[source]

Given an error, returns a string for val formated to the appropriate number of significant figures.

pycbc.results.str_utils.mathjax_html_header()[source]

Standard header to use for html pages to display latex math.

Returns:

header – The necessary html head needed to use latex on an html page.

Return type:

str

pycbc.results.table_utils module

This module provides functions to generate sortable html tables

pycbc.results.table_utils.html_table(columns, names, page_size=None, format_strings=None)[source]

Return an html table of this data

Parameters:
  • columns (list of numpy arrays) –

  • names (list of strings) – The list of columns names

  • page_size ({int, None}, optional) – The number of items to show on each page of the table

  • format_strings ({lists of strings, None}, optional) – The ICU format string for this column, None for no formatting. All

  • provided. (columns must have a format string if) –

Returns:

html_table – A str containing the html code to display a table of this data

Return type:

str

pycbc.results.table_utils.static_table(data, titles=None)[source]

Return an html tableo of this data

Parameters:
  • data (two-dimensional numpy string array) – Array containing the cell values

  • titles (numpy array) – Vector str of titles

Returns:

html_table – A string containing the html table.

Return type:

str

pycbc.results.versioning module

pycbc.results.versioning.get_code_version_numbers(executable_names, executable_files)[source]

Will extract the version information from the executables listed in the executable section of the supplied ConfigParser object.

Returns:

A dictionary keyed by the executable name with values giving the version string for each executable.

Return type:

dict

pycbc.results.versioning.get_library_version_info()[source]

This will return a list of dictionaries containing versioning information about the various LIGO libraries that PyCBC will use in an analysis run.

Module contents