mbank.utils

Some utilities for mbank, where you find lots of useful stuff for some boring operations on the templates. It keeps functions for plotting, injection recovery computation, I/O operations with ligo xml format and other useful operations useful for the package.

class DefaultSimInspiralTable(*args, **kwargs)[source]

This is a copy of ligo.lw.lsctables.SimInspiralTable with implemented defaults. Implemented as in sbank.waveform

Construct an element. The argument is a sax.xmlreader.AttributesImpl object (see the xml.sax documentation, but it’s basically a dictionary-like thing) used to set the element attributes.

class DefaultSnglInspiralTable(*args, **kwargs)[source]

This is a copy of ligo.lw.lsctables.SnglInspiralTable with implemented defaults. Implemented as in sbank.waveform

Construct an element. The argument is a sax.xmlreader.AttributesImpl object (see the xml.sax documentation, but it’s basically a dictionary-like thing) used to set the element attributes.

class LIGOLWContentHandler(document, start_handlers={})[source]

Initialize the handler by pointing it to the Document object into which the parsed file will be loaded.

avg_dist(avg_match, D)[source]

The average distance between templates such that an injection have an average match with a cubic lattice of templates. This sets the spacing between templates.

Parameters:

MM (float) – Minimum match

Returns:

avg_dist – Average distance between templates

Return type:

float

clip_eigenvalues(metric, min_eig=0.05)[source]

Given a metric, it sets to min_eig the eigenvalues of the metric which are lower than min_eig.

Parameters:
  • metric (ndarray) – shape: (D,D)/(N,D,D) - A D dimensional metric

  • min_eig (float) – The minimum value for the eigenvalues. The metric will be changed accordingly

Returns:

trimmed_metric – shape: (D,D)/(N,D,D) - The clipped-eigenvalues D dimensional metric

Return type:

ndarray

compute_injections_match(inj_dict, bank, metric_obj, mchirp_window=0.1, symphony_match=False, worker_id=None, verbose=True)[source]

Given an injection dictionary, generated by compute_injections_metric_match() it computes the actual match (not the metric approximation) between injections and templates of a given bank. It updates the match and id_match entries of inj_dict with the newly computed match values. The injections are generic (not necessarly projected on the bank submanifold).

For each injection, it identifies the templates within the mchirp window. At a second stage, it loops on the templates and computes the injection match, whenever required.

Parameters:
  • inj_dict (dict) – A dictionary with the data injection as computed by compute_injections_metric_match().

  • bank (mbank.bank.cbc_bank) – A bank object

  • metric_obj (cbc_metric) – A cbc_metric object to compute the match with.

  • mchirp_window (float) – Window in mchirp where the match between templates and injections is evaluated. The window is expressed in terms of \(\Delta\mathcal{M}/\mathcal{M}\), where \(\Delta\mathcal{M}\) is the distance in chirp mass between injection and each template

  • symphony_match (bool) – Whether to use the symphony match

  • worker_id ('int') – Id of the ray worker being used. If None, it is assumed that ray is not called

  • verbose ('bool') – Whether to print the output

Returns:

inj_dict – The output dictionary with the updated matches

Return type:

dict

compute_injections_metric_match(inj_dict, bank, tiling, verbose=True)[source]

Computes the match of the injections in inj_dict with the bank by using the metric approximation. It makes use of a brute force approach where each injection is checked against each template of the bank. The metric used is the one of the tile each injection belongs to.

It updates the entries id_tile, metric_match and id_metric_match of the injection stat dictionary.

Parameters:
  • inj_dict (dict) – A valid injection stat dictionary with injections. Can be easily filled with initialize_inj_stat_dict()

  • bank (cbc_bank) – A cbc_bank object

  • tiling (tiling_handler) – A tiling object to compute the metric match between templates and injections

  • verbose (bool) – Whether to print the output

Returns:

inj_dict – The updated injection stat dictionary with the result of metric fitting factor computation

Return type:

dict

get_antenna_patterns(longitude, latitude, polarization)[source]

Returns the antenna pattern functions \(F_+, F_\times\) for an hypotetical interferometer located at the north pole. Antenna patterns are defined in terms of the longitude and latitude (sky location) \(\alpha, \delta\) and the polarization angle angle \(\Psi\) as:

