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.SimInspiralTablewith implemented defaults. Implemented as in sbank.waveformConstruct 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.SnglInspiralTablewith implemented defaults. Implemented as in sbank.waveformConstruct 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.
- clip_eigenvalues(metric, min_eig=0.05)[source]
Given a metric, it sets to
min_eigthe eigenvalues of the metric which are lower thanmin_eig.
- 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 thematchandid_matchentries ofinj_dictwith 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 objectmetric_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:
- compute_injections_metric_match(inj_dict, bank, tiling, verbose=True)[source]
Computes the match of the injections in
inj_dictwith 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_matchandid_metric_matchof 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_bankobjecttiling (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:
- 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:
- Returns:
- 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_handlerfor more informationM_range (tuple) – Ranges for each physical quantity. They will be used whenever required by the
variable_formatIfmchirpetamass format is set,M_rangeandq_rangeare interpreted as mchirp and eta respectively. IflogMqmass format is set,M_rangeis 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_formatIfmchirpetamass format is set,M_rangeandq_rangeare interpreted as mchirp and eta respectively. IflogMqmass format is set,M_rangeis 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_formatIfmchirpetamass format is set,M_rangeandq_rangeare interpreted as mchirp and eta respectively. IflogMqmass format is set,M_rangeis 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_formatIfmchirpetamass format is set,M_rangeandq_rangeare interpreted as mchirp and eta respectively. IflogMqmass format is set,M_rangeis 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_formatIfmchirpetamass format is set,M_rangeandq_rangeare interpreted as mchirp and eta respectively. IflogMqmass format is set,M_rangeis 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_formatIfmchirpetamass format is set,M_rangeandq_rangeare interpreted as mchirp and eta respectively. IflogMqmass format is set,M_rangeis 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_formatIfmchirpetamass format is set,M_rangeandq_rangeare interpreted as mchirp and eta respectively. IflogMqmass format is set,M_rangeis 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_formatIfmchirpetamass format is set,M_rangeandq_rangeare interpreted as mchirp and eta respectively. IflogMqmass format is set,M_rangeis 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_formatIfmchirpetamass format is set,M_rangeandq_rangeare interpreted as mchirp and eta respectively. IflogMqmass format is set,M_rangeis 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_formatIfmchirpetamass format is set,M_rangeandq_rangeare interpreted as mchirp and eta respectively. IflogMqmass format is set,M_rangeis 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_formatIfmchirpetamass format is set,M_rangeandq_rangeare interpreted as mchirp and eta respectively. IflogMqmass format is set,M_rangeis still interpreted as the mass and not the log mass.
- Returns:
boundaries – shape (2,D) - An array with the boundaries.
- Return type:
- 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.
- 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:
- Returns:
metric_projected – shape: (D,D) - The D dimensional metric projected along the large eigenvalues
- Return type:
- 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.
- 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:
- Returns:
- 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/orcompute_injections_match()which fill the relevant entries, with the results of fitting factors calculations.An injection stat dictionary is dictionary with entries:
theta_inj: the parameters of the injectionsid_tile: index of the tile the injections belongs to in a given tiling (filled bycompute_injections_metric_match())mchirp_window: the window in relative chirp mass inside which the templates are considered for full matchmatch: match of the closest template (filled bycompute_injections_match())id_match: index of the closest template (filled bycompute_injections_match())metric_match: metric match of the closest template (filled bycompute_injections_metric_match())id_metric_match: metric index of the closest template (filled bycompute_injections_metric_match())sky_loc: the sky location for each injection
- Parameters:
injs (
ndarray) – shape: (N,12) - A set of injections. They must be in the full format of thembank.metric.cbc_metric.get_BBH_components(). Each row keeps the following entries: m1, m2, s1x, s1y, s1z, s2x, s2y, s2z, e, meanano, iota, phisky_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: seeget_random_sky_loc()andget_antenna_patterns()for more information. IfNone, only the plus polarization will be used for injection recovery: this can only happens if the standard match is used (symphony = Falseincompute_injections_match()).
- Returns:
inj_dict – An injection stat dictionary
- Return type:
- 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:
- 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:
- 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:
- 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.
- 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 formatvalues (
ndarray) – shape: (N,D) - Datapoints to plot. They must be compatible with the chosen variable formatvariable_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 inmbank.bank.cbc_bank.templatesvariable_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 = Nonedist_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
- 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 bycompute_injections_metric_match()it computes the actual match (without the metric approximation) between injections and templates. It updatesinj_dictwith 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 objectmetric_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:
- 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_handlersky_locs (
ndarray) – shape (N,3) - An array with sky localization and polarization angles. Each row contains longitude \(\alpha\), latitude \(\delta\) and polarization angle \(\Psi\) (seeget_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 ofmbank.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\) (seeget_antenna_patterns()). IfNone, 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
plawspaceis 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 isboundaries[0,:]while upper limits isboundaries[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: