18 from itertools
import chain
23 matplotlib.rcParams.update({
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,
34 from matplotlib
import pyplot
as plt
35 from matplotlib
import ticker
as tkr
38 from lal
import iterutils
39 from lal
import GPSToUTC
41 from ligo.lw
import utils
as ligolw_utils
43 from gstlal
import imr_utils
44 from gstlal.plots
import segments
as plotsegments
45 from gstlal.plots
import util
as plotutil
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":
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":
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]
67 label =
"$%.2f \,\mathrm{s} < t_\mathrm{template} \leq %.2f \,\mathrm{s}$" % (mlo[0], mhi[0])
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())
76 center = numpy.array([v[bin_mid]
for v
in volumes[1]])
77 if (center == 0).all():
79 lo = numpy.array([v[bin_mid]
for v
in volumes[0]])
80 hi = numpy.array([v[bin_mid]
for v
in volumes[2]])
82 yield lo, center, hi, bin_type_to_label(bin_type, bin_lo, bin_mid, bin_hi)
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())
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])
95 yield lo, center, hi, ds, bin_type_to_label(bin_type, bin_lo, bin_mid, bin_hi)
97 def vt_to_range(volume, livetime):
98 return (volume / (4 * math.pi * livetime / 3))**(1./3)
100 def plot_sensitivity_vs_far(volumes, fars, livetime, ifos, bins, bin_type):
102 fig.set_size_inches((8., 8. / plotutil.golden_ratio))
106 mbins = rate.NDBins(bins[1:])
108 for lo, center, hi, label
in volumes_bins_to_range_label(volumes, mbins, bin_type):
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())
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")
125 vol_tix = ax_far.get_yticks()
127 tx.set_yticks(vol_tix)
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)")
133 ax_far.set_title(
"%s Observing (%.2f days)" % (
"".join(sorted(list(ifos))), livetime[ifos]*365.25))
134 fig.tight_layout(pad = .8)
138 def plot_range_vs_far(volumes, fars, livetime, ifos, bins, bin_type):
140 fig.set_size_inches((8., 8. / plotutil.golden_ratio))
141 ax_far_range = fig.gca()
144 mbins = rate.NDBins(bins[1:])
146 for lo, center, hi, label
in volumes_bins_to_range_label(volumes, mbins, bin_type):
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())
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")
165 ax_far_range.set_title(
"%s Observing (%.2f days)" % (
"".join(sorted(list(ifos))), livetime[ifos]*365.25))
166 fig.tight_layout(pad = .8)
170 def plot_sensitivity_vs_snr(volumes, snrs, livetime, ifos, bins, bin_type):
172 fig.set_size_inches((8., 8. / plotutil.golden_ratio))
176 mbins = rate.NDBins(bins[1:])
178 for lo, center, hi, label
in volumes_bins_to_range_label(volumes, mbins, bin_type):
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())
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")
194 vol_tix = ax_snr.get_yticks()
196 tx.set_yticks(vol_tix)
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)")
202 ax_snr.set_title(
"%s Observing (%.2f days)" % (
"".join(sorted(list(ifos))), livetime[ifos]*365.25))
203 fig.tight_layout(pad = .8)
207 def plot_fiducial_efficiency(eff_fids, fiducial_far, ifos, bins, bin_type):
209 fig.set_size_inches((8., 8. / plotutil.golden_ratio))
213 mbins = rate.NDBins(bins[1:])
215 for lo, eff, hi, ds, label
in fiducial_efficiency_to_range_label(eff_fids, mbins, bins[0], bin_type):
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())
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")
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)
235 def parse_sensitivity_docs(database, cumulative_segments_file, simdb_query_end_time):
237 seglistdicts = plotsegments.parse_segments_xml(cumulative_segments_file)
239 seg_bins = [ligotimegps.seconds
for ligotimegps
in sorted(list(chain.from_iterable(seglistdicts[
"joint segments"][
"H1L1"])))]
245 seg_bins[-1] = min(seg_bins[-1], simdb_query_end_time)
247 db =
imr_utils.DataBaseSummary([database], live_time_program =
"gstlal_inspiral", veto_segments_name =
None, data_segments_name =
"statevectorsegments", tmp_path =
None, verbose =
True)
249 found_inj = db.found_injections_by_instrument_set[frozenset((
"H1",
"L1"))]
250 missed_inj = db.missed_injections_by_instrument_set[frozenset((
"H1",
"L1"))]
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)
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]]
263 return found_inj, missed_inj, seglistdicts, seg_bins
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):
272 axes = fig.add_subplot(111)
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))
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
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)
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)
304 def plot_missedfound(found_inj, missed_inj, tlohi, fig = None, axes = 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)
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):
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')
336 lgd1 = ax1.legend(numpoints = 1, loc=6, bbox_to_anchor=(1.01,0.5))
337 plt.setp(ax1.get_xticklabels(), rotation = 10.)
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([])
342 lgd2 = ax2.legend(loc=6, bbox_to_anchor=(1.01,0.5))
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.)
347 return fig, lgd1, lgd2