gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
summary.py
1 # Copyright (C) 2009-2013 Kipp Cannon, Chad Hanna, Drew Keppel
2 #
3 # This program is free software; you can redistribute it and/or modify it
4 # under the terms of the GNU General Public License as published by the
5 # Free Software Foundation; either version 2 of the License, or (at your
6 # option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11 # Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 
17 ### A program to produce a variety of plots from a gstlal inspiral analysis, e.g. IFAR plots, missed found, etc.
18 
19 #
20 # =============================================================================
21 #
22 # Preamble
23 #
24 # =============================================================================
25 #
26 
27 
28 import bisect
29 import itertools
30 import math
31 import matplotlib
32 import matplotlib.figure
33 matplotlib.rcParams.update({
34  "font.size": 12.0,
35  "axes.titlesize": 12.0,
36  "axes.labelsize": 12.0,
37  "xtick.labelsize": 12.0,
38  "ytick.labelsize": 12.0,
39  "legend.fontsize": 10.0,
40  "figure.dpi": 300,
41  "savefig.dpi": 300,
42  "text.usetex": True,
43  "path.simplify": True,
44  "font.family": "serif"
45 })
46 from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
47 import numpy
48 import os
49 import scipy
50 import sys
51 
52 import lal
53 
54 from ligo import segments
55 from ligo.lw import lsctables
56 from gstlal.plots.util import golden_ratio
57 
58 
59 #
60 # =============================================================================
61 #
62 # Utilities
63 #
64 # =============================================================================
65 #
66 
67 
68 def create_plot(x_label = None, y_label = None, width = 165.0, aspect = golden_ratio):
69  #
70  # width is in mm, default aspect ratio is the golden ratio
71  #
72  fig = matplotlib.figure.Figure()
73  FigureCanvas(fig)
74  if aspect is None:
75  aspect = golden_ratio
76  fig.set_size_inches(width / 25.4, width / 25.4 / aspect)
77  axes = fig.add_axes((0.1, 0.12, .875, .80))
78  axes.grid(True)
79  if x_label is not None:
80  axes.set_xlabel(x_label)
81  if y_label is not None:
82  axes.set_ylabel(y_label)
83  return fig, axes
84 
85 
86 def marker_and_size(n):
87  if n > 2000:
88  return "ko", (10000.0 / n)**0.7
89  else:
90  return "k.", None
91 
92 
93 def sigma_region(mean, nsigma):
94  return numpy.concatenate((mean - nsigma * numpy.sqrt(mean), (mean + nsigma * numpy.sqrt(mean))[::-1]))
95 
96 
97 #
98 # =============================================================================
99 #
100 # Plotting Routines
101 #
102 # =============================================================================
103 #
104 
105 
106 def plot_injection_param_dist(x, y, x_label, y_label, waveform, aspect=None):
107  fig, axes = create_plot(x_label, y_label)
108  waveform_name = waveform.replace("_", "\_")
109  axes.set_title(fr"$\textrm{{Injection Parameter Distribution ({waveform_name} Injections)}}$")
110  mrkr, markersize = marker_and_size(len(x))
111  if markersize is not None:
112  axes.plot(x, y, mrkr, markersize=markersize)
113  else:
114  axes.plot(x, y, mrkr)
115  minx, maxx = axes.get_xlim()
116  miny, maxy = axes.get_ylim()
117  if aspect == 1:
118  axes.set_xlim((min(minx, miny), max(maxx, maxy)))
119  axes.set_ylim((min(minx, miny), max(maxx, maxy)))
120 
121  return fig
122 
123 
124 def plot_missed_found(found, missed, x_label, y_label, title, legend=True):
125  fig, axes = create_plot(x_label, y_label)
126  legend = []
127  for ifos, (x_found, y_found) in found.items():
128  legend.append("Found in %s" % ", ".join(sorted(ifos)))
129  axes.semilogy(x_found, y_found, ".")
130  if missed:
131  legend.append("Missed")
132  axes.semilogy(*missed, "k.")
133  if legend:
134  axes.legend(legend)
135  axes.set_title(title)
136 
137  return fig
138 
139 
140 def plot_param_accuracy_histogram(data, label, title):
141  fig, axes = create_plot(label, "Number")
142  start = scipy.stats.mstats.mquantiles(data, 0.01)
143  end = scipy.stats.mstats.mquantiles(data, 0.99)
144  axes.hist(data, numpy.linspace(start, end, 100))
145  axes.set_title(title)
146 
147  return fig
148 
149 
150 def plot_param_accuracy_scatter(x, y, z, x_label, y_label, z_label, title):
151  fig, axes = create_plot(x_label, y_label)
152  cb = axes.scatter(x, y, c=z, norm=matplotlib.colors.LogNorm(), vmin=1e-13, vmax=1e-3, linewidth=0.2, alpha=0.8)
153  axes.set_title(title)
154  fig.colorbar(cb, ax=axes).set_label(z_label)
155 
156  return fig
157 
158 
159 def plot_param_accuracy(x, y, x_label, y_label, title, loglog=False):
160  fig, axes = create_plot(x_label, y_label)
161  if loglog:
162  axes.loglog(x, y, "kx")
163  else:
164  axes.plot(x, y, "kx")
165  axes.set_title(title)
166 
167  return fig
168 
169 
170 def plot_snr_chi2_background(ifo, min_snr, injections, background, zerolag=None):
171  fig, axes = create_plot(r"$\rho$", r"$\chi^{2}$")
172  axes.loglog(injections[ifo].snr, injections[ifo].chi2, 'r.', label = "Inj")
173  axes.loglog(background[ifo].snr, background[ifo].chi2, "kx", label = "Background")
174  if zerolag:
175  axes.loglog(zerolag[ifo].snr, zerolag[ifo].chi2, "bx", label = "Zero-lag")
176  axes.set_title(fr"$\chi^{2}$ vs.\ $\rho$ in {ifo}")
177  else:
178  axes.set_title(fr"$\chi^{2}$ vs.\ $\rho$ in {ifo} (Closed box)")
179  axes.legend(loc = "upper left")
180  axes.set_xlim((min_snr, None))
181 
182  return fig
183 
184 
185 def plot_param_background_multiifo(ifo1, ifo2, min_snr, name, symbol, injections, background, zerolag=None):
186  fig, axes = create_plot(fr"{symbol} in {ifo1}", fr"{symbol} in {ifo2}", aspect = 1.0)
187  axes.grid(True, which = "both")
188  axes.loglog([x for x, y in injections], [y for x, y in injections], "rx", label = "Injections")
189  axes.loglog([x for x, y in background], [y for x, y in background], "kx", label = "Background")
190  if zerolag:
191  axes.loglog([x for x, y in zerolag], [y for x, y in zerolag], "bx", label = "Zero-lag")
192  axes.set_title(fr"{name} in {ifo1} vs.\ {ifo2}")
193  else:
194  axes.set_title(fr"{name} in {ifo1} vs.\ {ifo2} (Closed Box)")
195  axes.legend(loc = "lower right")
196  axes.set_xlim((min_snr, None))
197  axes.set_ylim((min_snr, None))
198 
199  return fig
200 
201 
202 def plot_mass_chi2_snr2_background(inj_mchirp, inj_chisq, inj_snr, bg_mchirp, bg_chisq, bg_snr, ifo):
203  fig, axes = create_plot(r"$M_\mathrm{chirp}$", r"$\chi^{2}/\rho^2$")
204  coll = axes.scatter(inj_mchirp, inj_chisq / inj_snr**2, c = inj_snr, label = "Injections", vmax = 20, linewidth = 0.2, alpha = 0.8)
205  fig.colorbar(coll, ax = axes).set_label("SNR in %s" % ifo)
206  axes.scatter(bg_mchirp, bg_chisq / bg_snr**2, edgecolor = 'k', c = bg_snr, marker = 'x', label = "Background")
207  axes.legend(loc = "upper left")
208  axes.semilogy()
209 
210  return fig
211 
212 
213 def plot_background_param_dist(x, y, z, x_label, y_label, z_label, title):
214  fig, axes = create_plot(x_label, y_label)
215  coll = axes.scatter(x, y, c = z, linewidth = 0.2, alpha = 0.8)
216  fig.colorbar(coll, ax = axes).set_label(z_label)
217  axes.set_title(title)
218 
219  return fig
220 
221 
222 def plot_candidate_lnL_vs_snr(min_snr, bg_snr, bg_ln_likelihood_ratio, zl_snr=None, zl_ln_likelihood_ratio=None):
223  # assume at least two instruments are required
224  fig, axes = create_plot(r"$\sqrt{\sum_{\mathrm{instruments}} \mathrm{SNR}^{2}}$", r"$\ln \mathcal{L}$")
225  axes.grid(True, which = "both")
226  axes.plot(bg_snr, bg_ln_likelihood_ratio, "kx", label = "Background")
227  if zl_snr and zl_ln_likelihood_ratio:
228  axes.plot(zl_snr, zl_ln_likelihood_ratio, "bx", label = "Zero-lag")
229  axes.set_title(r"Candidate's $\ln \mathcal{L}$ vs.\ SNR")
230  else:
231  axes.set_title(r"Candidate's $\ln \mathcal{L}$ vs.\ SNR (Closed Box)")
232  axes.set_xlim(((2. * min_snr**2.)**.5, None))
233  axes.legend(loc = "upper left")
234 
235  return fig
236 
237 
238 def plot_rate_vs_ifar(zerolag_stats, fapfar, is_open_box=False, stair_steps=False):
239  fig, axes = create_plot(r"Inverse False-Alarm Rate (s)", r"Number of Events")
240  expected_count_y = numpy.logspace(-7, numpy.log10(len(zerolag_stats)), 100)
241  expected_count_x = fapfar.livetime / expected_count_y
242  axes.loglog()
243 
244  # determine plot limits
245  xlim = (fapfar.livetime / fapfar.count_above_threshold, fapfar.livetime / 1e-4)
246  xlim = max(zerolag_stats.min(), xlim[0]), max(2.**math.ceil(math.log(zerolag_stats.max(), 2.)), xlim[1])
247  ylim = 0.001, (10.**math.ceil(math.log10(expected_count_y[::-1][bisect.bisect_right(expected_count_x[::-1], xlim[0])])) if xlim[0] is not None else None)
248 
249  # background. stair_steps option makes the background
250  # stair-step-style like the observed counts
251  if stair_steps:
252  expected_count_x = expected_count_x.repeat(2)[1:]
253  expected_count_y = expected_count_y.repeat(2)[:-1]
254  line1, = axes.plot(expected_count_x, expected_count_y, 'k--', linewidth = 1)
255 
256  # error bands
257  expected_count_x = numpy.concatenate((expected_count_x, expected_count_x[::-1]))
258  line2, = axes.fill(expected_count_x, sigma_region(expected_count_y, 3.0).clip(*ylim), alpha = 0.25, facecolor = [0.75, 0.75, 0.75])
259  line3, = axes.fill(expected_count_x, sigma_region(expected_count_y, 2.0).clip(*ylim), alpha = 0.25, facecolor = [0.5, 0.5, 0.5])
260  line4, = axes.fill(expected_count_x, sigma_region(expected_count_y, 1.0).clip(*ylim), alpha = 0.25, facecolor = [0.25, 0.25, 0.25])
261 
262  # zero-lag
263  N = numpy.arange(1., len(zerolag_stats) + 1., dtype = "double")
264  line5, = axes.plot(zerolag_stats.repeat(2)[1:], N.repeat(2)[:-1], 'k', linewidth = 2)
265 
266  # legend
267  labels = [r"Expected, $\langle N \rangle$", r"$\pm\sqrt{\langle N \rangle}$", r"$\pm 2\sqrt{\langle N \rangle}$", r"$\pm 3\sqrt{\langle N \rangle}$"]
268  if is_open_box:
269  axes.legend((line5, line1, line4, line3, line2), tuple(["Observed"] + labels), loc = "upper right")
270  else:
271  axes.legend((line5, line1, line4, line3, line2), tuple([r"Observed (time shifted)"] + labels), loc = "upper right")
272 
273  # adjust bounds of plot
274  axes.set_xlim(xlim)
275  axes.set_ylim(ylim)
276 
277  # set title
278  if is_open_box:
279  axes.set_title(r"Event Count vs.\ Inverse False-Alarm Rate Threshold")
280  else:
281  axes.set_title(r"Event Count vs.\ Inverse False-Alarm Rate Threshold (Closed Box)")
282 
283  return fig
284 
285 
286 def plot_rate_vs_lnL(zerolag_stats, fapfar, is_open_box):
287  fig, axes = create_plot(r"$\ln \mathcal{L}$ Threshold", r"Number of Events $\geq \ln \mathcal{L}$")
288  axes.semilogy()
289 
290  # plot limits and expected counts
291  def expected_count(lr):
292  return fapfar.far_from_rank(lr) * fapfar.livetime
293 
294  xlim = max(zerolag_stats.min(), fapfar.minrank), max(2. * math.ceil(zerolag_stats.max() / 2.), 30.)
295  ylim = 0.001, 10.**math.ceil(math.log10(expected_count(xlim[0])))
296 
297  # expected count curve
298  expected_count_x = numpy.linspace(xlim[0], xlim[1], 10000)
299  expected_count_y = list(map(expected_count, expected_count_x))
300  line1, = axes.plot(expected_count_x, expected_count_y, 'k--', linewidth = 1)
301 
302  # error bands
303  expected_count_x = numpy.concatenate((expected_count_x, expected_count_x[::-1]))
304  line2, = axes.fill(expected_count_x, sigma_region(expected_count_y, 3.0).clip(*ylim), alpha = 0.25, facecolor = [0.75, 0.75, 0.75])
305  line3, = axes.fill(expected_count_x, sigma_region(expected_count_y, 2.0).clip(*ylim), alpha = 0.25, facecolor = [0.5, 0.5, 0.5])
306  line4, = axes.fill(expected_count_x, sigma_region(expected_count_y, 1.0).clip(*ylim), alpha = 0.25, facecolor = [0.25, 0.25, 0.25])
307 
308  # zero-lag
309  if zerolag_stats is not None:
310  N = numpy.arange(1., len(zerolag_stats) + 1., dtype = "double")
311  line5, = axes.plot(zerolag_stats.repeat(2)[1:], N.repeat(2)[:-1], 'k', linewidth = 2)
312 
313  # legend
314  labels = [r"Noise Model, $\langle N \rangle$", r"$\pm\sqrt{\langle N \rangle}$", r"$\pm 2\sqrt{\langle N \rangle}$", r"$\pm 3\sqrt{\langle N \rangle}$"]
315  if is_open_box:
316  axes.legend((line5, line1, line4, line3, line2), tuple(["Observed"] + labels), loc = "upper right")
317  else:
318  axes.legend((line5, line1, line4, line3, line2), tuple([r"Observed (time shifted)"] + labels), loc = "upper right")
319 
320  # adjust bounds of plot
321  axes.set_xlim(xlim)
322  axes.set_ylim(ylim)
323 
324  # set title
325  if is_open_box:
326  axes.set_title(r"Event Count vs.\ Ranking Statistic Threshold")
327  else:
328  axes.set_title(r"Event Count vs.\ Ranking Statistic Threshold (Closed Box)")
329 
330  return fig
331 
332 
333 def plot_rate_vs_background_lnL(zerolag_stats, background_stats, fapfar):
334  fig, axes = create_plot(r"$\ln \mathcal{L}$ Threshold", r"Number of Events $\geq \ln \mathcal{L}$")
335  axes.semilogy()
336 
337  # plot limits and expected counts
338  def expected_count(lr):
339  return fapfar.far_from_rank(lr) * fapfar.livetime
340 
341  xlim = max(zerolag_stats.min(), fapfar.minrank), 2. * math.ceil(min(max(zerolag_stats.max(), background_stats.max()), 200.) / 2.)
342  ylim = 10.**math.floor(math.log10(expected_count(zerolag_stats.max()))), 10.**math.ceil(math.log10(expected_count(xlim[0])))
343 
344  axes.set_position((0.10, 0.12, .88, .78))
345  axes.set_title(r"Event Count vs.\ Ranking Statistic Threshold", position = (0.5, 1.05))
346 
347  # expected count curve
348  expected_count_x = numpy.linspace(xlim[0], xlim[1], 10000)
349  expected_count_y = list(map(expected_count, expected_count_x))
350  line1, = axes.plot(expected_count_x, expected_count_y, 'k--', linewidth = 1)
351 
352  # time slide
353  N = numpy.arange(1., len(background_stats) + 1., dtype = "double")
354  line5, = axes.plot(background_stats.repeat(2)[1:], N.repeat(2)[:-1], 'k', linewidth = 2)
355 
356  # zero-lag
357  N = numpy.arange(1., len(zerolag_stats) + 1., dtype = "double")
358  line6, = axes.plot(zerolag_stats.repeat(2)[1:], N.repeat(2)[:-1], 'r', linewidth = 1)
359 
360  # legend
361  axes.legend((line1, line5, line6), (r"Noise Model", r"Time-shifted Trial", r"Observed"), loc = "lower left", handlelength = 5)
362 
363  # adjust bounds of plot
364  axes.set_xlim(xlim)
365  axes.set_ylim(ylim)
366 
367  # build false-alarm probability labels
368  ax = axes.twiny()
369  ax.set_xlim(xlim)
370  ax.set_xlabel(r"$P(\geq 1 \mathrm{candidate} | \mathrm{noise})$", horizontalalignment = "left", position = (0.05, 1.02), size = "small")
371 
372  if False:
373  label_rank_alpha = [
374  (None, xlim[0], None), # left-edge of plot
375  (r"$1 \sigma$", fapfar.rank_from_fap(math.erfc(1. / math.sqrt(2.))), 0.1),
376  (r"$2 \sigma$", fapfar.rank_from_fap(math.erfc(2. / math.sqrt(2.))), 0.2),
377  (r"$3 \sigma$", fapfar.rank_from_fap(math.erfc(3. / math.sqrt(2.))), 0.3),
378  (r"$4 \sigma$", fapfar.rank_from_fap(math.erfc(4. / math.sqrt(2.))), 0.4),
379  (r"$5 \sigma$", fapfar.rank_from_fap(math.erfc(5. / math.sqrt(2.))), 0.5)
380  ]
381  else:
382  label_rank_alpha = [
383  (None, xlim[0], None), # left-edge of plot
384  (r"$10^{-1}$", fapfar.rank_from_fap(0.1), 0.1),
385  (r"$10^{-3}$", fapfar.rank_from_fap(0.001), 0.2),
386  (r"$10^{-6}$", fapfar.rank_from_fap(0.000001), 0.3)
387  ]
388 
389  for (_, lo, _), (_, hi, alpha) in zip(label_rank_alpha[:-1], label_rank_alpha[1:]):
390  if hi < lo: # can happen if xlim[0] > 1 sigma
391  continue
392  ax.axvspan(lo, hi, color = "k", alpha = alpha)
393 
394  ax.set_xticks([rank for (label, rank, _) in label_rank_alpha[1:]])
395  ax.set_xticklabels([label for (label, rank, _) in label_rank_alpha[1:]])
396 
397  return fig