gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
sensitivity.py
1 # Copyright (C) 2015 Chad Hanna, Cody Messick
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 import datetime
18 from itertools import chain
19 import math
20 
21 import matplotlib
22 matplotlib.use('Agg')
23 matplotlib.rcParams.update({
24  "font.size": 10.0,
25  "axes.titlesize": 10.0,
26  "axes.labelsize": 10.0,
27  "xtick.labelsize": 8.0,
28  "ytick.labelsize": 8.0,
29  "legend.fontsize": 8.0,
30  "figure.dpi": 200,
31  "savefig.dpi": 200,
32  "text.usetex": True
33 })
34 from matplotlib import pyplot as plt
35 from matplotlib import ticker as tkr
36 import numpy
37 
38 from lal import iterutils
39 from lal import GPSToUTC
40 from lal import rate
41 from ligo.lw import utils as ligolw_utils
42 
43 from gstlal import imr_utils
44 from gstlal.plots import segments as plotsegments
45 from gstlal.plots import util as plotutil
46 
47 
48 def bin_type_to_label(bin_type, mlo, mmid, mhi):
49  if bin_type == "Aligned_Spin":
50  label = "$\chi \in [%.2f, %.2f]$" % (mlo[0], mhi[0])
51  if bin_type == "Mass_Ratio":
52  label = "$m_1/m_2 \in [%.2f, %.2f]$" % (mlo[0], mhi[0])
53  if bin_type == "Total_Mass":
54  label = "$M_\mathrm{total} \in [%.2f, %.2f] \,\mathrm{M}_\odot$" % (mlo[0], mhi[0])
55  if bin_type == "Chirp_Mass" or bin_type == "Source_Type":
56  label = "$M_\mathrm{chirp} \in [%.2f, %.2f] \,\mathrm{M}_\odot$" % (mlo[0], mhi[0])
57  if bin_type == "Mass1_Mass2":
58  if mmid[0] > mmid[1]: # symmetrized sims have m1 < m2
59  return
60  label = "$m_1 \in [%.2f, %.2f], m_2 \in [%.2f, %.2f] \,\mathrm{M}_\odot$" % (mlo[0], mhi[0], mlo[1], mhi[1])
61  if bin_type == "Duration":
62  if mlo[0] == 0:
63  label = "$t_\mathrm{template} \leq %.2f \,\mathrm{s}$" % mhi[0]
64  elif numpy.isinf(mhi[0]):
65  label = "$t_\mathrm{template} > %.2f \,\mathrm{s}$" % mlo[0]
66  else:
67  label = "$%.2f \,\mathrm{s} < t_\mathrm{template} \leq %.2f \,\mathrm{s}$" % (mlo[0], mhi[0])
68  return label
69 
70 def volumes_bins_to_range_label(volumes, bins, bin_type):
71  for bin_lo, bin_mid, bin_hi in zip(
72  iterutils.MultiIter(*bins.lower()),
73  iterutils.MultiIter(*bins.centres()),
74  iterutils.MultiIter(*bins.upper())
75  ):
76  center = numpy.array([v[bin_mid] for v in volumes[1]])
77  if (center == 0).all():
78  continue
79  lo = numpy.array([v[bin_mid] for v in volumes[0]])
80  hi = numpy.array([v[bin_mid] for v in volumes[2]])
81 
82  yield lo, center, hi, bin_type_to_label(bin_type, bin_lo, bin_mid, bin_hi)
83 
84 def fiducial_efficiency_to_range_label(eff_fid, bins, zero_bin, bin_type):
85  for bin_lo, bin_mid, bin_hi in zip(
86  iterutils.MultiIter(*bins.lower()),
87  iterutils.MultiIter(*bins.centres()),
88  iterutils.MultiIter(*bins.upper())
89  ):
90  ds = (zero_bin.lower() + zero_bin.upper()) / 2
91  center = numpy.array([eff_fid[1][(d,) + bin_mid] for d in ds])
92  lo = numpy.array([eff_fid[0][(d,) + bin_mid] for d in ds])
93  hi = numpy.array([eff_fid[2][(d,) + bin_mid] for d in ds])
94 
95  yield lo, center, hi, ds, bin_type_to_label(bin_type, bin_lo, bin_mid, bin_hi)
96 
97 def vt_to_range(volume, livetime):
98  return (volume / (4 * math.pi * livetime / 3))**(1./3)
99 
100 def plot_sensitivity_vs_far(volumes, fars, livetime, ifos, bins, bin_type):
101  fig = plt.figure()
102  fig.set_size_inches((8., 8. / plotutil.golden_ratio))
103  ax_far = fig.gca()
104 
105  # plot the volume/range versus far/snr for each bin
106  mbins = rate.NDBins(bins[1:])
107  labels = []
108  for lo, center, hi, label in volumes_bins_to_range_label(volumes, mbins, bin_type):
109  labels.append(label)
110 
111  # NOTE create regular plots, and define log x,y scales below
112  # since otherwise, fill_between allocates too many blocks and crashes
113  line, = ax_far.plot(fars, center, label=label, linewidth=2)
114  ax_far.fill_between(fars, lo, hi, alpha=0.5, color=line.get_color())
115 
116  ax_far.set_xlabel("Combined FAR (Hz)")
117  ax_far.set_ylabel(r"Volume $\times$ Time ($\mathrm{Mpc}^3 \mathrm{yr}$)")
118  ax_far.set_xscale("log")
119  ax_far.set_yscale("log")
120  ax_far.set_xlim([min(fars), max(fars)])
121  ax_far.invert_xaxis()
122  ax_far.legend(loc="lower left")
123  ax_far.grid()
124 
125  vol_tix = ax_far.get_yticks()
126  tx = ax_far.twinx() # map volume to distance
127  tx.set_yticks(vol_tix)
128  tx.set_yscale("log")
129  tx.set_ylim(ax_far.get_ylim())
130  tx.set_yticklabels(["%.3g" % (vt_to_range(float(k), livetime[ifos])) for k in vol_tix])
131  tx.set_ylabel("Range (Mpc)")
132 
133  ax_far.set_title("%s Observing (%.2f days)" % ("".join(sorted(list(ifos))), livetime[ifos]*365.25))
134  fig.tight_layout(pad = .8)
135 
136  return fig
137 
138 def plot_range_vs_far(volumes, fars, livetime, ifos, bins, bin_type):
139  fig = plt.figure()
140  fig.set_size_inches((8., 8. / plotutil.golden_ratio))
141  ax_far_range = fig.gca()
142 
143  # plot the volume/range versus far/snr for each bin
144  mbins = rate.NDBins(bins[1:])
145  labels = []
146  for lo, center, hi, label in volumes_bins_to_range_label(volumes, mbins, bin_type):
147  labels.append(label)
148 
149  # NOTE create regular plots, and define log x,y scales below
150  # since otherwise, fill_between allocates too many blocks and crashes
151  center = vt_to_range(center, livetime[ifos])
152  lo = vt_to_range(lo, livetime[ifos])
153  hi = vt_to_range(hi, livetime[ifos])
154  line, = ax_far_range.plot(fars, center, label=label, linewidth=2)
155  ax_far_range.fill_between(fars, lo, hi, alpha=0.5, color=line.get_color())
156 
157  ax_far_range.set_xlabel("Combined FAR (Hz)")
158  ax_far_range.set_ylabel("Range (Mpc)")
159  ax_far_range.set_xscale("log")
160  ax_far_range.set_xlim([min(fars), max(fars)])
161  ax_far_range.invert_xaxis()
162  ax_far_range.legend(loc="lower left")
163  ax_far_range.grid()
164 
165  ax_far_range.set_title("%s Observing (%.2f days)" % ("".join(sorted(list(ifos))), livetime[ifos]*365.25))
166  fig.tight_layout(pad = .8)
167 
168  return fig
169 
170 def plot_sensitivity_vs_snr(volumes, snrs, livetime, ifos, bins, bin_type):
171  fig = plt.figure()
172  fig.set_size_inches((8., 8. / plotutil.golden_ratio))
173  ax_snr = fig.gca()
174 
175  # plot the volume/range versus far/snr for each bin
176  mbins = rate.NDBins(bins[1:])
177  labels = []
178  for lo, center, hi, label in volumes_bins_to_range_label(volumes, mbins, bin_type):
179  labels.append(label)
180 
181  # NOTE create regular plots, and define log x,y scales below
182  # since otherwise, fill_between allocates too many blocks and crashes
183  line, = ax_snr.plot( snrs, center, label=label, linewidth=2 )
184  ax_snr.fill_between( snrs, lo, hi, alpha=0.5, color=line.get_color())
185 
186  ax_snr.set_xlabel("Network SNR")
187  ax_snr.set_ylabel(r"Volume $\times$ Time ($\mathrm{Mpc}^3 \mathrm{yr}$)")
188  ax_snr.set_yscale("log")
189  ax_snr.set_xlim([min(snrs), max(snrs)])
190  ax_snr.set_ylim(ymin=0)
191  ax_snr.legend(loc="lower left")
192  ax_snr.grid()
193 
194  vol_tix = ax_snr.get_yticks()
195  tx = ax_snr.twinx() # map volume to distance
196  tx.set_yticks(vol_tix)
197  tx.set_yscale("log")
198  tx.set_ylim(ax_snr.get_ylim())
199  tx.set_yticklabels(["%.3g" % (vt_to_range(float(k), livetime[ifos])) for k in vol_tix])
200  tx.set_ylabel("Range (Mpc)")
201 
202  ax_snr.set_title("%s Observing (%.2f days)" % ("".join(sorted(list(ifos))), livetime[ifos]*365.25))
203  fig.tight_layout(pad = .8)
204 
205  return fig
206 
207 def plot_fiducial_efficiency(eff_fids, fiducial_far, ifos, bins, bin_type):
208  fig = plt.figure()
209  fig.set_size_inches((8., 8. / plotutil.golden_ratio))
210  ax_eff = fig.gca()
211 
212  # plot the volume/range versus far/snr for each bin
213  mbins = rate.NDBins(bins[1:])
214  labels = []
215  for lo, eff, hi, ds, label in fiducial_efficiency_to_range_label(eff_fids, mbins, bins[0], bin_type):
216  labels.append(label)
217 
218  # NOTE create regular plots, and define log x,y scales below
219  # since otherwise, fill_between allocates too many blocks and crashes
220  line, = ax_eff.plot(ds, eff, label=label, linewidth=2)
221  ax_eff.fill_between(ds, lo, hi, alpha=0.5, color=line.get_color())
222 
223  ax_eff.set_xlabel("Distance (Mpc)")
224  ax_eff.set_ylabel("Efficiency")
225  ax_eff.set_xscale("log")
226  ax_eff.legend(loc="upper right")
227  ax_eff.grid()
228 
229  ax_eff.set_title("%s Observing ($\mathrm{FAR} < %s\,\mathrm{Hz}$)" % ("".join(sorted(list(ifos))), plotutil.latexnumber("%.2e" % fiducial_far)))
230  fig.tight_layout(pad = .8)
231 
232  return fig
233 
234 # FIXME Currently this program assumes there are only two ifos
235 def parse_sensitivity_docs(database, cumulative_segments_file, simdb_query_end_time):
236  # Get segments and coincident segment bins
237  seglistdicts = plotsegments.parse_segments_xml(cumulative_segments_file)
238  # FIXME This will need to be generalized to more than two IFOs
239  seg_bins = [ligotimegps.seconds for ligotimegps in sorted(list(chain.from_iterable(seglistdicts["joint segments"]["H1L1"])))]
240  # Adjust the last segment bin so that we dont get a situation where we
241  # have segment information for an interval of time that we haven't
242  # queries simdb for yet (this is necessary due to the asynchronous
243  # nature of the cumulative_segments.xml downloads and the simdb
244  # queries)
245  seg_bins[-1] = min(seg_bins[-1], simdb_query_end_time)
246 
247  db = imr_utils.DataBaseSummary([database], live_time_program = "gstlal_inspiral", veto_segments_name = None, data_segments_name = "statevectorsegments", tmp_path = None, verbose = True)
248 
249  found_inj = db.found_injections_by_instrument_set[frozenset(("H1","L1"))]
250  missed_inj = db.missed_injections_by_instrument_set[frozenset(("H1","L1"))]
251 
252  # Constrain found to be events with a far <= 3.86e-7, roughly once per
253  # 30 days, and sort found injections by time
254  missed_inj.extend([f[1] for f in found_inj if f[0] > 3.86e-7])
255  found_inj = sorted([f for f in found_inj if f[0] <= 3.86e-7], key=lambda f: f[1].geocent_end_time)
256 
257  # Throw away any events that have been downloaded before their segment
258  # information was updated (this is caused by the asynchronous nature of
259  # the cumulative_segments.xml downloads and the simdb queries)
260  found_inj = [f for f in found_inj if f[1].geocent_end_time < seg_bins[-1]]
261  missed_inj = [m for m in missed_inj if m.geocent_end_time < seg_bins[-1]]
262 
263  return found_inj, missed_inj, seglistdicts, seg_bins
264 
265 def plot_range(found_inj, missed_inj, seg_bins, tlohi, dlohi, horizon_history, colors = {'H1': numpy.array((1.0, 0.0, 0.0)), 'L1': numpy.array((0.0, 0.8, 0.0)), 'V1': numpy.array((1.0, 0.0, 1.0))}, fig = None, axes = None):
266 
267  tlo, thi = tlohi
268  dlo, dhi = dlohi
269  if fig is None:
270  fig = plt.figure()
271  if axes is None:
272  axes = fig.add_subplot(111)
273 
274  # FIXME Add number of distance bins as option
275  ndbins = rate.NDBins((rate.LinearBins(dlo, dhi, int(dhi - dlo + 1)), rate.IrregularBins(seg_bins)))
276  vol, err = imr_utils.compute_search_volume_in_bins([f[1] for f in found_inj], missed_inj + [f[1] for f in found_inj], ndbins, lambda sim: (sim.distance, sim.geocent_end_time))
277 
278  x = vol.bins[0].lower()
279  dx = vol.bins[0].upper() - vol.bins[0].lower()
280  y = (vol.array * 3./ (4. * math.pi))**(1./3.)
281  yerr = (1./3.) * (3./(4.*math.pi))**(1./3.)*vol.array**(-2./3.) * err.array
282  yerr[~numpy.isfinite(yerr)] = 0.
283  err_lo = y - 2.0 * yerr
284  err_lo[err_lo<=0] = 0.
285  err_hi = y + 2.0 * yerr
286 
287  axes.bar(x, err_hi-err_lo, bottom=err_lo, color='c', alpha=0.6, label='95\% confidence interval\non range estimated \nfrom injections', width=dx, linewidth=0)
288  for ifo in horizon_history.keys():
289  horizon_times = numpy.array(horizon_history[ifo].keys()).clip(tlo,thi)
290  sensemon_range = numpy.array([horizon_history[ifo][seg]/2.26 for seg in horizon_times])
291  axes.scatter(horizon_times.compress(horizon_times <= horizon_history[ifo].maxkey()), sensemon_range, s = 1, color = colors[ifo], label='%s SenseMon Range' % ifo, alpha=1.0)
292 
293 
294  xticks = numpy.linspace(tlo,thi,9)
295  x_format = tkr.FuncFormatter(lambda x, pos: datetime.datetime(*GPSToUTC(int(x))[:7]).strftime("%Y-%m-%d, %H:%M:%S UTC"))
296  axes.set_ylabel('Range (Mpc)')
297  axes.set_xlim(tlo,thi)
298  axes.set_ylim(0,5*(int(max(err_hi)/5.)+1))
299  axes.xaxis.set_major_formatter(x_format)
300  axes.xaxis.set_ticks(xticks)
301  axes.grid(color=(0.1,0.4,0.5), linewidth=2)
302  return fig, axes
303 
304 def plot_missedfound(found_inj, missed_inj, tlohi, fig = None, axes = None):
305  tlo, thi = tlohi
306  if fig is None:
307  fig = plt.figure()
308  if axes is None:
309  axes = fig.add_subplot(111)
310  xticks = numpy.linspace(tlo,thi,9)
311  x_format = tkr.FuncFormatter(lambda x, pos: datetime.datetime(*GPSToUTC(int(x))[:7]).strftime("%Y-%m-%d, %H:%M:%S UTC"))
312  axes.grid(color=(0.1,0.4,0.5), linewidth=2)
313  axes.semilogy([float(m.get_time_geocent()) for m in missed_inj], [m.eff_dist_l for m in missed_inj], '.k', label=r'Missed (FAR$>$1 / month)')
314  axes.semilogy([float(f[1].get_time_geocent()) for f in found_inj], [f[1].eff_dist_l for f in found_inj], '.b', label=r'Found (FAR$\leq$1 / month)', alpha=0.75)
315  axes.set_ylabel(r'D$_{\mathrm{eff}_{\mathrm{H1}}}$ (Mpc)')
316  axes.xaxis.set_major_formatter(x_format)
317  axes.set_xlim(tlo,thi)
318  axes.xaxis.set_ticks(xticks)
319  return fig, axes
320 
321 def plot_missedfound_range_segments(found_inj, missed_inj, seglistdicts, seg_bins, tlohi, dlohi, horizon_history, colors = {'H1': numpy.array((1.0, 0.0, 0.0)), 'L1': numpy.array((0.0, 0.8, 0.0)), 'V1': numpy.array((1.0, 0.0, 1.0)), 'H1L1': numpy.array((.5, .5, .5))}, fig = None):
322  # FIXME In order to save the figure with the legends included off to
323  # the right, users need to do something along these lines:
324  # fig.savefig(path, additional_artists=[lgd1, lgd2], bbox_inches=matplotlib.transforms.Bbox([[0.,0.],[fig_width+1.5,fig_height]]))
325  # There has to be a better a way, and I think tight_layout() may do it
326  # automatically
327  tlo, thi = tlohi
328  dlo, dhi = dlohi
329 
330  if fig is None:
331  fig = plt.figure()
332  fig, ax1 = plot_missedfound(found_inj, missed_inj, (tlo, thi), fig = fig, axes = fig.add_subplot(311))
333  ax1.xaxis.set_tick_params(labeltop='on', labelbottom='off')
334 
335  # Move the legend out of the plot
336  lgd1 = ax1.legend(numpoints = 1, loc=6, bbox_to_anchor=(1.01,0.5))
337  plt.setp(ax1.get_xticklabels(), rotation = 10.)
338 
339  fig, ax2 = plot_range(found_inj, missed_inj, seg_bins, (tlo, thi), (dlo, dhi), horizon_history, colors = colors, fig = fig, axes = fig.add_subplot(312))
340  ax2.xaxis.set_ticklabels([])
341  # Move the legend out of the plot
342  lgd2 = ax2.legend(loc=6, bbox_to_anchor=(1.01,0.5))
343 
344  fig, ax3 = plotsegments.plot_segments_history(seglistdicts, segments_to_plot = ["state vector", "joint segments"], t_max = thi, length = (thi - tlo), fig = fig, axes = fig.add_subplot(313))
345  plt.setp(ax3.get_xticklabels(), rotation = 10.)
346 
347  return fig, lgd1, lgd2