gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
far.py
Go to the documentation of this file.
1 # Copyright (C) 2011--2014 Kipp Cannon, Chad Hanna, Drew Keppel
2 # Copyright (C) 2013 Jacob Peoples
3 #
4 # This program is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU General Public License as published by the
6 # Free Software Foundation; either version 2 of the License, or (at your
7 # option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
12 # Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 
18 ## @file
19 
20 ## @package plotfar
21 
22 #
23 # =============================================================================
24 #
25 # Preamble
26 #
27 # =============================================================================
28 #
29 
30 import warnings
31 import math
32 import matplotlib
33 from matplotlib import figure
34 from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
35 matplotlib.rcParams.update({
36  "font.size": 10.0,
37  "axes.titlesize": 10.0,
38  "axes.labelsize": 10.0,
39  "xtick.labelsize": 8.0,
40  "ytick.labelsize": 8.0,
41  "legend.fontsize": 8.0,
42  "figure.dpi": 300,
43  "savefig.dpi": 300,
44  "text.usetex": True
45 })
46 import numpy
47 from gstlal import far
48 from gstlal.plots import util as plotutil
49 
50 def init_plot(figsize):
51  fig = figure.Figure()
52  FigureCanvas(fig)
53  fig.set_size_inches(figsize)
54  axes = fig.gca()
55 
56  return fig, axes
57 
58 
59 def plot_snr_chi_pdf(rankingstat, instrument, which, snr_max, event_snr = None, event_chisq = None, sngls = None):
60  # also checks that which is an allowed value
61  tag = {
62  "background_pdf": "Noise",
63  "injection_pdf": "Signal",
64  "zero_lag_pdf": "Candidates",
65  "LR": "LR"
66  }[which]
67 
68  # sngls is a sequence of {instrument: (snr, chisq)} dictionaries,
69  # obtain the co-ordinates for a sngls scatter plot for this
70  # instrument from that. need to handle case in which there are no
71  # singles for this instrument
72  if sngls is not None:
73  sngls = numpy.array([sngl[instrument] for sngl in sngls if instrument in sngl])
74  if not len(sngls):
75  sngls = None
76 
77  if which == "background_pdf":
78  # a ln PDF object
79  binnedarray = rankingstat.denominator.densities["%s_snr_chi" % instrument]
80  elif which == "injection_pdf":
81  # a ln PDF object. numerator has only one, same for all
82  # instruments
83  binnedarray = rankingstat.numerator.densities["snr_chi"]
84  elif which == "zero_lag_pdf":
85  # a ln PDF object
86  binnedarray = rankingstat.zerolag.densities["%s_snr_chi" % instrument]
87  elif which == "LR":
88  num = rankingstat.numerator.densities["snr_chi"]
89  den = rankingstat.denominator.densities["%s_snr_chi" % instrument]
90  assert num.bins == den.bins
91  binnedarray = num.count.copy()
92  with numpy.errstate(invalid = "ignore"):
93  binnedarray.array[:,:] = num.at_centres() - den.at_centres()
94  binnedarray.array[num.count.array == 0] = float("-inf")
95  else:
96  raise ValueError("invalid which (%s)" % which)
97 
98  # the last bin can have a centre at infinity, and its value is
99  # always 0 anyway so there's no point in trying to include it
100  x = binnedarray.bins[0].centres()[:-1]
101  y = binnedarray.bins[1].centres()[:-1]
102  z = binnedarray.at_centres()[:-1,:-1]
103  if numpy.isnan(z).any():
104  if numpy.isnan(z).all():
105  warnings.warn("%s %s is all NaN, skipping" % (instrument, which))
106  return None
107  warnings.warn("%s %s contains NaNs" % (instrument, which))
108  z = numpy.ma.masked_where(numpy.isnan(z), z)
109 
110  # the range of the plots
111  xlo, xhi = rankingstat.snr_min, snr_max
112  ylo, yhi = .0001, 1.
113 
114  x = x[binnedarray.bins[xlo:xhi, ylo:yhi][0]]
115  y = y[binnedarray.bins[xlo:xhi, ylo:yhi][1]]
116  z = z[binnedarray.bins[xlo:xhi, ylo:yhi]]
117 
118  fig, axes = init_plot((8., 8. / plotutil.golden_ratio))
119  if which == "LR":
120  norm = matplotlib.colors.Normalize(vmin = -80., vmax = +200.)
121  levels = numpy.linspace(-80., +200, 141)
122  elif which == "background_pdf":
123  norm = matplotlib.colors.Normalize(vmin = -30., vmax = z.max())
124  levels = 50
125  elif which == "injection_pdf":
126  norm = matplotlib.colors.Normalize(vmin = -60., vmax = z.max())
127  levels = 50
128  elif which == "zero_lag_pdf":
129  norm = matplotlib.colors.Normalize(vmin = -30., vmax = z.max())
130  levels = 50
131  else:
132  raise ValueError("invalid which (%s)" % which)
133 
134  mesh = axes.pcolormesh(x, y, z.T, norm = norm, cmap = "afmhot", shading = "gouraud")
135  if which == "LR":
136  cs = axes.contour(x, y, z.T, levels, norm = norm, colors = "k", linewidths = .5, alpha = .3)
137  axes.clabel(cs, [-20., -10., 0., +10., +20.], fmt = "%g", fontsize = 8)
138  else:
139  axes.contour(x, y, z.T, levels, norm = norm, colors = "k", linestyles = "-", linewidths = .5, alpha = .3)
140  if event_snr is not None and event_chisq is not None:
141  axes.plot(event_snr, event_chisq / event_snr / event_snr, "ko", mfc = "None", mec = "g", ms = 14, mew=4)
142  if sngls is not None:
143  axes.plot(sngls[:,0], sngls[:,1] / sngls[:,0]**2., "b.", alpha = .2)
144  axes.loglog()
145  axes.grid(which = "both")
146  #axes.set_xlim((xlo, xhi))
147  #axes.set_ylim((ylo, yhi))
148  fig.colorbar(mesh, ax = axes)
149  axes.set_xlabel(r"$\mathrm{SNR}$")
150  axes.set_ylabel(r"$\chi^{2} / \mathrm{SNR}^{2}$")
151  if tag.lower() in ("signal",):
152  axes.set_title(r"$\ln P(\chi^{2} / \mathrm{SNR}^{2} | \mathrm{SNR}, \mathrm{%s})$ in %s" % (tag.lower(), instrument))
153  elif tag.lower() in ("noise", "candidates"):
154  axes.set_title(r"$\ln P(\mathrm{SNR}, \chi^{2} / \mathrm{SNR}^{2} | \mathrm{%s})$ in %s" % (tag.lower(), instrument))
155  elif tag.lower() in ("lr",):
156  axes.set_title(r"$\ln P(\chi^{2} / \mathrm{SNR}^{2} | \mathrm{SNR}, \mathrm{signal} ) / P(\mathrm{SNR}, \chi^{2} / \mathrm{SNR}^{2} | \mathrm{noise})$ in %s" % instrument)
157  else:
158  raise ValueError(tag)
159  try:
160  fig.tight_layout(pad = .8)
161  except RuntimeError:
162  if tag.lower() in ("signal",):
163  axes.set_title("ln P(chi^2 / SNR^2 | SNR, %s) in %s" % (tag.lower(), instrument))
164  elif tag.lower() in ("noise", "candidates"):
165  axes.set_title("ln P(SNR, chi^2 / SNR^2 | %s) in %s" % (tag.lower(), instrument))
166  elif tag.lower() in ("lr",):
167  axes.set_title("ln P(chi^2 / SNR^2 | SNR, signal) / P(SNR, chi^2 / SNR^2 | noise) in %s" % instrument)
168  fig.tight_layout(pad = .8)
169  return fig
170 
171 
172 def plot_rates(rankingstat):
173  fig = figure.Figure()
174  FigureCanvas(fig)
175  fig.set_size_inches((6., 6.))
176  axes0 = fig.add_subplot(2, 2, 1)
177  axes1 = fig.add_subplot(2, 2, 2)
178  axes2 = fig.add_subplot(2, 2, 3)
179  axes3 = fig.add_subplot(2, 2, 4)
180 
181  # singles counts
182  labels = []
183  sizes = []
184  colours = []
185  for instrument, count in sorted(rankingstat.denominator.triggerrates.counts.items()):
186  labels.append("%s\n(%d)" % (instrument, count))
187  sizes.append(count)
188  colours.append(plotutil.colour_from_instruments((instrument,)))
189  axes0.pie(sizes, labels = labels, colors = colours, autopct = "%.3g%%", pctdistance = 0.4, labeldistance = 0.8)
190  axes0.set_title("Trigger Counts")
191 
192  # singles rates
193  labels = []
194  sizes = []
195  colours = []
196  for instrument, rate in sorted(rankingstat.denominator.triggerrates.densities.items()):
197  labels.append("%s\n(%g Hz)" % (instrument, rate))
198  sizes.append(rate)
199  colours.append(plotutil.colour_from_instruments((instrument,)))
200  axes1.pie(sizes, labels = labels, colors = colours, autopct = "%.3g%%", pctdistance = 0.4, labeldistance = 0.8)
201  axes1.set_title(r"Mean Trigger Rates (per live-time)")
202 
203  # live time
204  labels = []
205  sizes = []
206  colours = []
207  seglists = rankingstat.denominator.triggerrates.segmentlistdict()
208  for instruments in sorted(rankingstat.denominator.coinc_rates.all_instrument_combos, key = lambda instruments: sorted(instruments)):
209  livetime = float(abs(seglists.intersection(instruments) - seglists.union(frozenset(seglists) - instruments)))
210  labels.append("%s\n(%g s)" % (", ".join(sorted(instruments)), livetime))
211  sizes.append(livetime)
212  colours.append(plotutil.colour_from_instruments(instruments))
213  axes2.pie(sizes, labels = labels, colors = colours, autopct = "%.3g%%", pctdistance = 0.4, labeldistance = 0.8)
214  axes2.set_title("Live-time")
215 
216  # projected background counts
217  labels = []
218  sizes = []
219  colours = []
220  # FIXME: make sure this sort works
221  for instruments, count in sorted(rankingstat.denominator.candidate_count_model().items(), key = lambda instruments : sorted(instruments[0])):
222  labels.append("%s\n(%d)" % (", ".join(sorted(instruments)), count))
223  sizes.append(count)
224  colours.append(plotutil.colour_from_instruments(instruments))
225  axes3.pie(sizes, labels = labels, colors = colours, autopct = "%.3g%%", pctdistance = 0.4, labeldistance = 0.8)
226  axes3.set_title("Expected Background Candidate Counts\n(before $\ln \mathcal{L}$ cut)")
227 
228  fig.tight_layout(pad = .8)
229  return fig
230 
231 
232 def plot_snr_joint_pdf(snrpdf, instruments, horizon_distances, min_instruments, max_snr, sngls = None):
233  if len(instruments) < 1:
234  raise ValueError("len(instruments) must be >= 1")
235 
236  # retrieve the PDF in binned array form (not the interpolator)
237  binnedarray = snrpdf.get_snr_joint_pdf_binnedarray(instruments, horizon_distances, min_instruments)
238 
239  # the range of the axes
240  xlo, xhi = far.RankingStat.snr_min, max_snr
241  mask = binnedarray.bins[(slice(xlo, xhi),) * len(instruments)]
242 
243  # axes are in alphabetical order
244  instruments = sorted(instruments)
245 
246  # sngls is a sequence of {instrument: (snr, chisq)} dictionaries,
247  # digest into co-ordinate tuples for a sngls scatter plot
248  if sngls is not None:
249  # NOTE: the PDFs are computed subject to the constraint
250  # that the candidate is observed in precisely that set of
251  # instruments, so we need to restrict ourselves, here, to
252  # coincs that involve the combination of instruments in
253  # question otherwise we'll be overlaying a scatter plot
254  # that we don't believe to have been drawn from the PDF
255  # we're showing.
256  sngls = numpy.array([tuple(sngl[instrument][0] for instrument in instruments) for sngl in sngls if sorted(sngl) == instruments])
257 
258  x = [binning.centres() for binning in binnedarray.bins]
259  z = binnedarray.array
260  if numpy.isnan(z).any():
261  warnings.warn("%s SNR PDF for %s contains NaNs" % (", ".join(instruments), ", ".join("%s=%g" % instdist for instdist in sorted(horizon_distances.items()))))
262  z = numpy.ma.masked_where(numpy.isnan(z), z)
263 
264  x = [coords[m] for coords, m in zip(x, mask)]
265  z = z[mask]
266 
267  # one last check for craziness to make error messages more
268  # meaningful
269  assert not numpy.isnan(z).any()
270  assert not (z < 0.).any()
271 
272  # plot the natural logarithm of the PDF
273  with numpy.errstate(divide = "ignore"):
274  z = numpy.log(z)
275 
276  if len(instruments) == 1:
277  # 1D case
278  fig, axes = init_plot((5., 5. / plotutil.golden_ratio))
279 
280  # FIXME: hack to allow all-0 PDFs to be plotted. remove
281  # when we have a version of matplotlib that doesn't crash,
282  # whatever version of matplotlib that is
283  if numpy.isinf(z).all():
284  z[:] = -60.
285  z[0] = -55.
286 
287  axes.semilogx(x[0], z, color = "k")
288  ylo, yhi = -40., max(0., z.max())
289  if sngls is not None and len(sngls) == 1:
290  axes.axvline(sngls[0, 0])
291  axes.set_xlim((xlo, xhi))
292  axes.set_ylim((ylo, yhi))
293  axes.grid(which = "both", linestyle = "-", linewidth = 0.2)
294  axes.set_xlabel(r"$\mathrm{SNR}_{\mathrm{%s}}$" % instruments[0])
295  axes.set_ylabel(r"$\ln P(\mathrm{SNR}_{\mathrm{%s}})$" % instruments[0])
296 
297  elif len(instruments) == 2:
298  # 2D case
299  fig, axes = init_plot((5., 4.))
300 
301  # FIXME: hack to allow all-0 PDFs to be plotted. remove
302  # when we have a version of matplotlib that doesn't crash,
303  # whatever version of matplotlib that is
304  if numpy.isinf(z).all():
305  z[:,:] = -60.
306  z[0,0] = -55.
307 
308  norm = matplotlib.colors.Normalize(vmin = -40., vmax = max(0., z.max()))
309 
310  mesh = axes.pcolormesh(x[0], x[1], z.T, norm = norm, cmap = "afmhot", shading = "gouraud")
311  axes.contour(x[0], x[1], z.T, 50, norm = norm, colors = "k", linestyles = "-", linewidths = .5, alpha = .3)
312 
313  if sngls is not None and len(sngls) == 1:
314  axes.plot(sngls[0, 0], sngls[0, 1], "ko", mfc = "None", mec = "g", ms = 14, mew=4)
315  elif sngls is not None:
316  axes.plot(sngls[:,0], sngls[:,1], "b.", alpha = .2)
317 
318  axes.loglog()
319  axes.grid(which = "both", linestyle = "-", linewidth = 0.2)
320  fig.colorbar(mesh, ax = axes)
321  # co-ordinates are in alphabetical order
322  axes.set_xlabel(r"$\mathrm{SNR}_{\mathrm{%s}}$" % instruments[0])
323  axes.set_ylabel(r"$\mathrm{SNR}_{\mathrm{%s}}$" % instruments[1])
324 
325  else:
326  # FIXME: figure out how to plot 3+D PDFs
327  return None
328 
329  axes.set_title(r"$\ln P(%s | \{%s\}, \mathrm{signal})$" % (", ".join("\mathrm{SNR}_{\mathrm{%s}}" % instrument for instrument in instruments), ", ".join("{D_{\mathrm{H}}}_{\mathrm{%s}}=%.3g" % item for item in sorted(horizon_distances.items()))))
330  fig.tight_layout(pad = .8)
331  return fig
332 
333 
334 def plot_likelihood_ratio_pdf(rankingstatpdf, xlohi, title, which = "noise"):
335 
336  xlo, xhi = xlohi
337  fig, axes = init_plot((8., 8. / plotutil.golden_ratio))
338 
339  if rankingstatpdf.zero_lag_lr_lnpdf.array.any():
340  extincted = rankingstatpdf.new_with_extinction()
341  else:
342  extincted = None
343 
344  if which == "noise":
345  lnpdf = rankingstatpdf.noise_lr_lnpdf
346  extinctedlnpdf = extincted.noise_lr_lnpdf if extincted is not None else None
347  zerolag_lnpdf = rankingstatpdf.zero_lag_lr_lnpdf
348  elif which == "signal":
349  lnpdf = rankingstatpdf.signal_lr_lnpdf
350  extinctedlnpdf = extincted.signal_lr_lnpdf if extincted is not None else None
351  zerolag_lnpdf = None
352  else:
353  raise ValueError("invalid which (%s)" % which)
354 
355  axes.semilogy(lnpdf.bins[0].centres(), numpy.exp(lnpdf.at_centres()), color = "r", label = "%s model without extinction" % title)
356  if extincted is not None:
357  axes.semilogy(extinctedlnpdf.bins[0].centres(), numpy.exp(extinctedlnpdf.at_centres()), color = "k", label = "%s model with extinction" % title)
358  if zerolag_lnpdf is not None:
359  axes.semilogy(zerolag_lnpdf.bins[0].centres(), numpy.exp(zerolag_lnpdf.at_centres()), color = "k", linestyle = "--", label = "Observed candidate density")
360 
361  axes.grid(which = "major", linestyle = "-", linewidth = 0.2)
362  axes.set_title(r"Ranking Statistic Distribution Density Model for %s" % title)
363  axes.set_xlabel(r"$\ln \mathcal{L}$")
364  axes.set_ylabel(r"$P(\ln \mathcal{L} | \mathrm{%s})$" % which)
365  yhi = math.exp(lnpdf[xlo:xhi,].max())
366  ylo = math.exp(lnpdf[xlo:xhi,].min())
367  if zerolag_lnpdf is not None:
368  yhi = max(yhi, math.exp(zerolag_lnpdf[xlo:xhi,].max()))
369  ylo = max(yhi * 1e-40, ylo)
370  axes.set_ylim((10**math.floor(math.log10(ylo) - .5), 10**math.ceil(math.log10(yhi) + .5)))
371  axes.set_xlim((xlo, xhi))
372  axes.legend(loc = "lower left", handlelength = 3)
373  fig.tight_layout(pad = .8)
374  return fig
375 
376 
377 def plot_likelihood_ratio_ccdf(fapfar, xlohi, observed_ln_likelihood_ratios = None, is_open_box = False, ln_likelihood_ratio_markers = None):
378 
379  xlo, xhi = xlohi
380  assert xlo < xhi
381 
382  fig, axes = init_plot((8., 8. / plotutil.golden_ratio))
383 
384  x = numpy.linspace(xlo, xhi, int(math.ceil(xhi - xlo)) * 8)
385  axes.semilogy(x, fapfar.fap_from_rank(x), color = "k")
386 
387  ylo = fapfar.fap_from_rank(xhi)
388  ylo = 10**math.floor(math.log10(ylo))
389  yhi = 10.
390 
391  if observed_ln_likelihood_ratios is not None:
392  observed_ln_likelihood_ratios = numpy.array(observed_ln_likelihood_ratios)
393  x = observed_ln_likelihood_ratios[:,0]
394  y = observed_ln_likelihood_ratios[:,1]
395  axes.semilogy(x, y, color = "k", linestyle = "", marker = "+", label = r"Candidates" if is_open_box else r"Candidates (time shifted)")
396  axes.legend(loc = "upper right")
397 
398  if ln_likelihood_ratio_markers is not None:
399  for ln_likelihood_ratio in ln_likelihood_ratio_markers:
400  axes.axvline(ln_likelihood_ratio)
401 
402  axes.set_xlim((xlo, xhi))
403  axes.set_ylim((ylo, yhi))
404  axes.grid(which = "major", linestyle = "-", linewidth = 0.2)
405  axes.set_title(r"False Alarm Probability vs.\ Log Likelihood Ratio")
406  axes.set_xlabel(r"$\ln \mathcal{L}$")
407  axes.set_ylabel(r"$P(\mathrm{one\ or\ more\ candidates} \geq \ln \mathcal{L} | \mathrm{noise})$")
408  fig.tight_layout(pad = .8)
409  return fig
410 
411 
412 def plot_horizon_distance_vs_time(rankingstat, tlohi, masses = (1.4, 1.4), tref = None):
413  tlo, thi = tlohi
414  fig, axes = init_plot((8., 8. / plotutil.golden_ratio))
415  axes.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(1800.))
416  axes.yaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(5.))
417  axes.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(50.))
418 
419  yhi = 1.
420  for instrument, history in rankingstat.numerator.horizon_history.items():
421  x = numpy.array([t for t in history.keys() if tlo <= t < thi])
422  y = list(map(history.__getitem__, x))
423  if tref is not None:
424  x -= float(tref)
425  axes.plot(x, y, color = plotutil.colour_from_instruments([instrument]), label = "%s" % instrument)
426  try:
427  yhi = max(max(y), yhi)
428  except ValueError:
429  pass
430  if tref is not None:
431  axes.set_xlabel("Time From GPS %.2f (s)" % float(tref))
432  else:
433  axes.set_xlim((math.floor(tlo), math.ceil(thi)))
434  axes.set_xlabel("GPS Time (s)")
435  axes.set_ylim((0., math.ceil(yhi / 10.) * 10.))
436  axes.set_ylabel("Horizon Distance (Mpc)")
437  axes.set_title(r"Horizon Distance for $%.3g\,\mathrm{M}_{\odot}$--$%.3g\,\mathrm{M}_{\odot}$ vs.\ Time" % masses)
438  axes.grid(which = "major", linestyle = "-", linewidth = 0.2)
439  axes.legend(loc = "lower left")
440  fig.tight_layout(pad = .8)
441  return fig