33 from matplotlib
import figure
34 from matplotlib.backends.backend_agg
import FigureCanvasAgg
as FigureCanvas
35 matplotlib.rcParams.update({
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,
47 from gstlal
import far
48 from gstlal.plots
import util
as plotutil
50 def init_plot(figsize):
53 fig.set_size_inches(figsize)
59 def plot_snr_chi_pdf(rankingstat, instrument, which, snr_max, event_snr = None, event_chisq = None, sngls = None):
62 "background_pdf":
"Noise",
63 "injection_pdf":
"Signal",
64 "zero_lag_pdf":
"Candidates",
73 sngls = numpy.array([sngl[instrument]
for sngl
in sngls
if instrument
in sngl])
77 if which ==
"background_pdf":
79 binnedarray = rankingstat.denominator.densities[
"%s_snr_chi" % instrument]
80 elif which ==
"injection_pdf":
83 binnedarray = rankingstat.numerator.densities[
"snr_chi"]
84 elif which ==
"zero_lag_pdf":
86 binnedarray = rankingstat.zerolag.densities[
"%s_snr_chi" % instrument]
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")
96 raise ValueError(
"invalid which (%s)" % which)
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))
107 warnings.warn(
"%s %s contains NaNs" % (instrument, which))
108 z = numpy.ma.masked_where(numpy.isnan(z), z)
111 xlo, xhi = rankingstat.snr_min, snr_max
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]]
118 fig, axes = init_plot((8., 8. / plotutil.golden_ratio))
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())
125 elif which ==
"injection_pdf":
126 norm = matplotlib.colors.Normalize(vmin = -60., vmax = z.max())
128 elif which ==
"zero_lag_pdf":
129 norm = matplotlib.colors.Normalize(vmin = -30., vmax = z.max())
132 raise ValueError(
"invalid which (%s)" % which)
134 mesh = axes.pcolormesh(x, y, z.T, norm = norm, cmap =
"afmhot", shading =
"gouraud")
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)
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)
145 axes.grid(which =
"both")
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)
158 raise ValueError(tag)
160 fig.tight_layout(pad = .8)
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)
172 def plot_rates(rankingstat):
173 fig = figure.Figure()
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)
185 for instrument, count
in sorted(rankingstat.denominator.triggerrates.counts.items()):
186 labels.append(
"%s\n(%d)" % (instrument, 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")
196 for instrument, rate
in sorted(rankingstat.denominator.triggerrates.densities.items()):
197 labels.append(
"%s\n(%g Hz)" % (instrument, 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)")
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")
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))
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)")
228 fig.tight_layout(pad = .8)
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")
237 binnedarray = snrpdf.get_snr_joint_pdf_binnedarray(instruments, horizon_distances, min_instruments)
240 xlo, xhi = far.RankingStat.snr_min, max_snr
241 mask = binnedarray.bins[(slice(xlo, xhi),) * len(instruments)]
244 instruments = sorted(instruments)
248 if sngls
is not None:
256 sngls = numpy.array([tuple(sngl[instrument][0]
for instrument
in instruments)
for sngl
in sngls
if sorted(sngl) == instruments])
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)
264 x = [coords[m]
for coords, m
in zip(x, mask)]
269 assert not numpy.isnan(z).any()
270 assert not (z < 0.).any()
273 with numpy.errstate(divide =
"ignore"):
276 if len(instruments) == 1:
278 fig, axes = init_plot((5., 5. / plotutil.golden_ratio))
283 if numpy.isinf(z).all():
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])
297 elif len(instruments) == 2:
299 fig, axes = init_plot((5., 4.))
304 if numpy.isinf(z).all():
308 norm = matplotlib.colors.Normalize(vmin = -40., vmax = max(0., z.max()))
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)
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)
319 axes.grid(which =
"both", linestyle =
"-", linewidth = 0.2)
320 fig.colorbar(mesh, ax = axes)
322 axes.set_xlabel(
r"$\mathrm{SNR}_{\mathrm{%s}}$" % instruments[0])
323 axes.set_ylabel(
r"$\mathrm{SNR}_{\mathrm{%s}}$" % instruments[1])
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)
334 def plot_likelihood_ratio_pdf(rankingstatpdf, xlohi, title, which = "noise"):
337 fig, axes = init_plot((8., 8. / plotutil.golden_ratio))
339 if rankingstatpdf.zero_lag_lr_lnpdf.array.any():
340 extincted = rankingstatpdf.new_with_extinction()
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
353 raise ValueError(
"invalid which (%s)" % which)
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")
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)
377 def plot_likelihood_ratio_ccdf(fapfar, xlohi, observed_ln_likelihood_ratios = None, is_open_box = False, ln_likelihood_ratio_markers = None):
382 fig, axes = init_plot((8., 8. / plotutil.golden_ratio))
384 x = numpy.linspace(xlo, xhi, int(math.ceil(xhi - xlo)) * 8)
385 axes.semilogy(x, fapfar.fap_from_rank(x), color =
"k")
387 ylo = fapfar.fap_from_rank(xhi)
388 ylo = 10**math.floor(math.log10(ylo))
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")
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)
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)
412 def plot_horizon_distance_vs_time(rankingstat, tlohi, masses = (1.4, 1.4), tref =
None):
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.))
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))
425 axes.plot(x, y, color = plotutil.colour_from_instruments([instrument]), label =
"%s" % instrument)
427 yhi = max(max(y), yhi)
431 axes.set_xlabel(
"Time From GPS %.2f (s)" % float(tref))
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)