\[ \begin{align}\begin{aligned}F_+ = - \frac{1}{2}(1 + \cos(\theta^2)) \cos(2\alpha) \cos(2\Psi) - \cos(\theta)\sin(2\alpha)\sin(2\Psi)\\F_\times = \frac{1}{2}(1 + \cos(\theta^2)) \cos(2\alpha) \sin(2\Psi) - \cos(\theta)\sin(2\alpha)\cos(2\Psi)\end{aligned}\end{align} \]

where \(\theta = \frac{\pi}{2} - \delta\).

See pycbc.detector for more information.

Parameters:
  • longitude (ndarray) – shape: (N,)/() - Longitude of the source (right ascension)

  • latitude (ndarray) – shape: (N,)/() - Latitude of the source (declination)

  • polarization (ndarray) – shape: (N,)/() - Polarization angle

Returns:

  • F_p (ndarray) – shape: (N,)/() - Values for the plus antenna pattern

  • F_c (ndarray) – shape: (N,)/() - Values for the cross antenna pattern

get_boundaries_from_ranges(variable_format, M_range, q_range, s1_range=(-0.99, 0.99), s2_range=(-0.99, 0.99), chi_range=(-0.99, 0.99), theta_range=(-3.141592653589793, 3.141592653589793), phi_range=(-1.5707963267948966, 1.5707963267948966), iota_range=(0, 3.141592653589793), ref_phase_range=(-3.141592653589793, 3.141592653589793), e_range=(0.0, 0.5), meanano_range=(0.1, 1.0))[source]

Given the ranges of each quantity, it combines them in a bondary array, suitable for other uses in the package (for instance in the bank generation). No checks are performed whether the given ranges make sense.

Parameters:
  • variable_format (str) – A string to specify the variable format. See mbank.handlers.variable_handler for more information

  • M_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the variable_format If mchirpeta mass format is set, M_range and q_range are interpreted as mchirp and eta respectively. If logMq mass format is set, M_range is still interpreted as the mass and not the log mass.

  • q_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the variable_format If mchirpeta mass format is set, M_range and q_range are interpreted as mchirp and eta respectively. If logMq mass format is set, M_range is still interpreted as the mass and not the log mass.

  • s1_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the variable_format If mchirpeta mass format is set, M_range and q_range are interpreted as mchirp and eta respectively. If logMq mass format is set, M_range is still interpreted as the mass and not the log mass.

  • s2_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the variable_format If mchirpeta mass format is set, M_range and q_range are interpreted as mchirp and eta respectively. If logMq mass format is set, M_range is still interpreted as the mass and not the log mass.

  • chi_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the variable_format If mchirpeta mass format is set, M_range and q_range are interpreted as mchirp and eta respectively. If logMq mass format is set, M_range is still interpreted as the mass and not the log mass.

  • theta_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the variable_format If mchirpeta mass format is set, M_range and q_range are interpreted as mchirp and eta respectively. If logMq mass format is set, M_range is still interpreted as the mass and not the log mass.

  • phi_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the variable_format If mchirpeta mass format is set, M_range and q_range are interpreted as mchirp and eta respectively. If logMq mass format is set, M_range is still interpreted as the mass and not the log mass.

  • iota_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the variable_format If mchirpeta mass format is set, M_range and q_range are interpreted as mchirp and eta respectively. If logMq mass format is set, M_range is still interpreted as the mass and not the log mass.

  • ref_phase_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the variable_format If mchirpeta mass format is set, M_range and q_range are interpreted as mchirp and eta respectively. If logMq mass format is set, M_range is still interpreted as the mass and not the log mass.

  • e_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the variable_format If mchirpeta mass format is set, M_range and q_range are interpreted as mchirp and eta respectively. If logMq mass format is set, M_range is still interpreted as the mass and not the log mass.

  • meanano_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the variable_format If mchirpeta mass format is set, M_range and q_range are interpreted as mchirp and eta respectively. If logMq mass format is set, M_range is still interpreted as the mass and not the log mass.

Returns:

boundaries – shape (2,D) - An array with the boundaries.

Return type:

ndarray

get_ellipse(metric, center, dist, **kwargs)[source]

Given a two dimensional metric and a center, it returns the matplotlib.Patch that represent the points at constant distance dist according to the metric. It accepts as an additional parameter, anything that can be given to matplotlib.patches.Ellipse.

Parameters:
  • metric (ndarray) – shape: (2,2) - A two dimensional metric

  • center (ndarray) – shape: (2,) - The center for the ellipse

  • dist (float) – The distance between points

Returns:

ellipse – The ellips of constant match

Return type:

matplotlib.patches.Ellipse

get_projected_metric(metric, min_eig=0.0001)[source]

Given a metric \(M\), it applies the projector operator \(P\) along the eigen-direction with eigenvalue smaller than min_eig.

The resulting metric is obtained as:

\[M' = PMP\]
Parameters:
  • metric (ndarray) – shape: (D,D) - A D dimensional metric

  • min_eig (float) – Minimum tolerable eigenvalue for metric. The metric will be projected on the directions of smaller eigenvalues

Returns:

metric_projected – shape: (D,D) - The D dimensional metric projected along the large eigenvalues

Return type:

ndarray

get_projector(*directions)[source]

Given a set of orthogonal directions it computes the projector matrix \(P\) on the orthogonal space. This means that for each direction \(d\) in directions and each point \(x\) of the space:

\[<d, Px> = 0\]

See this stack exchange page for more info.

Parameters:

directions (list) – List of the orthogonal directions d that defines the projector. Each direction has dimension D.

Returns:

metric – shape: (D,D) - The projector (a D dimensional metric)

Return type:

ndarray

get_random_sky_loc(N=None, seed=None)[source]

Returns a random value for the sky location \(\alpha, \delta\) and the polarization angle \(\Psi\): The values for the sky location are randomly drawn uniformly across the sky and the polarization angle is uniformly extracted in the range \([-\pi,\pi]\).

Parameters:
  • N (int) – Number of pattern values to be extracted If None, one value will be extraced and the returned arrays will be one dimensional.

  • seed (int) – A random seed for the sky location and polarization angles

Returns:

  • longitude (ndarray) – shape: (N,)/() - Longitude of the source (right ascension)

  • latitude (ndarray) – shape: (N,)/() - Latitude of the source (declination)

  • polarization (ndarray) – shape: (N,)/() - Polarization angle

initialize_inj_stat_dict(injs, sky_locs=None)[source]

Creates an injection stat dictionary for the given injections and (possibly) sky localization. The injection stat dictionary can be passed to compute_injections_metric_match() and/or compute_injections_match() which fill the relevant entries, with the results of fitting factors calculations.

An injection stat dictionary is dictionary with entries:

Parameters:
  • injs (ndarray) – shape: (N,12) - A set of injections. They must be in the full format of the mbank.metric.cbc_metric.get_BBH_components(). Each row keeps the following entries: m1, m2, s1x, s1y, s1z, s2x, s2y, s2z, e, meanano, iota, phi

  • sky_locs (ndarray) – shape (N,3) - Sky localization for the injections. Each row corresponds to longitude, latitude and polarization angle for the injections. Sky localization will be used to compute the antenna pattern: see get_random_sky_loc() and get_antenna_patterns() for more information. If None, only the plus polarization will be used for injection recovery: this can only happens if the standard match is used (symphony = False in compute_injections_match()).

Returns:

inj_dict – An injection stat dictionary

Return type:

dict

load_PSD(filename, asd=False, ifo='H1', df=None)[source]

Loads a PSD from file and returns a grid of frequency and PSD values

Parameters:
  • filename (str) – Name of the file to load the PSD from (can be a txt file or an xml file)

  • asd (bool) – Whether the file contains an ASD rather than a PSD

  • ifo (str) – Interferometer which the PSD refers to. Only for loading a PSD from xml

  • df (float) – Spacing for the grid on which the PSD is evaluated. It controls the resolution of the PSD (and also the speed of metric computation) If None is given, the grid of the PSD won’t be changed

Returns:

  • f (ndarray) – Frequency grid

  • PSD (ndarray) – PSD evaluated on the frequency grid

load_inj_stat_dict(filename)[source]

Loads an injection statistics dictionary (see :func`compute_injections_match`) from a json or pickle file.

Parameters:

filename (str) – Filename to load the dictionary from.

Returns:

inj_stat_dict – A dictionary with the results of an injection study. It can be generated by :func`compute_injections_match` and compute_injections_metric_match().

Return type:

dict

partition_tiling(thresholds, d, tiling)[source]

Given a tiling, it partitions the tiling given a list of thresholds. The splitting is performed along axis d.

Parameters:
  • thresholds (list) – list of trhesholds for the partitioning

  • d (int) – Axis to split the tiling along.

  • tiling (tiling_handler) – Tiling to partion

Returns:

partitions – List of tiling handlers making the partitions

Return type:

list

plawspace(start, stop, exp, N_points)[source]

Generates a grid which is power law distributed. It has almost the same behaviour as logspace(). Helpful for a nice grid spacing in the mass sector.

Parameters:
  • start (float) – Starting point of the grid

  • end (float) – End point of the grid

  • exp (float) – Exponent for the equally space points

  • N_points (int) – Number of points to include in the grid

plot_colormap(datapoints, values, variable_format, statistics='mean', bins=10, fs=15, values_label=None, savefile=None, show=False, title=None)[source]

Plots a colormap values for the given datapoints

Parameters:
  • datapoints (ndarray) – shape: (N,D) - Datapoints to plot. They must be compatible with the chosen variable format

  • values (ndarray) – shape: (N,D) - Datapoints to plot. They must be compatible with the chosen variable format

  • variable_format (str) – How to handle the BBH variables.

  • statistics (str) – Statistics to use for the binned_statistic_2d()

  • bins (int) – Bins to use along each dimension (as in binned_statistic_2d())

  • fs (int) – Font size for the labels and axis

  • values_label (str) – Labels for the colorbar.

  • savefile (str) – File where to save the plots. If None, no plots will be saved

  • show (bool) – Whether to show the plots

  • title (str) – A title for all the plots

plot_match_histogram(matches_metric=None, matches=None, mm=None, bank_name=None, save_folder=None)[source]

Makes a simple histogram of the injection recovery.

Parameters:
  • matches_metric (ndarray) – shape: (N,) - Values for the matches computed by the metric, if any.

  • matches (ndarray) – shape: (N,) - Values for the true matches, if any.

  • mm (float) – Minimum match requirement used to create the bank. Used for visualization purposes.

  • bank_name (str) – Name of the bank tested. Used to set a title.

  • save_folder (str) – Folder where to save the plots If None, no plots will be saved

plot_tiles_templates(templates, variable_format, tiling=None, injections=None, inj_cmap=None, dist_ellipse=None, save_folder=None, fs=15, show=False, savetag='', title=None)[source]

Make some plots of a bunch of templates, possibly with a tiling and/or injections

Parameters:
  • templates (ndarray) – shape: (N,D) - The templates to plot, as stored in mbank.bank.cbc_bank.templates

  • variable_format (str) – How to handle the BBH variables.

  • tiling (tiling_handler) – Tiling handler that tiles the parameter space. If None, no tiling will be plotted

  • injections (ndarray) – shape: (N,D) - An extra set of injections to plot. If None, no extra points will be plotted.

  • inj_cmap (ndarray) – shape: (N,) - A colouring value for each injection, tipically the match with the bank. If None, no colouring will be done. The argument is ignored if injections = None

  • dist_ellipse (float) – The distance for the match countour ellipse to draw. If None, no contour will be drawn. Requires a tiling object.

  • fs (int) – Font size for the labels and axis

  • save_folder (str) – Folder where to save the plots If None, no plots will be saved

  • show (bool) – Whether to show the plots

  • savetag (str) – A tag to append to the name of each file, to distinguish between different call

  • title (str) – A title for all the plots

project_metric(metric, axes)[source]

Projects the metric on the given axes. It follows a discussion on stackexchange

Parameters:
  • metric (ndarray) – shape: (D,D) - A D dimensional metric

  • axes (list, int) – The D’ axes to project the metric over

Returns:

projected_metric – shape: (D’,D’) - The projected dimensional metric

Return type:

ndarray

ray_compute_injections_match(inj_dict, bank, metric_obj, mchirp_window=0.1, symphony_match=False, max_jobs=8, verbose=True)[source]

Wrapper to compute_injections_match() to allow for parallel execution. Given an injection dictionary, generated by compute_injections_metric_match() it computes the actual match (without the metric approximation) between injections and templates. It updates inj_dict with the new computed results. The injections are generic (not necessarly projected on the bank submanifold).

Parameters:
  • inj_dict (dict) – A dictionary with the data injection as computed by compute_injections_metric_match.

  • bank (mbank.bank.cbc_bank) – A bank object

  • metric_obj (cbc_metric) – A cbc_metric object to compute the match with.

  • mchirp_window (float) – Window in mchirp where the match between templates and injections is evaluated. The window is expressed in terms of \(\Delta\mathcal{M}/\mathcal{M}\), where \(\Delta\mathcal{M}\) is the distance in chirp mass between injection and each template

  • symphony_match (bool) – Whether to use the symphony match

  • max_jobs (int) – Maximum number of parallel ray jobs to be instantiated

  • verbose ('bool') – Whether to print the output

Returns:

inj_dict – The output dictionary with the updated matches

Return type:

dict

read_xml(filename, table, N=None)[source]

Read an xml file in the ligo.lw standard and extracts the BBH parameters

Parameters:
  • filename (str) – Name of the file to load

  • table (ligo.lw.lsctables.table.Table, str) – A ligo.lw table type. User typically will want to set ligo.lw.lsctables.SnglInspiralTable for a bank and ligo.lw.lsctables.SimInspiralTable for injections. A string ‘sngl_inspiral’ or ‘sim_inspiral’ can be given, instead of a ligo object, referring to ligo.lw.lsctables.SnglInspiralTable and ligo.lw.lsctables.SimInspiralTable respectively.

  • N (int) – Number of rows to be read. If None all the rows inside the table will be read

Returns:

  • BBH_components (ndarray) – shape (N,12) - An array with the read BBH components. It has the same layout as in mbank.handlers.variable_handler

  • sky_locs (ndarray) – shape (N,3) - An array with sky localization and polarization angles. Each row contains longitude \(\alpha\), latitude \(\delta\) and polarization angle \(\Psi\) (see get_antenna_patterns()). Returned only if reading a SimInspiralTable.

save_inj_stat_dict(filename, inj_stat_dict)[source]

Saves an injection statistics dictionary (see :func`compute_injections_match`) to file with json or pickle format. The dictionary can be loaded again with load_inj_stat_dict(). The format of the file is determined by the extension of the file (‘json’ or ‘pkl’).

Parameters:
  • filename (str) – Filename to save the dictionary at

  • inj_stat_dict (dict) – A dictionary with the results of an injection study. It can be generated by :func`compute_injections_match` and compute_injections_metric_match().

save_injs(filename, injs, GPS_start, GPS_end, time_step, approx, sky_locs=None, luminosity_distance=100, f_min=10.0, f_max=1024.0)[source]

Save the given injections to a ligo xml injection file (sim_inspiral table).

Parameters:
  • filename (str) – Filename to save the injections at

  • injs (ndarray) – shape (N,12) - Injection array. It must be in the same layout of mbank.handlers.get_BBH_components(): m1, m2, s1x, s1y, s1z, s2x, s2y, s2z, e, meanano iota, phi.

  • GPS_start (int) – Start GPS time for the injections

  • GPS_end (int) – End GPS time for the injections

  • time_step (float) – Time step between consecutive injections Warning: no checks are made for overlapping injections

  • approx (str) – Lal approximant to use to perform injections

  • sky_locs (ndarray) – shape (N,3) - An array with sky localization and polarization angles. Each row contains longitude \(\alpha\), latitude \(\delta\) and polarization angle \(\Psi\) (see get_antenna_patterns()). If None, they will randomly drawn uniformly over the sky.

  • luminosity_distance (float/tuple) – Luminosity distance in Mpc for the all the injections If a tuple, it has the meaning max luminosity/min luminosity

  • f_min (float) – Starting frequency (in Hz) for the injections

  • f_max (float) – End frequency (in Hz) for the injections

  • multiple_template (bool) – Whether to allow the same template to appear more than once in the injection set

split_boundaries(boundaries, grid_list, use_plawspace=True)[source]

Splits a boundary rectangle by dividing each dimension into a number of evenly spaced segments defined by each entry grid_list.

If option plawspace is set, the segments will be evenly distributed acconrding to a power law with exponent -8/3

Parameters:
  • boundaries (ndarray) – shape: (2,D) - Boundaries of the space to split. Lower limit is boundaries[0,:] while upper limits is boundaries[1,:]

  • grid_list (list) – A list of ints, each representing the number of coarse division of the space.

  • use_plawspace (bool) – Whether to use a power law spacing for the first variable

Returns:

boundaries_list – A list of the boundaries arrays obtained after the splitting, each with shape (2,D)

Return type:

list